@camstack/addon-post-analysis 1.2.7 → 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.
@@ -20,7 +20,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  enumerable: true
21
21
  }) : target, mod));
22
22
  //#endregion
23
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
23
+ //#region ../types/dist/event-category-BLcNejAE.mjs
24
24
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
25
25
  EventCategory["SystemBoot"] = "system.boot";
26
26
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -170,9 +170,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
170
170
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
171
171
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
172
172
  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
173
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
177
174
  * progress bar the client reconciles via `recordingExport.getExport`. */
178
175
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -8302,6 +8299,61 @@ function subKindsOf(macro) {
8302
8299
  return out;
8303
8300
  }
8304
8301
  /**
8302
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8303
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8304
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8305
+ * taxonomy surface (timeline, filters, event page).
8306
+ *
8307
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8308
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8309
+ * for the `classes` / `classesExclude` conditions.
8310
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8311
+ * the same class picker, grouped under an Audio header.
8312
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8313
+ * lock / …) for the `sensorKinds` device-event condition.
8314
+ *
8315
+ * Each entry carries `parentKind` so the client can group video subs under
8316
+ * their macro and sensor/control kinds under their category. This surface is
8317
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8318
+ * method, no codegen — so it ships train-free with an addon deploy.
8319
+ */
8320
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8321
+ var NcTaxonomyEntrySchema = object({
8322
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8323
+ kind: string(),
8324
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8325
+ label: string(),
8326
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8327
+ parentKind: string().nullable()
8328
+ });
8329
+ /** The complete NC picker taxonomy — three grouped buckets. */
8330
+ var NcTaxonomySchema = object({
8331
+ videoClasses: array(NcTaxonomyEntrySchema),
8332
+ audioKinds: array(NcTaxonomyEntrySchema),
8333
+ labels: array(NcTaxonomyEntrySchema)
8334
+ });
8335
+ function toEntry(kind, label, parentKind) {
8336
+ return {
8337
+ kind,
8338
+ label,
8339
+ parentKind
8340
+ };
8341
+ }
8342
+ /**
8343
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8344
+ * (macros before their subs), which the client relies on for stable grouping.
8345
+ */
8346
+ function buildNcTaxonomy() {
8347
+ const all = Object.values(EVENT_TAXONOMY);
8348
+ return {
8349
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8350
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8351
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8352
+ };
8353
+ }
8354
+ /** The frozen NC taxonomy, derived once from the taxonomy dictionary. */
8355
+ var NC_TAXONOMY = Object.freeze(buildNcTaxonomy());
8356
+ /**
8305
8357
  * Error types for the safe expression engine. Two distinct classes so callers
8306
8358
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8307
8359
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -13743,94 +13795,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13743
13795
  bundleUrl: string()
13744
13796
  });
13745
13797
  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
13798
  /**
13835
13799
  * Alerts capability — collection-based internal alert system.
13836
13800
  *
@@ -14017,89 +13981,6 @@ method(object({
14017
13981
  password: string()
14018
13982
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
14019
13983
  /**
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
13984
  * Orchestrator-side destination metadata. The orchestrator computes
14104
13985
  * `id = <addonId>:<subId>` from its provider lookup so consumers
14105
13986
  * (admin UI, restore flow) see one canonical key.
@@ -14456,6 +14337,28 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
14456
14337
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
14457
14338
  DeviceType.Camera;
14458
14339
  /**
14340
+ * Identity — preserves literal types for downstream inference.
14341
+ *
14342
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
14343
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
14344
+ * the broader unions declared on `CustomActionSpec`'s default generics.
14345
+ * Shape validity is enforced separately by the `customAction(...)` helper
14346
+ * whose return type is already a `CustomActionSpec<...>`.
14347
+ */
14348
+ function defineCustomActions(spec) {
14349
+ return spec;
14350
+ }
14351
+ function customAction(input, output, options) {
14352
+ return {
14353
+ input,
14354
+ output,
14355
+ kind: options?.kind ?? "query",
14356
+ auth: options?.auth ?? "protected",
14357
+ scope: options?.scope ?? { kind: "system" },
14358
+ ...options?.caller ? { caller: "required" } : {}
14359
+ };
14360
+ }
14361
+ /**
14459
14362
  * `custom-model-registry` — collection cap exposing operator-registered
14460
14363
  * custom detection models. Each provider (today: `addon-model-studio`)
14461
14364
  * contributes a list of `CustomModelDescriptor`s; the hub auto-concatenates
@@ -15453,1193 +15356,1693 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15453
15356
  kind: "mutation",
15454
15357
  auth: "admin"
15455
15358
  });
15456
- var LogLevelSchema = _enum([
15457
- "debug",
15458
- "info",
15459
- "warn",
15460
- "error"
15359
+ /**
15360
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15361
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15362
+ * caps stay wire-compatible without a circular cap→cap import.
15363
+ *
15364
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15365
+ * every transport tier structurally, and failed calls still write usage rows.
15366
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15367
+ */
15368
+ var LlmUsageSchema = object({
15369
+ inputTokens: number(),
15370
+ outputTokens: number()
15371
+ });
15372
+ var LlmErrorCodeSchema = _enum([
15373
+ "timeout",
15374
+ "rate-limited",
15375
+ "auth",
15376
+ "refusal",
15377
+ "bad-request",
15378
+ "unavailable",
15379
+ "no-profile",
15380
+ "budget-exceeded",
15381
+ "adapter-error"
15461
15382
  ]);
15462
- var LogEntrySchema = object({
15463
- timestamp: date(),
15464
- level: LogLevelSchema,
15465
- scope: array(string()),
15383
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15384
+ ok: literal(true),
15385
+ text: string(),
15386
+ model: string(),
15387
+ usage: LlmUsageSchema,
15388
+ truncated: boolean(),
15389
+ latencyMs: number()
15390
+ }), object({
15391
+ ok: literal(false),
15392
+ code: LlmErrorCodeSchema,
15466
15393
  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()
15490
- });
15491
- var MemoryInfoSchema = object({
15492
- percent: number(),
15493
- totalBytes: number(),
15494
- usedBytes: number(),
15495
- availableBytes: number(),
15496
- swapUsedBytes: number(),
15497
- swapTotalBytes: number()
15394
+ retryAfterMs: number().optional()
15395
+ })]);
15396
+ /**
15397
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15398
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15399
+ * notification-output.cap.ts:27-31 precedents).
15400
+ */
15401
+ var LlmImageSchema = object({
15402
+ bytes: _instanceof(Uint8Array),
15403
+ mimeType: string()
15498
15404
  });
15499
- var DiskIoSnapshotSchema = object({
15500
- readBytes: number(),
15501
- writeBytes: number(),
15502
- readOps: number(),
15503
- writeOps: number(),
15504
- timestampMs: number()
15405
+ var LlmGenerateBaseInputSchema = object({
15406
+ /** Collection routing (the notification-output posture). */
15407
+ addonId: string().optional(),
15408
+ /** Explicit profile; else the resolution chain (spec §3). */
15409
+ profileId: string().optional(),
15410
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15411
+ consumer: string(),
15412
+ system: string().optional(),
15413
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15414
+ prompt: string(),
15415
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15416
+ jsonSchema: record(string(), unknown()).optional(),
15417
+ /** Per-call override of the profile default. */
15418
+ maxTokens: number().int().positive().optional(),
15419
+ temperature: number().optional()
15505
15420
  });
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()
15421
+ /**
15422
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15423
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15424
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15425
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15426
+ * this only through the `llm` cap's methods.
15427
+ *
15428
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15429
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15430
+ * watchdog operator decision #3).
15431
+ */
15432
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15433
+ object({
15434
+ kind: literal("catalog"),
15435
+ catalogId: string()
15547
15436
  }),
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()
15437
+ object({
15438
+ kind: literal("url"),
15439
+ url: string(),
15440
+ sha256: string().optional()
15441
+ }),
15442
+ object({
15443
+ kind: literal("path"),
15444
+ path: string()
15445
+ })
15446
+ ]);
15447
+ var ManagedRuntimeConfigSchema = object({
15448
+ /** WHERE the runtime lives — hub or any agent. */
15449
+ nodeId: string(),
15450
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15451
+ engine: _enum(["llama-cpp"]),
15452
+ model: ManagedModelRefSchema,
15453
+ contextSize: number().int().default(4096),
15454
+ /** 0 = CPU-only. */
15455
+ gpuLayers: number().int().default(0),
15456
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15457
+ threads: number().int().optional(),
15458
+ /** Concurrent slots. */
15459
+ parallel: number().int().default(1),
15460
+ /** Else lazy: first generate boots it. */
15461
+ autoStart: boolean().default(false),
15462
+ /** 0 = never; frees RAM after quiet periods. */
15463
+ idleStopMinutes: number().int().default(30)
15576
15464
  });
15577
- var AddonInstanceSchema = object({
15578
- addonId: string(),
15465
+ var LlmRuntimeStatusSchema = object({
15466
+ /** Status is ALWAYS node-qualified. */
15579
15467
  nodeId: string(),
15580
- role: _enum(["hub", "worker"]),
15581
- pid: number(),
15582
15468
  state: _enum([
15583
- "starting",
15584
- "running",
15585
- "stopping",
15586
15469
  "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"
15470
+ "downloading",
15471
+ "starting",
15472
+ "ready",
15473
+ "crashed",
15474
+ "failed"
15600
15475
  ]),
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
15476
  pid: number().optional(),
15633
- reason: string().optional()
15477
+ port: number().optional(),
15478
+ modelPath: string().optional(),
15479
+ modelId: string().optional(),
15480
+ downloadProgress: number().min(0).max(1).optional(),
15481
+ lastError: string().optional(),
15482
+ crashesInWindow: number(),
15483
+ /** Child RSS (sampled best-effort). */
15484
+ memoryBytes: number().optional(),
15485
+ vramBytes: number().optional()
15634
15486
  });
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()
15487
+ var LlmNodeModelSchema = object({
15488
+ file: string(),
15489
+ sizeBytes: number(),
15490
+ catalogId: string().optional(),
15491
+ installedAt: number().optional()
15644
15492
  });
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, {
15493
+ var LlmRuntimeDiskUsageSchema = object({
15494
+ nodeId: string(),
15495
+ modelsBytes: number(),
15496
+ freeBytes: number().optional()
15497
+ });
15498
+ method(LlmGenerateBaseInputSchema.extend({
15499
+ images: array(LlmImageSchema).optional(),
15500
+ runtime: ManagedRuntimeConfigSchema,
15501
+ /** The managed profile's timeout, threaded by the hub provider. */
15502
+ timeoutMs: number().int().positive().optional()
15503
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15646
15504
  kind: "mutation",
15647
15505
  auth: "admin"
15648
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15506
+ }), method(object({}), _void(), {
15649
15507
  kind: "mutation",
15650
15508
  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, {
15509
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15659
15510
  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
- }), {
15511
+ auth: "admin"
15512
+ }), method(object({ file: string() }), _void(), {
15676
15513
  kind: "mutation",
15677
15514
  auth: "admin"
15678
- });
15515
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15679
15516
  /**
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.
15686
- *
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.
15517
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15518
+ * methods concat-fan across providers; single-row methods route to ONE
15519
+ * provider by the `addonId` in the call input (the notification-output
15520
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15521
+ * (hub-placed); the cap stays open for future providers.
15692
15522
  *
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)
15523
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15524
+ * `apiKey` is a password field — providers REDACT it on read and merge on
15525
+ * write; a stored key NEVER round-trips to a client.
15712
15526
  */
15713
- var BrokerStatusSchema$1 = _enum([
15714
- "connected",
15715
- "disconnected",
15716
- "auth-failed",
15717
- "unreachable",
15718
- "tls-error"
15527
+ var LlmProfileKindSchema = _enum([
15528
+ "openai-compatible",
15529
+ "openai",
15530
+ "anthropic",
15531
+ "google",
15532
+ "managed-local"
15719
15533
  ]);
15720
- var BrokerInfoSchema = object({
15534
+ var LlmProfileSchema = object({
15721
15535
  id: string(),
15722
15536
  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()
15537
+ kind: LlmProfileKindSchema,
15538
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15539
+ addonId: string(),
15540
+ enabled: boolean(),
15541
+ /** Vendor model id, or the managed runtime's loaded model. */
15542
+ model: string(),
15543
+ /** Required for openai-compatible; override for cloud kinds. */
15544
+ baseUrl: string().optional(),
15545
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15546
+ apiKey: string().optional(),
15547
+ supportsVision: boolean(),
15548
+ temperature: number().min(0).max(2).optional(),
15549
+ maxTokens: number().int().positive().optional(),
15550
+ timeoutMs: number().int().positive().default(6e4),
15551
+ extraHeaders: record(string(), string()).optional(),
15552
+ /** kind === 'managed-local' only (spec §4). */
15553
+ runtime: ManagedRuntimeConfigSchema.optional()
15732
15554
  });
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()
15555
+ /** ConfigUISchema tree passed through untyped on the wire (the
15556
+ * notification-output `ConfigSchemaPassthrough` precedent at
15557
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15558
+ var ConfigSchemaPassthrough$1 = unknown();
15559
+ var LlmProfileKindDescriptorSchema = object({
15560
+ kind: LlmProfileKindSchema,
15561
+ label: string(),
15562
+ icon: string(),
15563
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15564
+ addonId: string(),
15565
+ configSchema: ConfigSchemaPassthrough$1
15750
15566
  });
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()
15567
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15568
+ var LlmDefaultSchema = object({
15569
+ selector: LlmDefaultSelectorSchema,
15570
+ profileId: string()
15757
15571
  });
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()
15572
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
15573
+ var LlmUsageRollupSchema = object({
15574
+ day: string(),
15575
+ consumer: string(),
15576
+ profileId: string(),
15577
+ calls: number(),
15578
+ okCalls: number(),
15579
+ errorCalls: number(),
15580
+ inputTokens: number(),
15581
+ outputTokens: number(),
15582
+ avgLatencyMs: number()
15774
15583
  });
15775
- var StartEmbeddedResultSchema = object({
15584
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15585
+ var ManagedModelCatalogEntrySchema = object({
15776
15586
  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({
15587
+ label: string(),
15588
+ family: string(),
15589
+ purpose: _enum(["text", "vision"]),
15785
15590
  url: string(),
15786
- hostname: string(),
15787
- port: number(),
15788
- protocol: _enum(["http", "https"])
15591
+ sha256: string(),
15592
+ sizeBytes: number(),
15593
+ quantization: string(),
15594
+ /** Load-time guidance shown in the picker. */
15595
+ minRamBytes: number(),
15596
+ contextSizeDefault: number().int(),
15597
+ /** Vision models: companion projector file. */
15598
+ mmprojUrl: string().optional()
15789
15599
  });
15790
- var NetworkAccessStatusSchema = object({
15791
- connected: boolean(),
15792
- endpoint: NetworkEndpointSchema.nullable(),
15600
+ var LlmRuntimeNodeSchema = object({
15601
+ nodeId: string(),
15602
+ reachable: boolean(),
15603
+ status: LlmRuntimeStatusSchema.optional(),
15604
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15793
15605
  error: string().optional()
15794
15606
  });
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()
15607
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15608
+ var ProfileRefInputSchema = object({
15609
+ addonId: string(),
15610
+ profileId: string()
15815
15611
  });
15816
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
15612
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15613
+ kind: "mutation",
15614
+ auth: "admin"
15615
+ }), method(ProfileRefInputSchema, _void(), {
15616
+ kind: "mutation",
15617
+ auth: "admin"
15618
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15619
+ kind: "mutation",
15620
+ auth: "admin"
15621
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15622
+ selector: LlmDefaultSelectorSchema,
15623
+ profileId: string().nullable()
15624
+ }), _void(), {
15625
+ kind: "mutation",
15626
+ auth: "admin"
15627
+ }), method(object({
15628
+ since: number().optional(),
15629
+ until: number().optional(),
15630
+ consumer: string().optional(),
15631
+ profileId: string().optional()
15632
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15633
+ nodeId: string(),
15634
+ model: ManagedModelRefSchema
15635
+ }), _void(), {
15636
+ kind: "mutation",
15637
+ auth: "admin"
15638
+ }), method(object({
15639
+ nodeId: string(),
15640
+ file: string()
15641
+ }), _void(), {
15642
+ kind: "mutation",
15643
+ auth: "admin"
15644
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15645
+ kind: "mutation",
15646
+ auth: "admin"
15647
+ }), method(ProfileRefInputSchema, _void(), {
15648
+ kind: "mutation",
15649
+ auth: "admin"
15650
+ });
15651
+ var LogLevelSchema = _enum([
15652
+ "debug",
15653
+ "info",
15654
+ "warn",
15655
+ "error"
15656
+ ]);
15657
+ var LogEntrySchema = object({
15658
+ timestamp: date(),
15659
+ level: LogLevelSchema,
15660
+ scope: array(string()),
15661
+ message: string(),
15662
+ meta: record(string(), unknown()).optional(),
15663
+ tags: record(string(), string()).optional()
15664
+ });
15665
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15666
+ scope: array(string()).optional(),
15667
+ level: LogLevelSchema.optional(),
15668
+ since: date().optional(),
15669
+ until: date().optional(),
15670
+ limit: number().optional(),
15671
+ tags: record(string(), string()).optional()
15672
+ }), array(LogEntrySchema).readonly());
15817
15673
  /**
15818
- * notification-outputcanonical, capability-gated notification delivery.
15674
+ * `login-method`collection cap through which auth addons contribute
15675
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15676
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15677
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15678
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15679
+ * procedure aggregates them for the unauthenticated login page.
15819
15680
  *
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
15823
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15824
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15825
- * message to what the kind supports — callers never special-case a service.
15681
+ * A contribution is a discriminated union on `kind`:
15826
15682
  *
15827
- * DESIGN DECISIONS (locked):
15828
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15829
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15830
- * cap. Rationale: the admin UI needs one uniform surface across the
15831
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15832
- * alternative would fork the UI per addon and cannot host the
15833
- * discovery→adopt flow.
15834
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15835
- * the generated cap-mount auto-`concatCollection`-fans them across every
15836
- * registered provider (notifiers addon + HA addon) so one catalog is
15837
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15838
- * `addonId` the generated collection router extracts from the call input.
15839
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15840
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15841
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15842
- * base64 fallback needed.
15683
+ * - `redirect` a declarative button. The login page renders a generic
15684
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15685
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15686
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
15687
+ * login page needs NO change.
15843
15688
  *
15844
- * TODO (deferred, closed-set change separate decision): add
15845
- * `providerKind: 'notify'` so notification providers surface on the unified
15846
- * admin "Integrations" page.
15847
- */
15848
- /**
15849
- * Zentik-derived typed-media enum — the superset across every kind. Each
15850
- * adapter picks what it supports and the degrade engine filters the rest.
15851
- */
15852
- var AttachmentMediaTypeSchema = _enum([
15853
- "image",
15854
- "video",
15855
- "gif",
15856
- "audio",
15857
- "icon"
15858
- ]);
15859
- /**
15860
- * A single attachment. Exactly one of `url` (remote source, most adapters
15861
- * prefer this) or `bytes` (inline source; required for Pushover-style
15862
- * bytes-only kinds) MUST be present the degrade engine expresses a
15863
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
15689
+ * - `widget` a Module-Federation widget the login page mounts (via
15690
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15691
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15692
+ * mechanism kept for future use; no shipped addon uses it on the login
15693
+ * page (the passkey ceremony below runs natively in the shell instead).
15694
+ *
15695
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
15696
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15697
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15698
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15699
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15700
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15701
+ * enrollment state is never leaked pre-auth; visibility is a shell
15702
+ * decision.
15703
+ *
15704
+ * Every contribution carries a `stage`:
15705
+ * - `primary` — shown on the first credentials screen (OIDC /
15706
+ * magic-link buttons; a future usernameless passkey).
15707
+ * - `second-factor` — shown AFTER the password leg, gated on the
15708
+ * returned `factors` (passkey-as-2FA today).
15709
+ *
15710
+ * `mount: skip` — the cap is read server-side by the core auth router
15711
+ * (`registry.getCollection('login-method')`), never mounted as its own
15712
+ * tRPC router.
15864
15713
  */
15865
- var AttachmentSchema = object({
15866
- mediaType: AttachmentMediaTypeSchema,
15867
- url: string().optional(),
15868
- bytes: _instanceof(Uint8Array).optional(),
15869
- mime: string().optional(),
15870
- name: string().optional()
15871
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
15872
- var NotificationFormatSchema = _enum([
15873
- "text",
15874
- "markdown",
15875
- "html"
15714
+ /** When a login method renders in the two-phase login flow. */
15715
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15716
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15717
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15718
+ object({
15719
+ kind: literal("redirect"),
15720
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15721
+ id: string(),
15722
+ /** Operator-facing button label. */
15723
+ label: string(),
15724
+ /** lucide-react icon name. */
15725
+ icon: string().optional(),
15726
+ /** Addon-owned HTTP route the button navigates to (GET). */
15727
+ startUrl: string(),
15728
+ stage: LoginStageEnum
15729
+ }),
15730
+ object({
15731
+ kind: literal("widget"),
15732
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15733
+ id: string(),
15734
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15735
+ addonId: string(),
15736
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15737
+ bundle: string(),
15738
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15739
+ remote: WidgetRemoteSchema,
15740
+ stage: LoginStageEnum
15741
+ }),
15742
+ object({
15743
+ kind: literal("passkey"),
15744
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15745
+ id: string(),
15746
+ /** Operator-facing button label. */
15747
+ label: string(),
15748
+ stage: LoginStageEnum,
15749
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15750
+ rpId: string(),
15751
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15752
+ origin: string().nullable()
15753
+ })
15876
15754
  ]);
15877
- /** A single tap-through action button. */
15878
- var NotificationActionSchema = object({
15879
- id: string(),
15880
- label: string(),
15881
- url: string().optional()
15755
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15756
+ var CpuBreakdownSchema = object({
15757
+ total: number(),
15758
+ user: number(),
15759
+ system: number(),
15760
+ irq: number(),
15761
+ nice: number(),
15762
+ loadAvg: tuple([
15763
+ number(),
15764
+ number(),
15765
+ number()
15766
+ ]),
15767
+ cores: number()
15882
15768
  });
15883
- /**
15884
- * The canonical notification. `body` is the only hard field (Apprise model).
15885
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
15886
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
15887
- * the adapter maps this ordinal onto its native level. `level?` is an
15888
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
15889
- * `priority` for that one target.
15890
- */
15891
- var NotificationSchema = object({
15892
- body: string(),
15893
- title: string().optional(),
15894
- format: NotificationFormatSchema.default("text"),
15895
- priority: number().int().min(1).max(5).default(3),
15896
- level: string().optional(),
15897
- attachments: array(AttachmentSchema).optional(),
15898
- clickUrl: string().optional(),
15899
- actions: array(NotificationActionSchema).optional(),
15900
- sound: string().optional(),
15901
- ttl: number().optional(),
15902
- tag: string().optional(),
15903
- deviceId: number().optional(),
15904
- eventId: string().optional(),
15905
- metadata: record(string(), unknown()).optional()
15769
+ var MemoryInfoSchema = object({
15770
+ percent: number(),
15771
+ totalBytes: number(),
15772
+ usedBytes: number(),
15773
+ availableBytes: number(),
15774
+ swapUsedBytes: number(),
15775
+ swapTotalBytes: number()
15906
15776
  });
15907
- /** One declared native severity/priority level for a kind. */
15908
- var TargetKindLevelSchema = object({
15909
- id: string(),
15910
- label: string(),
15911
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
15912
- ordinal: number().int().min(1).max(5).nullable(),
15913
- flags: object({
15914
- critical: boolean().optional(),
15915
- silent: boolean().optional(),
15916
- noPush: boolean().optional()
15917
- }).optional(),
15918
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15919
- requires: array(string()).optional(),
15920
- description: string().optional()
15777
+ var DiskIoSnapshotSchema = object({
15778
+ readBytes: number(),
15779
+ writeBytes: number(),
15780
+ readOps: number(),
15781
+ writeOps: number(),
15782
+ timestampMs: number()
15921
15783
  });
15922
- /** The full capability block consulted before dispatch. */
15923
- var TargetKindCapsSchema = object({
15924
- attachments: object({
15925
- mediaTypes: array(AttachmentMediaTypeSchema),
15926
- mode: _enum([
15927
- "url",
15928
- "bytes",
15929
- "both"
15930
- ]),
15931
- max: number().int().nonnegative(),
15932
- maxBytes: number().int().positive().optional()
15933
- }),
15934
- /** Max action buttons (0 = none). */
15935
- actions: number().int().nonnegative(),
15936
- levels: array(TargetKindLevelSchema),
15937
- format: array(NotificationFormatSchema),
15938
- clickUrl: boolean(),
15939
- sound: boolean(),
15940
- ttl: boolean(),
15941
- bodyMaxLen: number().int().positive()
15784
+ var NetworkIoSnapshotSchema = object({
15785
+ rxBytes: number(),
15786
+ txBytes: number(),
15787
+ rxPackets: number(),
15788
+ txPackets: number(),
15789
+ rxErrors: number(),
15790
+ txErrors: number(),
15791
+ timestampMs: number()
15942
15792
  });
15943
- /**
15944
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15945
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15946
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
15947
- * the union is large and not meant for runtime validation here; the exported
15948
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15949
- */
15950
- var ConfigSchemaPassthrough$1 = unknown();
15951
- var TargetKindSchema = object({
15952
- kind: string(),
15953
- label: string(),
15954
- icon: string(),
15955
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15956
- addonId: string(),
15957
- configSchema: ConfigSchemaPassthrough$1,
15958
- supportsDiscovery: boolean(),
15959
- caps: TargetKindCapsSchema
15793
+ var MetricsGpuInfoSchema = object({
15794
+ utilization: number(),
15795
+ model: string(),
15796
+ memoryUsedBytes: number(),
15797
+ memoryTotalBytes: number(),
15798
+ temperature: number().nullable()
15960
15799
  });
15961
- /**
15962
- * A persisted target. `config` holds secrets; providers REDACT secret fields
15963
- * (return a presence marker only) when serving `listTargets` — never
15964
- * round-trip a stored secret to the UI.
15965
- */
15966
- var TargetSchema = object({
15967
- id: string(),
15968
- name: string(),
15969
- kind: string(),
15970
- addonId: string(),
15971
- enabled: boolean(),
15972
- config: record(string(), unknown())
15800
+ var ProcessResourceInfoSchema = object({
15801
+ openFds: number(),
15802
+ threadCount: number(),
15803
+ activeHandles: number(),
15804
+ activeRequests: number()
15973
15805
  });
15974
- /** A discovery-surfaced candidate (config is partial + non-secret). */
15975
- var DiscoveredTargetSchema = object({
15976
- kind: string(),
15977
- suggestedName: string(),
15978
- config: record(string(), unknown())
15979
- });
15980
- /** The degrade engine's report — what was resolved / dropped / degraded. */
15981
- var RenderedAsSchema = object({
15982
- level: string(),
15983
- format: NotificationFormatSchema,
15984
- attachmentsSent: number().int().nonnegative(),
15985
- actionsSent: number().int().nonnegative(),
15986
- truncated: boolean(),
15987
- dropped: array(string())
15988
- });
15989
- var SendResultSchema = object({
15990
- success: boolean(),
15991
- error: string().optional(),
15992
- renderedAs: RenderedAsSchema.optional()
15806
+ var PressureAvgsSchema = object({
15807
+ avg10: number(),
15808
+ avg60: number(),
15809
+ avg300: number()
15993
15810
  });
15994
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
15995
- var TestResultSchema = SendResultSchema;
15996
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
15997
- kind: string(),
15998
- config: record(string(), unknown()).optional()
15999
- }), array(DiscoveredTargetSchema)), method(object({
16000
- targetId: string(),
16001
- notification: NotificationSchema
16002
- }), SendResultSchema, { kind: "mutation" }), method(object({
16003
- targetId: string(),
16004
- sample: NotificationSchema.optional()
16005
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16006
- targetId: string(),
16007
- enabled: boolean()
16008
- }), _void(), { kind: "mutation" });
16009
- /**
16010
- * notification-rules — the Notification Center rule surface (P1 core).
16011
- *
16012
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16013
- * (operator decisions D-1/D-2/D-3 are binding):
16014
- *
16015
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16016
- * `notification-center` module), hooked on the durable persistence
16017
- * moments (object-event insert, TrackCloser.closeExpired) with a
16018
- * persisted outbox + retry — never the lossy telemetry bus (D8).
16019
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16020
- * FIRST persisted detection matching the conditions (per-track dedup,
16021
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16022
- * `delivery: 'track-end'` evaluates the finalized track record at close.
16023
- * - DISPATCH stays behind `notification-output` (rules reference targets
16024
- * by id; per-backend params are a passthrough blob capped by the
16025
- * target kind's own caps/degrade engine).
16026
- *
16027
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
16028
- * server-injected caller identity — the first `caller: 'required'`
16029
- * adopter). The P1 condition subset is: devices, classes(+exclude),
16030
- * minConfidence, admin zones (any/all + exclude), weekly schedule
16031
- * windows, and the optional label/identity/plate matchers. User rules,
16032
- * private zones, per-recipient fan-out and the wider condition table are
16033
- * P2+ (see spec §7).
16034
- *
16035
- * All schemas here are the single source of truth — `NcRule` etc. are
16036
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16037
- * schema/interface drift is explicitly not repeated).
16038
- */
16039
- /** D-3: the urgency of a rule — which persistence moment evaluates it. */
16040
- var NcDeliverySchema = _enum(["immediate", "track-end"]);
16041
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
16042
- var NcScheduleSchema = object({
16043
- windows: array(object({
16044
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16045
- days: array(number().int().min(0).max(6)).min(1),
16046
- startMinute: number().int().min(0).max(1439),
16047
- endMinute: number().int().min(0).max(1439)
16048
- })).min(1),
16049
- /** IANA timezone; default = hub host timezone. */
16050
- timezone: string().optional(),
16051
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16052
- invert: boolean().optional()
15811
+ var PressureInfoSchema = object({
15812
+ some: PressureAvgsSchema,
15813
+ full: PressureAvgsSchema.nullable()
16053
15814
  });
16054
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16055
- var NcPlateMatcherSchema = object({
16056
- values: array(string().min(1)).min(1),
16057
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16058
- maxDistance: number().int().min(0).max(3).default(1)
15815
+ var SystemResourceSnapshotSchema = object({
15816
+ cpu: CpuBreakdownSchema,
15817
+ memory: MemoryInfoSchema,
15818
+ gpu: MetricsGpuInfoSchema.nullable(),
15819
+ network: NetworkIoSnapshotSchema,
15820
+ disk: DiskIoSnapshotSchema,
15821
+ pressure: object({
15822
+ cpu: PressureInfoSchema.nullable(),
15823
+ memory: PressureInfoSchema.nullable(),
15824
+ io: PressureInfoSchema.nullable()
15825
+ }),
15826
+ process: ProcessResourceInfoSchema,
15827
+ cpuTemperature: number().nullable(),
15828
+ timestampMs: number()
16059
15829
  });
16060
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16061
- var NcZoneConditionSchema = object({
16062
- ids: array(string().min(1)).min(1),
16063
- /** Quantifier over `ids` — at least one / every one visited. */
16064
- match: _enum(["any", "all"]).default("any")
15830
+ var DiskSpaceInfoSchema = object({
15831
+ path: string(),
15832
+ totalBytes: number(),
15833
+ usedBytes: number(),
15834
+ availableBytes: number(),
15835
+ percent: number()
16065
15836
  });
16066
- /**
16067
- * The P1 condition set — a flat AND of groups; absent group = pass;
16068
- * membership lists are OR within the list (spec §2.3).
16069
- */
16070
- var NcConditionsSchema = object({
16071
- /** Device scope — absent = all devices. */
16072
- devices: array(number()).optional(),
16073
- /** Detector class names (any overlap with the record's class set). */
16074
- classes: array(string().min(1)).optional(),
16075
- /** Veto classes — any overlap fails the rule. */
16076
- classesExclude: array(string().min(1)).optional(),
16077
- /** Minimum detection confidence 0–1 (fails when the record has none). */
16078
- minConfidence: number().min(0).max(1).optional(),
16079
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
16080
- zones: NcZoneConditionSchema.optional(),
16081
- /** Veto zones — any hit fails the rule. */
16082
- zonesExclude: array(string().min(1)).optional(),
15837
+ var PidResourceStatsSchema = object({
15838
+ pid: number(),
15839
+ cpu: number(),
15840
+ memory: number(),
16083
15841
  /**
16084
- * Exact (case-insensitive) match on the record's collapsed `label`
16085
- * (identity name / plate text / subclass).
15842
+ * Private (anonymous) resident bytes the per-process V8 heap + native
15843
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15844
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15845
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15846
+ * Undefined where /proc is unavailable (e.g. macOS).
16086
15847
  */
16087
- labelEquals: array(string().min(1)).optional(),
15848
+ privateBytes: number().optional(),
16088
15849
  /**
16089
- * Identity matcher. P1 boundary: matched against the record's collapsed
16090
- * `label` (the identity display name propagated by the face pipeline) —
16091
- * identity-ID matching rides in P2 when identity ids reach the record.
15850
+ * Shared file-backed resident bytes (Linux RssFile) mmap'd framework/lib
15851
+ * code shared copy-on-write across runners. Undefined on macOS.
16092
15852
  */
16093
- identities: array(string().min(1)).optional(),
16094
- /** Fuzzy plate matcher against the record's `label` (plate text). */
16095
- plates: NcPlateMatcherSchema.optional()
15853
+ sharedBytes: number().optional()
16096
15854
  });
16097
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
16098
- var NcRuleTargetSchema = object({
16099
- /** `notification-output` Target id. */
16100
- targetId: string().min(1),
16101
- /**
16102
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
16103
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16104
- * degrade engine drops what the backend can't render.
16105
- */
16106
- params: record(string(), unknown()).optional()
15855
+ var AddonInstanceSchema = object({
15856
+ addonId: string(),
15857
+ nodeId: string(),
15858
+ role: _enum(["hub", "worker"]),
15859
+ pid: number(),
15860
+ state: _enum([
15861
+ "starting",
15862
+ "running",
15863
+ "stopping",
15864
+ "stopped",
15865
+ "crashed"
15866
+ ]),
15867
+ uptimeSec: number()
16107
15868
  });
16108
- /**
16109
- * Media attachment policy (P1 still-image subset). `best` = the best
16110
- * AVAILABLE media at dispatch time (D-3); `best-matching` (track-end
16111
- * condition-best) is deferred — operator open point.
16112
- */
16113
- var NcMediaPolicySchema = object({ attach: _enum([
16114
- "best",
16115
- "keyFrame",
16116
- "none"
16117
- ]).default("best") });
16118
- /** Throttle cooldown survives restarts (rebuilt from the outbox on boot). */
16119
- var NcThrottleSchema = object({
16120
- cooldownSec: number().int().min(0).max(86400).default(60),
16121
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16122
- scope: _enum(["rule", "rule-device"]).default("rule-device")
15869
+ var NodeProcessSchema = object({
15870
+ pid: number(),
15871
+ ppid: number(),
15872
+ pgid: number(),
15873
+ classification: _enum([
15874
+ "root",
15875
+ "managed",
15876
+ "system",
15877
+ "ghost"
15878
+ ]),
15879
+ /** `$process` addon binding when `managed`, else null. */
15880
+ addonId: string().nullable(),
15881
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15882
+ nodeId: string().nullable(),
15883
+ /** Truncated command line. */
15884
+ command: string(),
15885
+ cpuPercent: number(),
15886
+ memoryRssBytes: number(),
15887
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15888
+ uptimeSec: number(),
15889
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15890
+ orphaned: boolean()
16123
15891
  });
16124
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16125
- var NcRuleInputSchema = object({
16126
- name: string().min(1).max(200),
16127
- enabled: boolean().default(true),
16128
- delivery: NcDeliverySchema,
16129
- conditions: NcConditionsSchema.default({}),
16130
- schedule: NcScheduleSchema.optional(),
16131
- targets: array(NcRuleTargetSchema).min(1),
16132
- media: NcMediaPolicySchema.default({ attach: "best" }),
16133
- throttle: NcThrottleSchema.default({
16134
- cooldownSec: 60,
16135
- scope: "rule-device"
16136
- }),
16137
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16138
- template: object({
16139
- title: string().max(500).optional(),
16140
- body: string().max(2e3).optional()
16141
- }).optional(),
16142
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
16143
- priority: number().int().min(1).max(5).default(3)
15892
+ var KillProcessInputSchema = object({
15893
+ pid: number(),
15894
+ /** Force = SIGKILL. Default is SIGTERM. */
15895
+ force: boolean().optional()
16144
15896
  });
16145
- /** Partial patch for `updateRule` — any subset of the input fields. */
16146
- var NcRulePatchSchema = NcRuleInputSchema.partial();
16147
- /** A persisted rule. */
16148
- var NcRuleSchema = NcRuleInputSchema.extend({
16149
- id: string(),
16150
- /** userId of the admin who created the rule (server-stamped caller). */
16151
- createdBy: string(),
16152
- createdAt: number(),
16153
- updatedAt: number()
15897
+ var KillProcessResultSchema = object({
15898
+ success: boolean(),
15899
+ reason: string().optional(),
15900
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
16154
15901
  });
16155
- var NcTestResultSchema = object({
16156
- recordId: string(),
16157
- recordKind: _enum(["object-event", "track"]),
16158
- deviceId: number(),
16159
- timestamp: number(),
16160
- wouldFire: boolean(),
16161
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
16162
- failedCondition: string().optional(),
16163
- className: string().optional(),
16164
- label: string().optional()
15902
+ var DumpHeapSnapshotInputSchema = object({
15903
+ /** The addon whose runner should dump a heap snapshot. */
15904
+ addonId: string() });
15905
+ var DumpHeapSnapshotResultSchema = object({
15906
+ success: boolean(),
15907
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15908
+ path: string().optional(),
15909
+ /** Process pid that was signalled. */
15910
+ pid: number().optional(),
15911
+ reason: string().optional()
16165
15912
  });
16166
- var NcConditionDescriptorSchema = object({
16167
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
15913
+ var SystemMetricsSchema = object({
15914
+ cpuPercent: number(),
15915
+ memoryPercent: number(),
15916
+ memoryUsedMB: number(),
15917
+ memoryTotalMB: number(),
15918
+ diskPercent: number().optional(),
15919
+ temperature: number().optional(),
15920
+ gpuPercent: number().optional(),
15921
+ gpuMemoryPercent: number().optional()
15922
+ });
15923
+ 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, {
15924
+ kind: "mutation",
15925
+ auth: "admin"
15926
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15927
+ kind: "mutation",
15928
+ auth: "admin"
15929
+ });
15930
+ method(object({
15931
+ sourceUrl: string(),
15932
+ metadata: ModelConvertMetadataSchema,
15933
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15934
+ calibrationRef: string().optional(),
15935
+ sessionId: string().optional()
15936
+ }), ConvertResultSchema, {
15937
+ kind: "mutation",
15938
+ auth: "admin",
15939
+ timeoutMs: 6e5
15940
+ });
15941
+ method(object({
15942
+ nodeId: string(),
15943
+ modelId: string(),
15944
+ format: _enum(MODEL_FORMATS),
15945
+ entry: ModelCatalogEntrySchema
15946
+ }), object({
15947
+ ok: boolean(),
15948
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15949
+ sha256: string(),
15950
+ bytes: number(),
15951
+ /** The target node's modelsDir the artifact landed in. */
15952
+ path: string()
15953
+ }), {
15954
+ kind: "mutation",
15955
+ auth: "admin"
15956
+ });
15957
+ /**
15958
+ * `mqtt-broker` — broker-registry cap.
15959
+ *
15960
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15961
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15962
+ * and (b) the connection details a consumer addon needs to spin up
15963
+ * its OWN `mqtt.js` client.
15964
+ *
15965
+ * Why: pub/sub routing over the system event-bus loses fidelity
15966
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15967
+ * refcount bookkeeping that addons would rather own themselves. The
15968
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15969
+ * features anyway — give it the connection config, get out of the way.
15970
+ *
15971
+ * Consumer flow:
15972
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15973
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15974
+ * client.subscribe('zigbee2mqtt/+')
15975
+ *
15976
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
15977
+ * cloud bridge). The "embedded" entry (when present) is just another
15978
+ * broker in the registry — its lifecycle is owned by the addon that
15979
+ * spawned it.
15980
+ */
15981
+ var BrokerKindSchema = _enum(["external", "embedded"]);
15982
+ /**
15983
+ * Broker live-probe status.
15984
+ *
15985
+ * - `connected` — last probe completed a clean CONNACK
15986
+ * - `disconnected` — no probe has run yet (cold cache)
15987
+ * - `auth-failed` — CONNACK refused with auth error (RC 4 / 5)
15988
+ * - `unreachable` — TCP connect timed out / refused
15989
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15990
+ */
15991
+ var BrokerStatusSchema$1 = _enum([
15992
+ "connected",
15993
+ "disconnected",
15994
+ "auth-failed",
15995
+ "unreachable",
15996
+ "tls-error"
15997
+ ]);
15998
+ var BrokerInfoSchema = object({
16168
15999
  id: string(),
16169
- group: _enum([
16170
- "scope",
16171
- "class",
16172
- "zones",
16173
- "quality",
16174
- "label",
16175
- "schedule"
16176
- ]),
16000
+ name: string(),
16001
+ url: string(),
16002
+ kind: BrokerKindSchema,
16003
+ status: BrokerStatusSchema$1,
16004
+ latencyMs: number().nullable(),
16005
+ error: string().optional(),
16006
+ /** Embedded brokers only: number of MQTT clients currently connected. */
16007
+ connectedClients: number().int().nonnegative().optional(),
16008
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
16009
+ lastCheckedAt: number().optional()
16010
+ });
16011
+ /**
16012
+ * Connection details — what a consumer needs to call
16013
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
16014
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
16015
+ * instead of stuffing creds into the URL (which leaks them into logs).
16016
+ */
16017
+ var BrokerConnectionDetailsSchema = object({
16018
+ url: string(),
16019
+ username: string().optional(),
16020
+ password: string().optional(),
16021
+ /**
16022
+ * Suggested prefix for `clientId`. Each consumer should suffix this
16023
+ * with its own discriminator (addon id, instance id) so reconnects
16024
+ * don't kick each other off (MQTT spec: clientId must be unique per
16025
+ * broker).
16026
+ */
16027
+ clientIdPrefix: string().optional()
16028
+ });
16029
+ var AddBrokerInputSchema = object({
16030
+ name: string().min(1),
16031
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
16032
+ username: string().optional(),
16033
+ password: string().optional(),
16034
+ clientIdPrefix: string().optional()
16035
+ });
16036
+ var AddBrokerResultSchema = object({ id: string() });
16037
+ var IdInputSchema = object({ id: string() });
16038
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
16039
+ ok: literal(true),
16040
+ latencyMs: number()
16041
+ }), object({
16042
+ ok: literal(false),
16043
+ error: string()
16044
+ })]);
16045
+ var StartEmbeddedInputSchema = object({
16046
+ port: number().int().min(1).max(65535).default(1883),
16047
+ /** Allow anonymous connect (no username/password). Default: false. */
16048
+ allowAnonymous: boolean().default(false),
16049
+ /** Optional shared username/password for clients. */
16050
+ username: string().optional(),
16051
+ password: string().optional()
16052
+ });
16053
+ var StartEmbeddedResultSchema = object({
16054
+ id: string(),
16055
+ url: string()
16056
+ });
16057
+ var StatusSchema = object({
16058
+ brokerCount: number(),
16059
+ embeddedRunning: boolean()
16060
+ });
16061
+ 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);
16062
+ var NetworkEndpointSchema = object({
16063
+ url: string(),
16064
+ hostname: string(),
16065
+ port: number(),
16066
+ protocol: _enum(["http", "https"])
16067
+ });
16068
+ var NetworkAccessStatusSchema = object({
16069
+ connected: boolean(),
16070
+ endpoint: NetworkEndpointSchema.nullable(),
16071
+ error: string().optional()
16072
+ });
16073
+ /**
16074
+ * Optional, richer endpoint shape returned by providers that expose
16075
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
16076
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16077
+ * the originating provider config (mode + sourcePort) so the
16078
+ * orchestrator UI can label rows distinctly. Providers that expose only
16079
+ * one endpoint just omit `listEndpoints` from their provider impl.
16080
+ */
16081
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16082
+ /**
16083
+ * Stable id within the provider — typically `<mode>-<sourcePort>` so
16084
+ * the orchestrator can dedupe across `listEndpoints` polls.
16085
+ */
16086
+ id: string(),
16087
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16177
16088
  label: string(),
16178
- /** Editor widget the UI renders never hardcode per-condition forms. */
16179
- valueType: _enum([
16180
- "deviceIdList",
16181
- "stringList",
16182
- "number01",
16183
- "zoneSelection",
16184
- "zoneIdList",
16185
- "schedule",
16186
- "plateMatcher"
16187
- ]),
16188
- operator: _enum([
16189
- "in",
16190
- "notIn",
16191
- "anyOf",
16192
- "allOf",
16193
- "gte",
16194
- "fuzzyIn",
16195
- "withinSchedule"
16196
- ]),
16197
- /** Which delivery kinds the condition applies to. */
16198
- appliesTo: array(NcDeliverySchema),
16199
- phase: string(),
16089
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16090
+ mode: string().optional(),
16091
+ /** Originating local port the ingress fronts (informational). */
16092
+ sourcePort: number().optional()
16093
+ });
16094
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16095
+ /**
16096
+ * notification-output — canonical, capability-gated notification delivery.
16097
+ *
16098
+ * Apprise-derived model (see
16099
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16100
+ * callers emit ONE canonical `Notification`; each provider declares a
16101
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
16102
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
16103
+ * message to what the kind supports — callers never special-case a service.
16104
+ *
16105
+ * DESIGN DECISIONS (locked):
16106
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
16107
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
16108
+ * cap. Rationale: the admin UI needs one uniform surface across the
16109
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
16110
+ * alternative would fork the UI per addon and cannot host the
16111
+ * discovery→adopt flow.
16112
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
16113
+ * the generated cap-mount auto-`concatCollection`-fans them across every
16114
+ * registered provider (notifiers addon + HA addon) so one catalog is
16115
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
16116
+ * `addonId` the generated collection router extracts from the call input.
16117
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
16118
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
16119
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
16120
+ * base64 fallback needed.
16121
+ *
16122
+ * TODO (deferred, closed-set change — separate decision): add
16123
+ * `providerKind: 'notify'` so notification providers surface on the unified
16124
+ * admin "Integrations" page.
16125
+ */
16126
+ /**
16127
+ * Zentik-derived typed-media enum — the superset across every kind. Each
16128
+ * adapter picks what it supports and the degrade engine filters the rest.
16129
+ */
16130
+ var AttachmentMediaTypeSchema = _enum([
16131
+ "image",
16132
+ "video",
16133
+ "gif",
16134
+ "audio",
16135
+ "icon"
16136
+ ]);
16137
+ /**
16138
+ * A single attachment. Exactly one of `url` (remote source, most adapters
16139
+ * prefer this) or `bytes` (inline source; required for Pushover-style
16140
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
16141
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
16142
+ */
16143
+ var AttachmentSchema = object({
16144
+ mediaType: AttachmentMediaTypeSchema,
16145
+ url: string().optional(),
16146
+ bytes: _instanceof(Uint8Array).optional(),
16147
+ mime: string().optional(),
16148
+ name: string().optional()
16149
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16150
+ var NotificationFormatSchema = _enum([
16151
+ "text",
16152
+ "markdown",
16153
+ "html"
16154
+ ]);
16155
+ /** A single tap-through action button. */
16156
+ var NotificationActionSchema = object({
16157
+ id: string(),
16158
+ label: string(),
16159
+ url: string().optional()
16160
+ });
16161
+ /**
16162
+ * The canonical notification. `body` is the only hard field (Apprise model).
16163
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16164
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16165
+ * the adapter maps this ordinal onto its native level. `level?` is an
16166
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16167
+ * `priority` for that one target.
16168
+ */
16169
+ var NotificationSchema = object({
16170
+ body: string(),
16171
+ title: string().optional(),
16172
+ format: NotificationFormatSchema.default("text"),
16173
+ priority: number().int().min(1).max(5).default(3),
16174
+ level: string().optional(),
16175
+ attachments: array(AttachmentSchema).optional(),
16176
+ clickUrl: string().optional(),
16177
+ actions: array(NotificationActionSchema).optional(),
16178
+ sound: string().optional(),
16179
+ ttl: number().optional(),
16180
+ tag: string().optional(),
16181
+ deviceId: number().optional(),
16182
+ eventId: string().optional(),
16183
+ metadata: record(string(), unknown()).optional()
16184
+ });
16185
+ /** One declared native severity/priority level for a kind. */
16186
+ var TargetKindLevelSchema = object({
16187
+ id: string(),
16188
+ label: string(),
16189
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16190
+ ordinal: number().int().min(1).max(5).nullable(),
16191
+ flags: object({
16192
+ critical: boolean().optional(),
16193
+ silent: boolean().optional(),
16194
+ noPush: boolean().optional()
16195
+ }).optional(),
16196
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16197
+ requires: array(string()).optional(),
16200
16198
  description: string().optional()
16201
16199
  });
16200
+ /** The full capability block consulted before dispatch. */
16201
+ var TargetKindCapsSchema = object({
16202
+ attachments: object({
16203
+ mediaTypes: array(AttachmentMediaTypeSchema),
16204
+ mode: _enum([
16205
+ "url",
16206
+ "bytes",
16207
+ "both"
16208
+ ]),
16209
+ max: number().int().nonnegative(),
16210
+ maxBytes: number().int().positive().optional()
16211
+ }),
16212
+ /** Max action buttons (0 = none). */
16213
+ actions: number().int().nonnegative(),
16214
+ levels: array(TargetKindLevelSchema),
16215
+ format: array(NotificationFormatSchema),
16216
+ clickUrl: boolean(),
16217
+ sound: boolean(),
16218
+ ttl: boolean(),
16219
+ bodyMaxLen: number().int().positive()
16220
+ });
16202
16221
  /**
16203
- * The P1 condition surface as data served by `getConditionCatalog` so
16204
- * rule editors render from the catalog, not hardcoded forms (spec §4.2).
16222
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16223
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16224
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
16225
+ * the union is large and not meant for runtime validation here; the exported
16226
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16205
16227
  */
16206
- var NC_CONDITION_CATALOG = [
16207
- {
16208
- id: "devices",
16209
- group: "scope",
16210
- label: "Cameras",
16211
- valueType: "deviceIdList",
16212
- operator: "in",
16213
- appliesTo: ["immediate", "track-end"],
16214
- phase: "P1",
16215
- description: "Restrict the rule to these devices; absent = all devices."
16216
- },
16217
- {
16218
- id: "classes",
16219
- group: "class",
16220
- label: "Object classes",
16221
- valueType: "stringList",
16222
- operator: "in",
16223
- appliesTo: ["immediate", "track-end"],
16224
- phase: "P1",
16225
- description: "Any overlap with the detection class set passes."
16226
- },
16227
- {
16228
- id: "classesExclude",
16229
- group: "class",
16230
- label: "Excluded classes",
16231
- valueType: "stringList",
16232
- operator: "notIn",
16233
- appliesTo: ["immediate", "track-end"],
16234
- phase: "P1"
16235
- },
16236
- {
16237
- id: "minConfidence",
16238
- group: "quality",
16239
- label: "Minimum confidence",
16240
- valueType: "number01",
16241
- operator: "gte",
16242
- appliesTo: ["immediate", "track-end"],
16243
- phase: "P1"
16244
- },
16245
- {
16246
- id: "zones",
16247
- group: "zones",
16248
- label: "Zones",
16249
- valueType: "zoneSelection",
16250
- operator: "anyOf",
16251
- appliesTo: ["immediate", "track-end"],
16252
- phase: "P1",
16253
- description: "Admin zone ids; quantifier any/all over the visited set."
16254
- },
16255
- {
16256
- id: "zonesExclude",
16257
- group: "zones",
16258
- label: "Excluded zones",
16259
- valueType: "zoneIdList",
16260
- operator: "notIn",
16261
- appliesTo: ["immediate", "track-end"],
16262
- phase: "P1"
16263
- },
16264
- {
16265
- id: "labelEquals",
16266
- group: "label",
16267
- label: "Label equals",
16268
- valueType: "stringList",
16269
- operator: "in",
16270
- appliesTo: ["immediate", "track-end"],
16271
- phase: "P1",
16272
- description: "Exact match on the collapsed label (identity / plate / subclass)."
16273
- },
16274
- {
16275
- id: "identities",
16276
- group: "label",
16277
- label: "Identities",
16278
- valueType: "stringList",
16279
- operator: "in",
16280
- appliesTo: ["immediate", "track-end"],
16281
- phase: "P1",
16282
- description: "P1: matched against the identity display name on the record label."
16283
- },
16284
- {
16285
- id: "plates",
16286
- group: "label",
16287
- label: "License plates",
16288
- valueType: "plateMatcher",
16289
- operator: "fuzzyIn",
16290
- appliesTo: ["immediate", "track-end"],
16291
- phase: "P1",
16292
- description: "Levenshtein-tolerant match against the plate text."
16293
- },
16294
- {
16295
- id: "schedule",
16296
- group: "schedule",
16297
- label: "Schedule",
16298
- valueType: "schedule",
16299
- operator: "withinSchedule",
16300
- appliesTo: ["immediate", "track-end"],
16301
- phase: "P1",
16302
- description: "Weekly activation windows (invertible); absent = always active."
16303
- }
16304
- ];
16305
- var notificationRulesCapability = {
16306
- name: "notification-rules",
16307
- scope: "system",
16308
- mode: "singleton",
16309
- methods: {
16310
- listRules: method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }),
16311
- getRule: method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }),
16312
- createRule: method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
16313
- kind: "mutation",
16314
- auth: "admin",
16315
- caller: "required"
16316
- }),
16317
- updateRule: method(object({
16318
- ruleId: string(),
16319
- patch: NcRulePatchSchema
16320
- }), object({ rule: NcRuleSchema }), {
16321
- kind: "mutation",
16322
- auth: "admin",
16323
- caller: "required"
16324
- }),
16325
- deleteRule: method(object({ ruleId: string() }), object({ success: literal(true) }), {
16326
- kind: "mutation",
16327
- auth: "admin"
16328
- }),
16329
- setRuleEnabled: method(object({
16330
- ruleId: string(),
16331
- enabled: boolean()
16332
- }), object({ success: literal(true) }), {
16333
- kind: "mutation",
16334
- auth: "admin"
16335
- }),
16336
- /**
16337
- * Dry-run a rule against recently persisted records (object events for
16338
- * `immediate`, closed tracks for `track-end`). Mutation kind only to
16339
- * carry the full rule object safely; no side effects.
16340
- */
16341
- testRule: method(object({
16342
- rule: NcRuleInputSchema,
16343
- lookbackMinutes: number().int().min(1).max(1440).default(60)
16344
- }), object({ results: array(NcTestResultSchema) }), {
16345
- kind: "mutation",
16346
- auth: "admin"
16347
- }),
16348
- getConditionCatalog: method(object({}), object({ catalog: array(NcConditionDescriptorSchema) }))
16349
- }
16350
- };
16228
+ var ConfigSchemaPassthrough = unknown();
16229
+ var TargetKindSchema = object({
16230
+ kind: string(),
16231
+ label: string(),
16232
+ icon: string(),
16233
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16234
+ addonId: string(),
16235
+ configSchema: ConfigSchemaPassthrough,
16236
+ supportsDiscovery: boolean(),
16237
+ caps: TargetKindCapsSchema
16238
+ });
16351
16239
  /**
16352
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
16353
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
16354
- * caps stay wire-compatible without a circular cap→cap import.
16355
- *
16356
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
16357
- * every transport tier structurally, and failed calls still write usage rows.
16358
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
16240
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16241
+ * (return a presence marker only) when serving `listTargets` — never
16242
+ * round-trip a stored secret to the UI.
16359
16243
  */
16360
- var LlmUsageSchema = object({
16361
- inputTokens: number(),
16362
- outputTokens: number()
16244
+ var TargetSchema = object({
16245
+ id: string(),
16246
+ name: string(),
16247
+ kind: string(),
16248
+ addonId: string(),
16249
+ enabled: boolean(),
16250
+ config: record(string(), unknown())
16363
16251
  });
16364
- var LlmErrorCodeSchema = _enum([
16365
- "timeout",
16366
- "rate-limited",
16367
- "auth",
16368
- "refusal",
16369
- "bad-request",
16370
- "unavailable",
16371
- "no-profile",
16372
- "budget-exceeded",
16373
- "adapter-error"
16374
- ]);
16375
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
16376
- ok: literal(true),
16377
- text: string(),
16378
- model: string(),
16379
- usage: LlmUsageSchema,
16252
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16253
+ var DiscoveredTargetSchema = object({
16254
+ kind: string(),
16255
+ suggestedName: string(),
16256
+ config: record(string(), unknown())
16257
+ });
16258
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
16259
+ var RenderedAsSchema = object({
16260
+ level: string(),
16261
+ format: NotificationFormatSchema,
16262
+ attachmentsSent: number().int().nonnegative(),
16263
+ actionsSent: number().int().nonnegative(),
16380
16264
  truncated: boolean(),
16381
- latencyMs: number()
16382
- }), object({
16383
- ok: literal(false),
16384
- code: LlmErrorCodeSchema,
16385
- message: string(),
16386
- retryAfterMs: number().optional()
16387
- })]);
16265
+ dropped: array(string())
16266
+ });
16267
+ var SendResultSchema = object({
16268
+ success: boolean(),
16269
+ error: string().optional(),
16270
+ renderedAs: RenderedAsSchema.optional()
16271
+ });
16272
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16273
+ var TestResultSchema = SendResultSchema;
16274
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16275
+ kind: string(),
16276
+ config: record(string(), unknown()).optional()
16277
+ }), array(DiscoveredTargetSchema)), method(object({
16278
+ targetId: string(),
16279
+ notification: NotificationSchema
16280
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16281
+ targetId: string(),
16282
+ sample: NotificationSchema.optional()
16283
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16284
+ targetId: string(),
16285
+ enabled: boolean()
16286
+ }), _void(), { kind: "mutation" });
16287
+ /**
16288
+ * notification-rules — the Notification Center rule surface (P1 core).
16289
+ *
16290
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16291
+ * (operator decisions D-1/D-2/D-3 are binding):
16292
+ *
16293
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16294
+ * `notification-center` module), hooked on the durable persistence
16295
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16296
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16297
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16298
+ * FIRST persisted detection matching the conditions (per-track dedup,
16299
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16300
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16301
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16302
+ * by id; per-backend params are a passthrough blob capped by the
16303
+ * target kind's own caps/degrade engine).
16304
+ *
16305
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16306
+ * server-injected caller identity — the first `caller: 'required'`
16307
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16308
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16309
+ * windows, and the optional label/identity/plate matchers. User rules,
16310
+ * private zones, per-recipient fan-out and the wider condition table are
16311
+ * P2+ (see spec §7).
16312
+ *
16313
+ * All schemas here are the single source of truth — `NcRule` etc. are
16314
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16315
+ * schema/interface drift is explicitly not repeated).
16316
+ */
16388
16317
  /**
16389
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
16390
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
16391
- * notification-output.cap.ts:27-31 precedents).
16318
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
16319
+ * The value maps 1:1 onto the evaluated record kind:
16320
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16321
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16322
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16323
+ * change of a LINKED device, one row per linked camera)
16324
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16325
+ * delivery / pick-up)
16326
+ *
16327
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16328
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16329
+ * this one field keeps the schema additive — a rule still declares exactly
16330
+ * one trigger.
16392
16331
  */
16393
- var LlmImageSchema = object({
16394
- bytes: _instanceof(Uint8Array),
16395
- mimeType: string()
16332
+ var NcDeliverySchema = _enum([
16333
+ "immediate",
16334
+ "track-end",
16335
+ "device-event",
16336
+ "package-event"
16337
+ ]);
16338
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16339
+ var NcScheduleSchema = object({
16340
+ windows: array(object({
16341
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16342
+ days: array(number().int().min(0).max(6)).min(1),
16343
+ startMinute: number().int().min(0).max(1439),
16344
+ endMinute: number().int().min(0).max(1439)
16345
+ })).min(1),
16346
+ /** IANA timezone; default = hub host timezone. */
16347
+ timezone: string().optional(),
16348
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16349
+ invert: boolean().optional()
16396
16350
  });
16397
- var LlmGenerateBaseInputSchema = object({
16398
- /** Collection routing (the notification-output posture). */
16399
- addonId: string().optional(),
16400
- /** Explicit profile; else the resolution chain (spec §3). */
16401
- profileId: string().optional(),
16402
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
16403
- consumer: string(),
16404
- system: string().optional(),
16405
- /** v1: single-turn. `messages[]` is a v2 additive field. */
16406
- prompt: string(),
16407
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
16408
- jsonSchema: record(string(), unknown()).optional(),
16409
- /** Per-call override of the profile default. */
16410
- maxTokens: number().int().positive().optional(),
16411
- temperature: number().optional()
16351
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16352
+ var NcPlateMatcherSchema = object({
16353
+ values: array(string().min(1)).min(1),
16354
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16355
+ maxDistance: number().int().min(0).max(3).default(1)
16412
16356
  });
16413
16357
  /**
16414
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
16415
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
16416
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
16417
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
16418
- * this only through the `llm` cap's methods.
16419
- *
16420
- * One running llama-server child per node in v1 (models are RAM-heavy).
16421
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
16422
- * watchdog operator decision #3).
16358
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16359
+ * occupancy edge for a device optionally narrowed to a single admin
16360
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16361
+ * - `became-occupied` (default) count crossed 0 `count`
16362
+ * - `became-free` — count crossed `count` below it
16363
+ * - `>=` / `<=` — count is at/over or at/under `count`
16364
+ * `sustainSeconds` requires the condition hold continuously that long
16365
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16366
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16367
+ * the condition never matches. Confirmed edge-state survives addon restarts
16368
+ * (declared SQLite collection, reseeded on boot).
16423
16369
  */
16424
- var ManagedModelRefSchema = discriminatedUnion("kind", [
16425
- object({
16426
- kind: literal("catalog"),
16427
- catalogId: string()
16428
- }),
16429
- object({
16430
- kind: literal("url"),
16431
- url: string(),
16432
- sha256: string().optional()
16433
- }),
16434
- object({
16435
- kind: literal("path"),
16436
- path: string()
16437
- })
16438
- ]);
16439
- var ManagedRuntimeConfigSchema = object({
16440
- /** WHERE the runtime lives — hub or any agent. */
16441
- nodeId: string(),
16442
- /** Closed for v1; 'ollama' is a v2 candidate. */
16443
- engine: _enum(["llama-cpp"]),
16444
- model: ManagedModelRefSchema,
16445
- contextSize: number().int().default(4096),
16446
- /** 0 = CPU-only. */
16447
- gpuLayers: number().int().default(0),
16448
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16449
- threads: number().int().optional(),
16450
- /** Concurrent slots. */
16451
- parallel: number().int().default(1),
16452
- /** Else lazy: first generate boots it. */
16453
- autoStart: boolean().default(false),
16454
- /** 0 = never; frees RAM after quiet periods. */
16455
- idleStopMinutes: number().int().default(30)
16370
+ var NcOccupancyConditionSchema = object({
16371
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16372
+ zoneId: string().optional(),
16373
+ /** Object class to count; absent = any class. */
16374
+ className: string().optional(),
16375
+ op: _enum([
16376
+ "became-occupied",
16377
+ "became-free",
16378
+ ">=",
16379
+ "<="
16380
+ ]).default("became-occupied"),
16381
+ count: number().int().min(0).default(1),
16382
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16456
16383
  });
16457
- var LlmRuntimeStatusSchema = object({
16458
- /** Status is ALWAYS node-qualified. */
16459
- nodeId: string(),
16460
- state: _enum([
16461
- "stopped",
16462
- "downloading",
16463
- "starting",
16464
- "ready",
16465
- "crashed",
16466
- "failed"
16467
- ]),
16468
- pid: number().optional(),
16469
- port: number().optional(),
16470
- modelPath: string().optional(),
16471
- modelId: string().optional(),
16472
- downloadProgress: number().min(0).max(1).optional(),
16473
- lastError: string().optional(),
16474
- crashesInWindow: number(),
16475
- /** Child RSS (sampled best-effort). */
16476
- memoryBytes: number().optional(),
16477
- vramBytes: number().optional()
16384
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16385
+ var NcZoneConditionSchema = object({
16386
+ ids: array(string().min(1)).min(1),
16387
+ /** Quantifier over `ids` — at least one / every one visited. */
16388
+ match: _enum(["any", "all"]).default("any")
16478
16389
  });
16479
- var LlmNodeModelSchema = object({
16480
- file: string(),
16481
- sizeBytes: number(),
16482
- catalogId: string().optional(),
16483
- installedAt: number().optional()
16390
+ /**
16391
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16392
+ * membership lists are OR within the list (spec §2.3).
16393
+ */
16394
+ var NcConditionsSchema = object({
16395
+ /** Device scope — absent = all devices. */
16396
+ devices: array(number()).optional(),
16397
+ /** Detector class names (any overlap with the record's class set). */
16398
+ classes: array(string().min(1)).optional(),
16399
+ /** Veto classes — any overlap fails the rule. */
16400
+ classesExclude: array(string().min(1)).optional(),
16401
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16402
+ minConfidence: number().min(0).max(1).optional(),
16403
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16404
+ zones: NcZoneConditionSchema.optional(),
16405
+ /** Veto zones — any hit fails the rule. */
16406
+ zonesExclude: array(string().min(1)).optional(),
16407
+ /**
16408
+ * Exact (case-insensitive) match on the record's collapsed `label`
16409
+ * (identity name / plate text / subclass).
16410
+ */
16411
+ labelEquals: array(string().min(1)).optional(),
16412
+ /**
16413
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16414
+ * `label` (the identity display name propagated by the face pipeline) —
16415
+ * identity-ID matching rides in P2 when identity ids reach the record.
16416
+ */
16417
+ identities: array(string().min(1)).optional(),
16418
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16419
+ plates: NcPlateMatcherSchema.optional(),
16420
+ /**
16421
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16422
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16423
+ * identity display name). A record with NO label passes (nothing to
16424
+ * exclude), unlike the include variant which fails on an absent label.
16425
+ */
16426
+ identitiesExclude: array(string().min(1)).optional(),
16427
+ /**
16428
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16429
+ * TRACK-END only: importance is scored at track close, so it does not exist
16430
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16431
+ * close the value is threaded via the close-time info (the `Track` clone is
16432
+ * captured before the DB row is updated, so it would otherwise read stale).
16433
+ * Fails when the record carries no importance (never guess quality — the
16434
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16435
+ */
16436
+ minImportance: number().min(0).max(1).optional(),
16437
+ /**
16438
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16439
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16440
+ * lifespan, so a dwell condition never matches immediate delivery
16441
+ * (documented choice — the object-event record carries no `firstSeen`,
16442
+ * so dwell cannot be computed from what the subject actually carries).
16443
+ */
16444
+ minDwellSeconds: number().min(0).optional(),
16445
+ /**
16446
+ * Detection provenance filter. `any` (default / absent) matches every
16447
+ * source; otherwise the subject's source must equal it. Legacy records
16448
+ * with no stamped source are treated as `pipeline`. The union spans both
16449
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16450
+ * tracks carry `sensor`.
16451
+ */
16452
+ source: _enum([
16453
+ "pipeline",
16454
+ "onboard",
16455
+ "sensor",
16456
+ "any"
16457
+ ]).optional(),
16458
+ /**
16459
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16460
+ * detector `minConfidence` (that gates the object-detection score; this
16461
+ * gates the recognition/OCR match score). Fails when the subject carries
16462
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16463
+ * lives on the recognition result and reaches the subject at track close.
16464
+ *
16465
+ * What it measures precisely (plumbed at track close — the closer threads
16466
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16467
+ * `importance`): the BEST recognition match confidence observed for the
16468
+ * label the track carries at close — for a face, the peak cosine similarity
16469
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16470
+ * for a plate, the peak OCR read score of the best-held plate
16471
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16472
+ * one track the higher of the two is used. A track that ended with no
16473
+ * confident identity/plate match carries no value, so the condition fails
16474
+ * closed for it (an un-recognized subject).
16475
+ */
16476
+ minLabelConfidence: number().min(0).max(1).optional(),
16477
+ /**
16478
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16479
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16480
+ * against the token carried on the device-event subject (extracted from the
16481
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16482
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16483
+ * eventType, so gate those with {@link sensorKinds} instead.
16484
+ */
16485
+ eventTypeTokens: array(string().min(1)).optional(),
16486
+ /**
16487
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16488
+ * `contact`, `button`, `device-event`) — matched against the persisted
16489
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16490
+ */
16491
+ sensorKinds: array(string().min(1)).optional(),
16492
+ /**
16493
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16494
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16495
+ * when the subject's phase does not match (a subject always carries a phase
16496
+ * on the package-event trigger).
16497
+ */
16498
+ packagePhase: _enum([
16499
+ "delivered",
16500
+ "picked-up",
16501
+ "both"
16502
+ ]).optional(),
16503
+ /**
16504
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16505
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16506
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16507
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16508
+ */
16509
+ customZones: array(MaskPolygonShapeSchema).optional(),
16510
+ /**
16511
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16512
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16513
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16514
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16515
+ */
16516
+ occupancy: NcOccupancyConditionSchema.optional()
16484
16517
  });
16485
- var LlmRuntimeDiskUsageSchema = object({
16486
- nodeId: string(),
16487
- modelsBytes: number(),
16488
- freeBytes: number().optional()
16518
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16519
+ var NcRuleTargetSchema = object({
16520
+ /** `notification-output` Target id. */
16521
+ targetId: string().min(1),
16522
+ /**
16523
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16524
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16525
+ * degrade engine drops what the backend can't render.
16526
+ */
16527
+ params: record(string(), unknown()).optional()
16489
16528
  });
16490
- method(LlmGenerateBaseInputSchema.extend({
16491
- images: array(LlmImageSchema).optional(),
16492
- runtime: ManagedRuntimeConfigSchema,
16493
- /** The managed profile's timeout, threaded by the hub provider. */
16494
- timeoutMs: number().int().positive().optional()
16495
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16496
- kind: "mutation",
16497
- auth: "admin"
16498
- }), method(object({}), _void(), {
16499
- kind: "mutation",
16500
- auth: "admin"
16501
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16502
- kind: "mutation",
16503
- auth: "admin"
16504
- }), method(object({ file: string() }), _void(), {
16505
- kind: "mutation",
16506
- auth: "admin"
16507
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16508
16529
  /**
16509
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16510
- * methods concat-fan across providers; single-row methods route to ONE
16511
- * provider by the `addonId` in the call input (the notification-output
16512
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16513
- * (hub-placed); the cap stays open for future providers.
16514
- *
16515
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16516
- * `apiKey` is a password field providers REDACT it on read and merge on
16517
- * write; a stored key NEVER round-trips to a client.
16530
+ * Media attachment policy (P1 still-image subset).
16531
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16532
+ * - `best-matching` the media that explains WHY the rule fired: a rule
16533
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16534
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16535
+ * (or when the specific crop is missing) degrades to `best`, then
16536
+ * `keyFrame`, then no attachment never delaying the send. The matched
16537
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16538
+ * name), so the choice never drifts from the record that fired it.
16539
+ * - `keyFrame` — the clean scene frame (no subject box).
16540
+ * - `none` — no attachment.
16541
+ */
16542
+ var NcMediaPolicySchema = object({ attach: _enum([
16543
+ "best",
16544
+ "best-matching",
16545
+ "keyFrame",
16546
+ "none"
16547
+ ]).default("best") });
16548
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16549
+ var NcThrottleSchema = object({
16550
+ cooldownSec: number().int().min(0).max(86400).default(60),
16551
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16552
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16553
+ });
16554
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16555
+ var NcRuleInputSchema = object({
16556
+ name: string().min(1).max(200),
16557
+ enabled: boolean().default(true),
16558
+ delivery: NcDeliverySchema,
16559
+ conditions: NcConditionsSchema.default({}),
16560
+ schedule: NcScheduleSchema.optional(),
16561
+ targets: array(NcRuleTargetSchema).min(1),
16562
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16563
+ throttle: NcThrottleSchema.default({
16564
+ cooldownSec: 60,
16565
+ scope: "rule-device"
16566
+ }),
16567
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16568
+ template: object({
16569
+ title: string().max(500).optional(),
16570
+ body: string().max(2e3).optional()
16571
+ }).optional(),
16572
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16573
+ priority: number().int().min(1).max(5).default(3),
16574
+ /**
16575
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16576
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16577
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16578
+ */
16579
+ ownerUserId: string().optional()
16580
+ });
16581
+ /**
16582
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16583
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16584
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16585
+ * input), so it is added here explicitly to let the store's per-target opt-out
16586
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16587
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16588
+ * `updateRule` patch.
16518
16589
  */
16519
- var LlmProfileKindSchema = _enum([
16520
- "openai-compatible",
16521
- "openai",
16522
- "anthropic",
16523
- "google",
16524
- "managed-local"
16525
- ]);
16526
- var LlmProfileSchema = object({
16590
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16591
+ /** A persisted rule. */
16592
+ var NcRuleSchema = NcRuleInputSchema.extend({
16527
16593
  id: string(),
16528
- name: string(),
16529
- kind: LlmProfileKindSchema,
16530
- /** Stamped by the provider — keeps the fanned catalog routable. */
16531
- addonId: string(),
16532
- enabled: boolean(),
16533
- /** Vendor model id, or the managed runtime's loaded model. */
16534
- model: string(),
16535
- /** Required for openai-compatible; override for cloud kinds. */
16536
- baseUrl: string().optional(),
16537
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16538
- apiKey: string().optional(),
16539
- supportsVision: boolean(),
16540
- temperature: number().min(0).max(2).optional(),
16541
- maxTokens: number().int().positive().optional(),
16542
- timeoutMs: number().int().positive().default(6e4),
16543
- extraHeaders: record(string(), string()).optional(),
16544
- /** kind === 'managed-local' only (spec §4). */
16545
- runtime: ManagedRuntimeConfigSchema.optional()
16594
+ /** userId of the admin who created the rule (server-stamped caller). */
16595
+ createdBy: string(),
16596
+ createdAt: number(),
16597
+ updatedAt: number(),
16598
+ /**
16599
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16600
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16601
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16602
+ */
16603
+ disabledTargetIds: array(string()).default([])
16546
16604
  });
16547
- /** ConfigUISchema tree passed through untyped on the wire (the
16548
- * notification-output `ConfigSchemaPassthrough` precedent at
16549
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16550
- var ConfigSchemaPassthrough = unknown();
16551
- var LlmProfileKindDescriptorSchema = object({
16552
- kind: LlmProfileKindSchema,
16553
- label: string(),
16554
- icon: string(),
16555
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16556
- addonId: string(),
16557
- configSchema: ConfigSchemaPassthrough
16605
+ var NcTestResultSchema = object({
16606
+ recordId: string(),
16607
+ recordKind: _enum([
16608
+ "object-event",
16609
+ "track",
16610
+ "device-event",
16611
+ "package-event"
16612
+ ]),
16613
+ deviceId: number(),
16614
+ timestamp: number(),
16615
+ wouldFire: boolean(),
16616
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16617
+ failedCondition: string().optional(),
16618
+ className: string().optional(),
16619
+ label: string().optional()
16558
16620
  });
16559
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16560
- var LlmDefaultSchema = object({
16561
- selector: LlmDefaultSelectorSchema,
16562
- profileId: string()
16621
+ var NcConditionDescriptorSchema = object({
16622
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16623
+ id: string(),
16624
+ group: _enum([
16625
+ "scope",
16626
+ "class",
16627
+ "zones",
16628
+ "quality",
16629
+ "label",
16630
+ "schedule",
16631
+ "device",
16632
+ "package",
16633
+ "occupancy"
16634
+ ]),
16635
+ label: string(),
16636
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16637
+ valueType: _enum([
16638
+ "deviceIdList",
16639
+ "stringList",
16640
+ "number01",
16641
+ "number",
16642
+ "sourceSelect",
16643
+ "zoneSelection",
16644
+ "zoneIdList",
16645
+ "schedule",
16646
+ "plateMatcher",
16647
+ "packagePhase",
16648
+ "polygonDraw",
16649
+ "occupancy"
16650
+ ]),
16651
+ operator: _enum([
16652
+ "in",
16653
+ "notIn",
16654
+ "anyOf",
16655
+ "allOf",
16656
+ "gte",
16657
+ "fuzzyIn",
16658
+ "withinSchedule"
16659
+ ]),
16660
+ /** Which delivery kinds the condition applies to. */
16661
+ appliesTo: array(NcDeliverySchema),
16662
+ phase: string(),
16663
+ description: string().optional()
16563
16664
  });
16564
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16565
- var LlmUsageRollupSchema = object({
16566
- day: string(),
16567
- consumer: string(),
16568
- profileId: string(),
16569
- calls: number(),
16570
- okCalls: number(),
16571
- errorCalls: number(),
16572
- inputTokens: number(),
16573
- outputTokens: number(),
16574
- avgLatencyMs: number()
16665
+ /**
16666
+ * The P1 condition surface as data — served by `getConditionCatalog` so
16667
+ * rule editors render from the catalog, not hardcoded forms (spec §4.2).
16668
+ */
16669
+ var NC_CONDITION_CATALOG = [
16670
+ {
16671
+ id: "devices",
16672
+ group: "scope",
16673
+ label: "Cameras",
16674
+ valueType: "deviceIdList",
16675
+ operator: "in",
16676
+ appliesTo: [
16677
+ "immediate",
16678
+ "track-end",
16679
+ "device-event",
16680
+ "package-event"
16681
+ ],
16682
+ phase: "P1",
16683
+ description: "Restrict the rule to these devices; absent = all devices."
16684
+ },
16685
+ {
16686
+ id: "classes",
16687
+ group: "class",
16688
+ label: "Object classes",
16689
+ valueType: "stringList",
16690
+ operator: "in",
16691
+ appliesTo: [
16692
+ "immediate",
16693
+ "track-end",
16694
+ "package-event"
16695
+ ],
16696
+ phase: "P1",
16697
+ description: "Any overlap with the detection class set passes."
16698
+ },
16699
+ {
16700
+ id: "classesExclude",
16701
+ group: "class",
16702
+ label: "Excluded classes",
16703
+ valueType: "stringList",
16704
+ operator: "notIn",
16705
+ appliesTo: [
16706
+ "immediate",
16707
+ "track-end",
16708
+ "package-event"
16709
+ ],
16710
+ phase: "P1"
16711
+ },
16712
+ {
16713
+ id: "minConfidence",
16714
+ group: "quality",
16715
+ label: "Minimum confidence",
16716
+ valueType: "number01",
16717
+ operator: "gte",
16718
+ appliesTo: [
16719
+ "immediate",
16720
+ "track-end",
16721
+ "package-event"
16722
+ ],
16723
+ phase: "P1"
16724
+ },
16725
+ {
16726
+ id: "zones",
16727
+ group: "zones",
16728
+ label: "Zones",
16729
+ valueType: "zoneSelection",
16730
+ operator: "anyOf",
16731
+ appliesTo: [
16732
+ "immediate",
16733
+ "track-end",
16734
+ "package-event"
16735
+ ],
16736
+ phase: "P1",
16737
+ description: "Admin zone ids; quantifier any/all over the visited set."
16738
+ },
16739
+ {
16740
+ id: "zonesExclude",
16741
+ group: "zones",
16742
+ label: "Excluded zones",
16743
+ valueType: "zoneIdList",
16744
+ operator: "notIn",
16745
+ appliesTo: [
16746
+ "immediate",
16747
+ "track-end",
16748
+ "package-event"
16749
+ ],
16750
+ phase: "P1"
16751
+ },
16752
+ {
16753
+ id: "labelEquals",
16754
+ group: "label",
16755
+ label: "Label equals",
16756
+ valueType: "stringList",
16757
+ operator: "in",
16758
+ appliesTo: ["immediate", "track-end"],
16759
+ phase: "P1",
16760
+ description: "Exact match on the collapsed label (identity / plate / subclass)."
16761
+ },
16762
+ {
16763
+ id: "identities",
16764
+ group: "label",
16765
+ label: "Identities",
16766
+ valueType: "stringList",
16767
+ operator: "in",
16768
+ appliesTo: ["immediate", "track-end"],
16769
+ phase: "P1",
16770
+ description: "P1: matched against the identity display name on the record label."
16771
+ },
16772
+ {
16773
+ id: "plates",
16774
+ group: "label",
16775
+ label: "License plates",
16776
+ valueType: "plateMatcher",
16777
+ operator: "fuzzyIn",
16778
+ appliesTo: ["immediate", "track-end"],
16779
+ phase: "P1",
16780
+ description: "Levenshtein-tolerant match against the plate text."
16781
+ },
16782
+ {
16783
+ id: "identitiesExclude",
16784
+ group: "label",
16785
+ label: "Excluded identities",
16786
+ valueType: "stringList",
16787
+ operator: "notIn",
16788
+ appliesTo: ["immediate", "track-end"],
16789
+ phase: "P1",
16790
+ description: "Veto by identity display name (mirror of Identities; absent label passes)."
16791
+ },
16792
+ {
16793
+ id: "minLabelConfidence",
16794
+ group: "label",
16795
+ label: "Minimum label confidence",
16796
+ valueType: "number01",
16797
+ operator: "gte",
16798
+ appliesTo: ["track-end"],
16799
+ phase: "P1",
16800
+ 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."
16801
+ },
16802
+ {
16803
+ id: "minImportance",
16804
+ group: "quality",
16805
+ label: "Minimum importance",
16806
+ valueType: "number01",
16807
+ operator: "gte",
16808
+ appliesTo: ["track-end"],
16809
+ phase: "P1",
16810
+ description: "Server-computed key-event importance [0,1]; track-end rules only (importance is scored at close). Fails when the record has none."
16811
+ },
16812
+ {
16813
+ id: "minDwellSeconds",
16814
+ group: "quality",
16815
+ label: "Minimum dwell (seconds)",
16816
+ valueType: "number",
16817
+ operator: "gte",
16818
+ appliesTo: ["track-end"],
16819
+ phase: "P1",
16820
+ description: "Track lifespan in seconds (lastSeen − firstSeen); track-end rules only."
16821
+ },
16822
+ {
16823
+ id: "source",
16824
+ group: "scope",
16825
+ label: "Detection source",
16826
+ valueType: "sourceSelect",
16827
+ operator: "in",
16828
+ appliesTo: [
16829
+ "immediate",
16830
+ "track-end",
16831
+ "device-event",
16832
+ "package-event"
16833
+ ],
16834
+ phase: "P1",
16835
+ description: "pipeline / onboard / sensor; a record with no stamped source counts as pipeline."
16836
+ },
16837
+ {
16838
+ id: "sensorKinds",
16839
+ group: "device",
16840
+ label: "Sensor kinds",
16841
+ valueType: "stringList",
16842
+ operator: "in",
16843
+ appliesTo: ["device-event"],
16844
+ phase: "P1",
16845
+ description: "Sensor/control taxonomy kinds (doorbell / contact / button / …) matched against the persisted device event."
16846
+ },
16847
+ {
16848
+ id: "eventTypeTokens",
16849
+ group: "device",
16850
+ label: "Event-type tokens",
16851
+ valueType: "stringList",
16852
+ operator: "in",
16853
+ appliesTo: ["device-event"],
16854
+ phase: "P1",
16855
+ description: "Raw device event-type tokens (e.g. doorbell press / press_long) from the event-emitter slice; absent on doorbell-pulse / passive sensors."
16856
+ },
16857
+ {
16858
+ id: "packagePhase",
16859
+ group: "package",
16860
+ label: "Package phase",
16861
+ valueType: "packagePhase",
16862
+ operator: "in",
16863
+ appliesTo: ["package-event"],
16864
+ phase: "P1",
16865
+ description: "Delivered / picked-up / both."
16866
+ },
16867
+ {
16868
+ id: "occupancy",
16869
+ group: "occupancy",
16870
+ label: "Occupancy",
16871
+ valueType: "occupancy",
16872
+ operator: "anyOf",
16873
+ appliesTo: ["device-event"],
16874
+ phase: "P1",
16875
+ description: "ZoneAnalytics occupancy edge (optionally zone/class-scoped): count crosses the threshold and holds for sustainSeconds. Fail-closed on a missing snapshot."
16876
+ },
16877
+ {
16878
+ id: "customZones",
16879
+ group: "zones",
16880
+ label: "Custom zones",
16881
+ valueType: "polygonDraw",
16882
+ operator: "anyOf",
16883
+ appliesTo: [
16884
+ "immediate",
16885
+ "track-end",
16886
+ "package-event"
16887
+ ],
16888
+ phase: "P1",
16889
+ description: "User-drawn polygons; a detection whose bbox overlaps any polygon matches."
16890
+ },
16891
+ {
16892
+ id: "schedule",
16893
+ group: "schedule",
16894
+ label: "Schedule",
16895
+ valueType: "schedule",
16896
+ operator: "withinSchedule",
16897
+ appliesTo: [
16898
+ "immediate",
16899
+ "track-end",
16900
+ "device-event",
16901
+ "package-event"
16902
+ ],
16903
+ phase: "P1",
16904
+ description: "Weekly activation windows (invertible); absent = always active."
16905
+ }
16906
+ ];
16907
+ /**
16908
+ * The delivery lifecycle status of a history row — a straight read of the
16909
+ * durable outbox row's own status (single source of truth):
16910
+ * - `pending` — enqueued, in-flight or retrying with backoff
16911
+ * - `sent` — delivered (terminal)
16912
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16913
+ * backend rejection / a deleted target (terminal; carries
16914
+ * the failure `error`)
16915
+ *
16916
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16917
+ * user dimension (quiet hours / snooze) and are additive when they land.
16918
+ */
16919
+ var NcHistoryStatusSchema = _enum([
16920
+ "pending",
16921
+ "sent",
16922
+ "dead"
16923
+ ]);
16924
+ /** The evaluated record kind a history row descends from (one per trigger). */
16925
+ var NcHistoryRecordKindSchema = _enum([
16926
+ "object-event",
16927
+ "track-end",
16928
+ "device-event",
16929
+ "package-event"
16930
+ ]);
16931
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16932
+ var NcHistorySubjectSchema = object({
16933
+ className: string(),
16934
+ label: string().optional(),
16935
+ confidence: number().optional(),
16936
+ zones: array(string()),
16937
+ timestamp: number()
16575
16938
  });
16576
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16577
- var ManagedModelCatalogEntrySchema = object({
16939
+ /**
16940
+ * One delivery-history row. This is a read-only VIEW over the durable
16941
+ * outbox row (single source of truth — the same row the drain loop drives;
16942
+ * NO second write path, so history can never drift from delivery state).
16943
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16944
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16945
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16946
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16947
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16948
+ * P1 (admin scope only).
16949
+ */
16950
+ var NcHistoryEntrySchema = object({
16951
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16578
16952
  id: string(),
16579
- label: string(),
16580
- family: string(),
16581
- purpose: _enum(["text", "vision"]),
16582
- url: string(),
16583
- sha256: string(),
16584
- sizeBytes: number(),
16585
- quantization: string(),
16586
- /** Load-time guidance shown in the picker. */
16587
- minRamBytes: number(),
16588
- contextSizeDefault: number().int(),
16589
- /** Vision models: companion projector file. */
16590
- mmprojUrl: string().optional()
16591
- });
16592
- var LlmRuntimeNodeSchema = object({
16593
- nodeId: string(),
16594
- reachable: boolean(),
16595
- status: LlmRuntimeStatusSchema.optional(),
16596
- disk: LlmRuntimeDiskUsageSchema.optional(),
16597
- error: string().optional()
16598
- });
16599
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16600
- var ProfileRefInputSchema = object({
16601
- addonId: string(),
16602
- profileId: string()
16953
+ ruleId: string(),
16954
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16955
+ ruleName: string(),
16956
+ /** The rule urgency/trigger that produced this delivery. */
16957
+ delivery: NcDeliverySchema,
16958
+ targetId: string(),
16959
+ deviceId: number(),
16960
+ recordKind: NcHistoryRecordKindSchema,
16961
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16962
+ recordId: string(),
16963
+ /** Present for track-scoped deliveries (object-event / track-end). */
16964
+ trackId: string().optional(),
16965
+ status: NcHistoryStatusSchema,
16966
+ /** Delivery attempts made so far. */
16967
+ attempts: number().int(),
16968
+ /** Fire time (outbox enqueue). */
16969
+ createdAt: number(),
16970
+ /** Last transition time (terminal for sent / dead). */
16971
+ updatedAt: number(),
16972
+ /** Failure detail — present on a `dead` row. */
16973
+ error: string().optional(),
16974
+ subject: NcHistorySubjectSchema
16603
16975
  });
16604
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16605
- kind: "mutation",
16606
- auth: "admin"
16607
- }), method(ProfileRefInputSchema, _void(), {
16608
- kind: "mutation",
16609
- auth: "admin"
16610
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16611
- kind: "mutation",
16612
- auth: "admin"
16613
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16614
- selector: LlmDefaultSelectorSchema,
16615
- profileId: string().nullable()
16616
- }), _void(), {
16617
- kind: "mutation",
16618
- auth: "admin"
16619
- }), method(object({
16976
+ /**
16977
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16978
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16979
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16980
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16981
+ */
16982
+ var NcHistoryFilterSchema = object({
16983
+ ruleId: string().optional(),
16984
+ deviceId: number().optional(),
16985
+ status: NcHistoryStatusSchema.optional(),
16620
16986
  since: number().optional(),
16621
16987
  until: number().optional(),
16622
- consumer: string().optional(),
16623
- profileId: string().optional()
16624
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16625
- nodeId: string(),
16626
- model: ManagedModelRefSchema
16627
- }), _void(), {
16628
- kind: "mutation",
16629
- auth: "admin"
16630
- }), method(object({
16631
- nodeId: string(),
16632
- file: string()
16633
- }), _void(), {
16634
- kind: "mutation",
16635
- auth: "admin"
16636
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16637
- kind: "mutation",
16638
- auth: "admin"
16639
- }), method(ProfileRefInputSchema, _void(), {
16640
- kind: "mutation",
16641
- auth: "admin"
16988
+ limit: number().int().min(1).max(500).default(100)
16642
16989
  });
16990
+ var notificationRulesCapability = {
16991
+ name: "notification-rules",
16992
+ scope: "system",
16993
+ mode: "singleton",
16994
+ methods: {
16995
+ listRules: method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }),
16996
+ getRule: method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }),
16997
+ createRule: method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
16998
+ kind: "mutation",
16999
+ auth: "admin",
17000
+ caller: "required"
17001
+ }),
17002
+ updateRule: method(object({
17003
+ ruleId: string(),
17004
+ patch: NcRulePatchSchema
17005
+ }), object({ rule: NcRuleSchema }), {
17006
+ kind: "mutation",
17007
+ auth: "admin",
17008
+ caller: "required"
17009
+ }),
17010
+ deleteRule: method(object({ ruleId: string() }), object({ success: literal(true) }), {
17011
+ kind: "mutation",
17012
+ auth: "admin"
17013
+ }),
17014
+ setRuleEnabled: method(object({
17015
+ ruleId: string(),
17016
+ enabled: boolean()
17017
+ }), object({ success: literal(true) }), {
17018
+ kind: "mutation",
17019
+ auth: "admin"
17020
+ }),
17021
+ /**
17022
+ * Dry-run a rule against recently persisted records (object events for
17023
+ * `immediate`, closed tracks for `track-end`). Mutation kind only to
17024
+ * carry the full rule object safely; no side effects.
17025
+ */
17026
+ testRule: method(object({
17027
+ rule: NcRuleInputSchema,
17028
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
17029
+ }), object({ results: array(NcTestResultSchema) }), {
17030
+ kind: "mutation",
17031
+ auth: "admin"
17032
+ }),
17033
+ getConditionCatalog: method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })),
17034
+ /**
17035
+ * Queryable delivery history — a read-only view over the durable outbox
17036
+ * (fired rule, subject summary, target, status, timestamps, error on a
17037
+ * dead row). Newest-first, bounded by `filter.limit`. Retention follows
17038
+ * the outbox's own terminal-row prune horizon (no separate history
17039
+ * horizon — single collection, single source of truth). Admin-only in
17040
+ * P1 (no user dimension); the P2 viewer History screen adds per-caller
17041
+ * scoping on the same method.
17042
+ */
17043
+ getHistory: method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" })
17044
+ }
17045
+ };
16643
17046
  /**
16644
17047
  * Zod schemas for persisted record types.
16645
17048
  *
@@ -17445,165 +17848,65 @@ var pipelineAnalyticsCapability = {
17445
17848
  auth: "admin"
17446
17849
  }),
17447
17850
  getEventMedia: method(object({
17448
- eventId: string(),
17449
- kind: MediaFileKindEnum.optional()
17450
- }), array(MediaFileSchema).readonly()),
17451
- /** All media rows owned by a track. `kinds` narrows to a kind subset so a
17452
- * client can fetch the SMALL display variants on open and pull the
17453
- * multi-MB native variants only on demand (mirrors `getEventMedia.kind`).
17454
- * Absent ⇒ every kind (back-compat). */
17455
- getTrackMedia: method(object({
17456
- trackId: string(),
17457
- kinds: array(MediaFileKindEnum).optional()
17458
- }), array(MediaFileSchema).readonly()),
17459
- /**
17460
- * Search object events by text query using CLIP cosine similarity.
17461
- * Encodes `text` via the `embedding-encoder` cap, queries the
17462
- * `ObjectEmbeddingStore` with optional prefilters, ranks all matching
17463
- * embeddings by cosine similarity, and joins winners to their
17464
- * ObjectEvents by trackId. Returns up to `limit` events scored ≥
17465
- * `minScore`, sorted descending by score.
17466
- */
17467
- searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly())
17468
- },
17469
- events: {
17470
- /**
17471
- * Enriched frame emitted after refinement — the live-overlay source of
17472
- * truth (two-plane re-injection). Carries the frame's detections in the
17473
- * `ObjectDetection` wire shape: first-level roots (with track info +
17474
- * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
17475
- * re-projected from per-track detail state, so stream overlays render
17476
- * boxes + recognized names without querying full Track state.
17477
- */
17478
- onFrameTracked: { data: object({
17479
- deviceId: number(),
17480
- timestamp: number(),
17481
- frameWidth: number(),
17482
- frameHeight: number(),
17483
- detections: array(OverlayDetectionSchema).readonly()
17484
- }) },
17485
- /** Track entered active state (first-seen). */
17486
- onTrackStarted: { data: object({
17487
- deviceId: number(),
17488
- trackId: string(),
17489
- className: string()
17490
- }) },
17491
- /** Track expired (TTL reached after last detection). */
17492
- onTrackEnded: { data: object({
17493
- deviceId: number(),
17494
- trackId: string(),
17495
- className: string(),
17496
- durationMs: number()
17497
- }) },
17498
- /** Canonical "something happened at device X" event, per-kind. */
17499
- onDetectionEvent: { data: object({
17500
- deviceId: number(),
17501
- kind: EventKindSchema,
17502
- eventId: string(),
17503
- timestamp: number()
17504
- }) }
17505
- }
17506
- };
17507
- /**
17508
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17509
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17510
- * caps into per-camera event-kind descriptors.
17511
- *
17512
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17513
- * is NOT duplicated here — every entry is derived from the single
17514
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17515
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17516
- * control cap means adding one line here (and a taxonomy entry); the anti-
17517
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17518
- * eventful cap is missing.
17519
- */
17520
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17521
- var LEGACY_ICON = {
17522
- motion: "motion",
17523
- audio: "audio",
17524
- person: "person",
17525
- vehicle: "vehicle",
17526
- animal: "animal",
17527
- package: "package",
17528
- door: "door",
17529
- pir: "pir",
17530
- smoke: "smoke",
17531
- water: "water",
17532
- button: "button",
17533
- generic: "generic",
17534
- gas: "smoke",
17535
- vibration: "generic",
17536
- tamper: "generic",
17537
- presence: "person",
17538
- lock: "generic",
17539
- siren: "generic",
17540
- switch: "generic",
17541
- doorbell: "button"
17542
- };
17543
- function legacyIcon(iconId) {
17544
- return LEGACY_ICON[iconId] ?? "generic";
17545
- }
17546
- /**
17547
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17548
- * The anti-drift guard cross-checks this against the eventful caps declared
17549
- * in `packages/types/src/capabilities/*.cap.ts`.
17550
- */
17551
- var CAP_TO_KIND = {
17552
- contact: "contact",
17553
- motion: "motion-sensor",
17554
- smoke: "smoke",
17555
- flood: "flood",
17556
- gas: "gas",
17557
- "carbon-monoxide": "carbon-monoxide",
17558
- vibration: "vibration",
17559
- tamper: "tamper",
17560
- presence: "presence",
17561
- "enum-sensor": "enum-sensor",
17562
- "event-emitter": "device-event",
17563
- "lock-control": "lock",
17564
- switch: "switch",
17565
- button: "button",
17566
- doorbell: "doorbell"
17851
+ eventId: string(),
17852
+ kind: MediaFileKindEnum.optional()
17853
+ }), array(MediaFileSchema).readonly()),
17854
+ /** All media rows owned by a track. `kinds` narrows to a kind subset so a
17855
+ * client can fetch the SMALL display variants on open and pull the
17856
+ * multi-MB native variants only on demand (mirrors `getEventMedia.kind`).
17857
+ * Absent ⇒ every kind (back-compat). */
17858
+ getTrackMedia: method(object({
17859
+ trackId: string(),
17860
+ kinds: array(MediaFileKindEnum).optional()
17861
+ }), array(MediaFileSchema).readonly()),
17862
+ /**
17863
+ * Search object events by text query using CLIP cosine similarity.
17864
+ * Encodes `text` via the `embedding-encoder` cap, queries the
17865
+ * `ObjectEmbeddingStore` with optional prefilters, ranks all matching
17866
+ * embeddings by cosine similarity, and joins winners to their
17867
+ * ObjectEvents by trackId. Returns up to `limit` events scored ≥
17868
+ * `minScore`, sorted descending by score.
17869
+ */
17870
+ searchObjectEvents: method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly())
17871
+ },
17872
+ events: {
17873
+ /**
17874
+ * Enriched frame emitted after refinement — the live-overlay source of
17875
+ * truth (two-plane re-injection). Carries the frame's detections in the
17876
+ * `ObjectDetection` wire shape: first-level roots (with track info +
17877
+ * enrichment labels) plus synthesized `kind:'detail'` face/plate entries
17878
+ * re-projected from per-track detail state, so stream overlays render
17879
+ * boxes + recognized names without querying full Track state.
17880
+ */
17881
+ onFrameTracked: { data: object({
17882
+ deviceId: number(),
17883
+ timestamp: number(),
17884
+ frameWidth: number(),
17885
+ frameHeight: number(),
17886
+ detections: array(OverlayDetectionSchema).readonly()
17887
+ }) },
17888
+ /** Track entered active state (first-seen). */
17889
+ onTrackStarted: { data: object({
17890
+ deviceId: number(),
17891
+ trackId: string(),
17892
+ className: string()
17893
+ }) },
17894
+ /** Track expired (TTL reached after last detection). */
17895
+ onTrackEnded: { data: object({
17896
+ deviceId: number(),
17897
+ trackId: string(),
17898
+ className: string(),
17899
+ durationMs: number()
17900
+ }) },
17901
+ /** Canonical "something happened at device X" event, per-kind. */
17902
+ onDetectionEvent: { data: object({
17903
+ deviceId: number(),
17904
+ kind: EventKindSchema,
17905
+ eventId: string(),
17906
+ timestamp: number()
17907
+ }) }
17908
+ }
17567
17909
  };
17568
- function buildDescriptor(capName, kind) {
17569
- const t = EVENT_TAXONOMY[kind];
17570
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17571
- return {
17572
- ...t,
17573
- icon: legacyIcon(t.iconId)
17574
- };
17575
- }
17576
- /**
17577
- * Sensor / control cap name → static event-kind descriptor. A linked device
17578
- * contributes one entry per bound cap present in this map.
17579
- */
17580
- var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17581
- /**
17582
- * Build a full `EventKindDescriptor` for a taxonomy `kind`, stamping the
17583
- * per-device `source`. Returns null when `kind` is not in the taxonomy.
17584
- * This is THE bridge from the serializable taxonomy dictionary to the cap
17585
- * wire shape — every event-kind descriptor the server emits goes through it,
17586
- * so color/iconId/labelKey are never re-declared at a call site.
17587
- */
17588
- function buildEventKindDescriptor(kind, source) {
17589
- const t = EVENT_TAXONOMY[kind];
17590
- if (t === void 0) return null;
17591
- return {
17592
- kind: t.kind,
17593
- labelKey: t.labelKey,
17594
- label: t.label,
17595
- color: t.color,
17596
- iconId: t.iconId,
17597
- icon: legacyIcon(t.iconId),
17598
- category: t.category,
17599
- parentKind: t.parentKind,
17600
- level: t.level,
17601
- source: {
17602
- capName: source.capName,
17603
- deviceId: source.deviceId
17604
- }
17605
- };
17606
- }
17607
17910
  var CameraPipelineConfigSchema = object({
17608
17911
  engine: PipelineEngineChoiceSchema.optional(),
17609
17912
  steps: array(PipelineStepInputSchema).readonly(),
@@ -18089,6 +18392,106 @@ method(object({
18089
18392
  auth: "admin"
18090
18393
  });
18091
18394
  /**
18395
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
18396
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
18397
+ * caps into per-camera event-kind descriptors.
18398
+ *
18399
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
18400
+ * is NOT duplicated here — every entry is derived from the single
18401
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
18402
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
18403
+ * control cap means adding one line here (and a taxonomy entry); the anti-
18404
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
18405
+ * eventful cap is missing.
18406
+ */
18407
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
18408
+ var LEGACY_ICON = {
18409
+ motion: "motion",
18410
+ audio: "audio",
18411
+ person: "person",
18412
+ vehicle: "vehicle",
18413
+ animal: "animal",
18414
+ package: "package",
18415
+ door: "door",
18416
+ pir: "pir",
18417
+ smoke: "smoke",
18418
+ water: "water",
18419
+ button: "button",
18420
+ generic: "generic",
18421
+ gas: "smoke",
18422
+ vibration: "generic",
18423
+ tamper: "generic",
18424
+ presence: "person",
18425
+ lock: "generic",
18426
+ siren: "generic",
18427
+ switch: "generic",
18428
+ doorbell: "button"
18429
+ };
18430
+ function legacyIcon(iconId) {
18431
+ return LEGACY_ICON[iconId] ?? "generic";
18432
+ }
18433
+ /**
18434
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
18435
+ * The anti-drift guard cross-checks this against the eventful caps declared
18436
+ * in `packages/types/src/capabilities/*.cap.ts`.
18437
+ */
18438
+ var CAP_TO_KIND = {
18439
+ contact: "contact",
18440
+ motion: "motion-sensor",
18441
+ smoke: "smoke",
18442
+ flood: "flood",
18443
+ gas: "gas",
18444
+ "carbon-monoxide": "carbon-monoxide",
18445
+ vibration: "vibration",
18446
+ tamper: "tamper",
18447
+ presence: "presence",
18448
+ "enum-sensor": "enum-sensor",
18449
+ "event-emitter": "device-event",
18450
+ "lock-control": "lock",
18451
+ switch: "switch",
18452
+ button: "button",
18453
+ doorbell: "doorbell"
18454
+ };
18455
+ function buildDescriptor(capName, kind) {
18456
+ const t = EVENT_TAXONOMY[kind];
18457
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
18458
+ return {
18459
+ ...t,
18460
+ icon: legacyIcon(t.iconId)
18461
+ };
18462
+ }
18463
+ /**
18464
+ * Sensor / control cap name → static event-kind descriptor. A linked device
18465
+ * contributes one entry per bound cap present in this map.
18466
+ */
18467
+ var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
18468
+ /**
18469
+ * Build a full `EventKindDescriptor` for a taxonomy `kind`, stamping the
18470
+ * per-device `source`. Returns null when `kind` is not in the taxonomy.
18471
+ * This is THE bridge from the serializable taxonomy dictionary to the cap
18472
+ * wire shape — every event-kind descriptor the server emits goes through it,
18473
+ * so color/iconId/labelKey are never re-declared at a call site.
18474
+ */
18475
+ function buildEventKindDescriptor(kind, source) {
18476
+ const t = EVENT_TAXONOMY[kind];
18477
+ if (t === void 0) return null;
18478
+ return {
18479
+ kind: t.kind,
18480
+ labelKey: t.labelKey,
18481
+ label: t.label,
18482
+ color: t.color,
18483
+ iconId: t.iconId,
18484
+ icon: legacyIcon(t.iconId),
18485
+ category: t.category,
18486
+ parentKind: t.parentKind,
18487
+ level: t.level,
18488
+ source: {
18489
+ capName: source.capName,
18490
+ deviceId: source.deviceId
18491
+ }
18492
+ };
18493
+ }
18494
+ /**
18092
18495
  * server-management — per-NODE singleton capability for a node's ROOT
18093
18496
  * package lifecycle (runtime-updatable node packages).
18094
18497
  *
@@ -19553,7 +19956,28 @@ var FaceInfoSchema = object({
19553
19956
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
19554
19957
  * track produced no key frame (e.g. native/onboard source) — the UI falls
19555
19958
  * back to the inline `base64` face crop. */
19556
- keyFrameMediaKey: string().optional()
19959
+ keyFrameMediaKey: string().optional(),
19960
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19961
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19962
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19963
+ * faces that were never auto-recognized. */
19964
+ bestMatchScore: number().optional(),
19965
+ /** Native-scale face short side (px) at recognition time, when the runner
19966
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19967
+ * legacy rows / runners that reported no native measure. */
19968
+ nativeFaceShortSidePx: number().optional(),
19969
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19970
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19971
+ * but blocked only by the recognition size floor). Mutually exclusive with
19972
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19973
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19974
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19975
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19976
+ suggestedIdentityId: string().optional(),
19977
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19978
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19979
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19980
+ suggestedMatchScore: number().optional()
19557
19981
  });
19558
19982
  var FaceFilterEnum = _enum([
19559
19983
  "unassigned",
@@ -21656,36 +22080,6 @@ Object.freeze({
21656
22080
  addonId: null,
21657
22081
  access: "view"
21658
22082
  },
21659
- "advancedNotifier.deleteRule": {
21660
- capName: "advanced-notifier",
21661
- capScope: "system",
21662
- addonId: null,
21663
- access: "delete"
21664
- },
21665
- "advancedNotifier.getHistory": {
21666
- capName: "advanced-notifier",
21667
- capScope: "system",
21668
- addonId: null,
21669
- access: "view"
21670
- },
21671
- "advancedNotifier.getRules": {
21672
- capName: "advanced-notifier",
21673
- capScope: "system",
21674
- addonId: null,
21675
- access: "view"
21676
- },
21677
- "advancedNotifier.testRule": {
21678
- capName: "advanced-notifier",
21679
- capScope: "system",
21680
- addonId: null,
21681
- access: "create"
21682
- },
21683
- "advancedNotifier.upsertRule": {
21684
- capName: "advanced-notifier",
21685
- capScope: "system",
21686
- addonId: null,
21687
- access: "create"
21688
- },
21689
22083
  "alarmPanel.arm": {
21690
22084
  capName: "alarm-panel",
21691
22085
  capScope: "device",
@@ -24008,6 +24402,12 @@ Object.freeze({
24008
24402
  addonId: null,
24009
24403
  access: "view"
24010
24404
  },
24405
+ "notificationRules.getHistory": {
24406
+ capName: "notification-rules",
24407
+ capScope: "system",
24408
+ addonId: null,
24409
+ access: "view"
24410
+ },
24011
24411
  "notificationRules.getRule": {
24012
24412
  capName: "notification-rules",
24013
24413
  capScope: "system",
@@ -26299,12 +26699,42 @@ Object.defineProperty(exports, "NC_CONDITION_CATALOG", {
26299
26699
  return NC_CONDITION_CATALOG;
26300
26700
  }
26301
26701
  });
26702
+ Object.defineProperty(exports, "NC_TAXONOMY", {
26703
+ enumerable: true,
26704
+ get: function() {
26705
+ return NC_TAXONOMY;
26706
+ }
26707
+ });
26708
+ Object.defineProperty(exports, "NcConditionDescriptorSchema", {
26709
+ enumerable: true,
26710
+ get: function() {
26711
+ return NcConditionDescriptorSchema;
26712
+ }
26713
+ });
26714
+ Object.defineProperty(exports, "NcRuleInputSchema", {
26715
+ enumerable: true,
26716
+ get: function() {
26717
+ return NcRuleInputSchema;
26718
+ }
26719
+ });
26720
+ Object.defineProperty(exports, "NcRulePatchSchema", {
26721
+ enumerable: true,
26722
+ get: function() {
26723
+ return NcRulePatchSchema;
26724
+ }
26725
+ });
26302
26726
  Object.defineProperty(exports, "NcRuleSchema", {
26303
26727
  enumerable: true,
26304
26728
  get: function() {
26305
26729
  return NcRuleSchema;
26306
26730
  }
26307
26731
  });
26732
+ Object.defineProperty(exports, "NcTaxonomySchema", {
26733
+ enumerable: true,
26734
+ get: function() {
26735
+ return NcTaxonomySchema;
26736
+ }
26737
+ });
26308
26738
  Object.defineProperty(exports, "OpsLogEntrySchema", {
26309
26739
  enumerable: true,
26310
26740
  get: function() {
@@ -26359,6 +26789,18 @@ Object.defineProperty(exports, "createEvent", {
26359
26789
  return createEvent;
26360
26790
  }
26361
26791
  });
26792
+ Object.defineProperty(exports, "customAction", {
26793
+ enumerable: true,
26794
+ get: function() {
26795
+ return customAction;
26796
+ }
26797
+ });
26798
+ Object.defineProperty(exports, "defineCustomActions", {
26799
+ enumerable: true,
26800
+ get: function() {
26801
+ return defineCustomActions;
26802
+ }
26803
+ });
26362
26804
  Object.defineProperty(exports, "embeddingEncoderCapability", {
26363
26805
  enumerable: true,
26364
26806
  get: function() {
@@ -26389,6 +26831,12 @@ Object.defineProperty(exports, "hydrateSchema", {
26389
26831
  return hydrateSchema;
26390
26832
  }
26391
26833
  });
26834
+ Object.defineProperty(exports, "literal", {
26835
+ enumerable: true,
26836
+ get: function() {
26837
+ return literal;
26838
+ }
26839
+ });
26392
26840
  Object.defineProperty(exports, "nodePin", {
26393
26841
  enumerable: true,
26394
26842
  get: function() {