@camstack/addon-decoder-ffmpeg 1.2.4 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +1400 -848
  2. package/dist/index.mjs +1400 -848
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ Object.defineProperties(exports, {
4
4
  });
5
5
  let node_crypto = require("node:crypto");
6
6
  let node_child_process = require("node:child_process");
7
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
7
+ //#region ../types/dist/event-category-BLcNejAE.mjs
8
8
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
9
9
  EventCategory["SystemBoot"] = "system.boot";
10
10
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -154,9 +154,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
154
154
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
155
155
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
156
156
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
157
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
158
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
159
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
160
157
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
161
158
  * progress bar the client reconciles via `recordingExport.getExport`. */
162
159
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6821,7 +6818,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6821
6818
  patch: record(string(), unknown())
6822
6819
  }), object({ success: literal(true) });
6823
6820
  object({ deviceId: number() }), unknown().nullable();
6824
- /** Shorthand to define a method schema */
6825
6821
  function method(input, output, options) {
6826
6822
  return {
6827
6823
  input,
@@ -6829,6 +6825,7 @@ function method(input, output, options) {
6829
6825
  kind: options?.kind ?? "query",
6830
6826
  auth: options?.auth ?? "protected",
6831
6827
  ...options?.access !== void 0 ? { access: options.access } : {},
6828
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6832
6829
  timeoutMs: options?.timeoutMs
6833
6830
  };
6834
6831
  }
@@ -8194,6 +8191,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8194
8191
  /** The complete taxonomy dictionary, keyed by kind. */
8195
8192
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8196
8193
  /**
8194
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8195
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8196
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8197
+ * taxonomy surface (timeline, filters, event page).
8198
+ *
8199
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8200
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8201
+ * for the `classes` / `classesExclude` conditions.
8202
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8203
+ * the same class picker, grouped under an Audio header.
8204
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8205
+ * lock / …) for the `sensorKinds` device-event condition.
8206
+ *
8207
+ * Each entry carries `parentKind` so the client can group video subs under
8208
+ * their macro and sensor/control kinds under their category. This surface is
8209
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8210
+ * method, no codegen — so it ships train-free with an addon deploy.
8211
+ */
8212
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8213
+ var NcTaxonomyEntrySchema = object({
8214
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8215
+ kind: string(),
8216
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8217
+ label: string(),
8218
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8219
+ parentKind: string().nullable()
8220
+ });
8221
+ object({
8222
+ videoClasses: array(NcTaxonomyEntrySchema),
8223
+ audioKinds: array(NcTaxonomyEntrySchema),
8224
+ labels: array(NcTaxonomyEntrySchema)
8225
+ });
8226
+ function toEntry(kind, label, parentKind) {
8227
+ return {
8228
+ kind,
8229
+ label,
8230
+ parentKind
8231
+ };
8232
+ }
8233
+ /**
8234
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8235
+ * (macros before their subs), which the client relies on for stable grouping.
8236
+ */
8237
+ function buildNcTaxonomy() {
8238
+ const all = Object.values(EVENT_TAXONOMY);
8239
+ return {
8240
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8241
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8242
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8243
+ };
8244
+ }
8245
+ Object.freeze(buildNcTaxonomy());
8246
+ /**
8197
8247
  * Error types for the safe expression engine. Two distinct classes so callers
8198
8248
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8199
8249
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10902,6 +10952,22 @@ var CameraMetricsSchema = object({
10902
10952
  ])
10903
10953
  });
10904
10954
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
10955
+ /**
10956
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
10957
+ * within the frame, so the executor can re-cut a leaf child ROI at native
10958
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
10959
+ */
10960
+ var NativeCropRefSchema = object({
10961
+ /** Handle keying the retained native surface (node-pinned to its owner). */
10962
+ handle: FrameHandleSchema,
10963
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
10964
+ cropFrameSpace: object({
10965
+ x: number(),
10966
+ y: number(),
10967
+ w: number(),
10968
+ h: number()
10969
+ })
10970
+ });
10905
10971
  var ModelFormatSchema$1 = _enum([
10906
10972
  "onnx",
10907
10973
  "coreml",
@@ -11177,7 +11243,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11177
11243
  * Omitted ⇒ the runner's default device (current single-engine
11178
11244
  * behaviour). Selects WHICH device pool of the node runs the call.
11179
11245
  */
11180
- deviceKey: string().optional()
11246
+ deviceKey: string().optional(),
11247
+ /**
11248
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11249
+ * when the parent crop was resolved from the frame's retained NATIVE
11250
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11251
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11252
+ * resolution from that surface — the SAME quality path faces already
11253
+ * had — instead of the downscaled parent tile. `handle` keys the native
11254
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11255
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11256
+ * the executor's crop-normalized child ROI back into frame-normalized
11257
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11258
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11259
+ * (today's behaviour on the fallback path).
11260
+ */
11261
+ nativeCropRef: NativeCropRefSchema.optional()
11181
11262
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11182
11263
  engine: PipelineEngineChoiceSchema.optional(),
11183
11264
  steps: array(PipelineStepInputSchema).min(1),
@@ -11393,7 +11474,11 @@ var DetailResultSchema = object({
11393
11474
  bbox: NativeCropBboxSchema.optional(),
11394
11475
  embedding: string().optional(),
11395
11476
  label: string().optional(),
11396
- alignedCropJpeg: string().optional()
11477
+ alignedCropJpeg: string().optional(),
11478
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11479
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11480
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11481
+ nativeFaceShortSidePx: number().optional()
11397
11482
  });
11398
11483
  /**
11399
11484
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11407,6 +11492,12 @@ var motionCooldownMsField = {
11407
11492
  default: 3e4,
11408
11493
  step: 500
11409
11494
  };
11495
+ var maxSessionHoldMsField = {
11496
+ min: 0,
11497
+ max: 6e5,
11498
+ default: 12e4,
11499
+ step: 5e3
11500
+ };
11410
11501
  var motionFpsField = {
11411
11502
  min: 1,
11412
11503
  max: 30,
@@ -11554,6 +11645,19 @@ var RunnerCameraConfigSchema = object({
11554
11645
  "on-motion"
11555
11646
  ]).default("always-on"),
11556
11647
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11648
+ /**
11649
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11650
+ * detection session is active and ≥1 confirmed non-stationary track is
11651
+ * still live, the orchestrator keeps the session open past
11652
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11653
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11654
+ * ms since the session opened, after which it closes regardless. `0`
11655
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11656
+ * runner itself — carried here so it shares the per-camera device-settings
11657
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11658
+ * resolved `CameraDetectionConfig`.
11659
+ */
11660
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11557
11661
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11558
11662
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11559
11663
  motionStreamId: string(),
@@ -11643,7 +11747,7 @@ var RunnerCameraConfigSchema = object({
11643
11747
  */
11644
11748
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11645
11749
  });
11646
- motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
11750
+ motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, maxSessionHoldMsField.min, maxSessionHoldMsField.max, maxSessionHoldMsField.step, maxSessionHoldMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
11647
11751
  /**
11648
11752
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11649
11753
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13497,94 +13601,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13497
13601
  bundleUrl: string()
13498
13602
  });
13499
13603
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13500
- var NotificationRuleConditionsSchema = object({
13501
- deviceIds: array(number()).readonly().optional(),
13502
- classNames: array(string()).readonly().optional(),
13503
- zoneIds: array(string()).readonly().optional(),
13504
- minConfidence: number().optional(),
13505
- source: _enum([
13506
- "pipeline",
13507
- "onboard",
13508
- "any"
13509
- ]).optional(),
13510
- schedule: object({
13511
- days: array(number()).readonly(),
13512
- startHour: number(),
13513
- endHour: number()
13514
- }).optional(),
13515
- cooldownSeconds: number().optional(),
13516
- minDwellSeconds: number().optional(),
13517
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13518
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13519
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13520
- eventTypeTokens: array(string()).readonly().optional(),
13521
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13522
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13523
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13524
- clipDescription: object({
13525
- text: string().min(1),
13526
- minSimilarity: number().min(0).max(1)
13527
- }).optional(),
13528
- /** Match events whose recognized-entity label (face identity name or plate
13529
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13530
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13531
- * vehicle/person> is seen". */
13532
- labels: array(string()).readonly().optional()
13533
- });
13534
- var NotificationRuleTemplateSchema = object({
13535
- title: string(),
13536
- body: string(),
13537
- imageMode: _enum([
13538
- "crop",
13539
- "annotated",
13540
- "full",
13541
- "none"
13542
- ])
13543
- });
13544
- var NotificationRuleSchema = object({
13545
- id: string(),
13546
- name: string(),
13547
- enabled: boolean(),
13548
- eventTypes: array(string()).readonly(),
13549
- conditions: NotificationRuleConditionsSchema,
13550
- outputs: array(string()).readonly(),
13551
- template: NotificationRuleTemplateSchema.optional(),
13552
- priority: _enum([
13553
- "low",
13554
- "normal",
13555
- "high",
13556
- "critical"
13557
- ])
13558
- });
13559
- var NotificationTestResultSchema = object({
13560
- ruleId: string(),
13561
- eventId: string(),
13562
- timestamp: number(),
13563
- wouldFire: boolean(),
13564
- reason: string().optional()
13565
- });
13566
- var NotificationHistoryEntrySchema = object({
13567
- id: string(),
13568
- ruleId: string(),
13569
- ruleName: string(),
13570
- eventId: string(),
13571
- timestamp: number(),
13572
- outputs: array(string()).readonly(),
13573
- success: boolean(),
13574
- error: string().optional(),
13575
- deviceId: number().optional()
13576
- });
13577
- var NotificationHistoryFilterSchema = object({
13578
- ruleId: string().optional(),
13579
- deviceId: number().optional(),
13580
- from: number().optional(),
13581
- to: number().optional(),
13582
- limit: number().optional()
13583
- });
13584
- 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({
13585
- ruleId: string(),
13586
- lookbackMinutes: number()
13587
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13588
13604
  /**
13589
13605
  * Alerts capability — collection-based internal alert system.
13590
13606
  *
@@ -13808,89 +13824,6 @@ method(object({
13808
13824
  password: string()
13809
13825
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13810
13826
  /**
13811
- * `login-method` — collection cap through which auth addons contribute
13812
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13813
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13814
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13815
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13816
- * procedure aggregates them for the unauthenticated login page.
13817
- *
13818
- * A contribution is a discriminated union on `kind`:
13819
- *
13820
- * - `redirect` — a declarative button. The login page renders a generic
13821
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13822
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13823
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13824
- * login page needs NO change.
13825
- *
13826
- * - `widget` — a Module-Federation widget the login page mounts (via
13827
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13828
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13829
- * mechanism kept for future use; no shipped addon uses it on the login
13830
- * page (the passkey ceremony below runs natively in the shell instead).
13831
- *
13832
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13833
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13834
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13835
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13836
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13837
- * fetching any remote code pre-auth. Contribution stays unconditional —
13838
- * enrollment state is never leaked pre-auth; visibility is a shell
13839
- * decision.
13840
- *
13841
- * Every contribution carries a `stage`:
13842
- * - `primary` — shown on the first credentials screen (OIDC /
13843
- * magic-link buttons; a future usernameless passkey).
13844
- * - `second-factor` — shown AFTER the password leg, gated on the
13845
- * returned `factors` (passkey-as-2FA today).
13846
- *
13847
- * `mount: skip` — the cap is read server-side by the core auth router
13848
- * (`registry.getCollection('login-method')`), never mounted as its own
13849
- * tRPC router.
13850
- */
13851
- /** When a login method renders in the two-phase login flow. */
13852
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13853
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13854
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13855
- object({
13856
- kind: literal("redirect"),
13857
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13858
- id: string(),
13859
- /** Operator-facing button label. */
13860
- label: string(),
13861
- /** lucide-react icon name. */
13862
- icon: string().optional(),
13863
- /** Addon-owned HTTP route the button navigates to (GET). */
13864
- startUrl: string(),
13865
- stage: LoginStageEnum
13866
- }),
13867
- object({
13868
- kind: literal("widget"),
13869
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13870
- id: string(),
13871
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13872
- addonId: string(),
13873
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13874
- bundle: string(),
13875
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13876
- remote: WidgetRemoteSchema,
13877
- stage: LoginStageEnum
13878
- }),
13879
- object({
13880
- kind: literal("passkey"),
13881
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13882
- id: string(),
13883
- /** Operator-facing button label. */
13884
- label: string(),
13885
- stage: LoginStageEnum,
13886
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13887
- rpId: string(),
13888
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13889
- origin: string().nullable()
13890
- })
13891
- ]);
13892
- method(_void(), array(LoginMethodContributionSchema).readonly());
13893
- /**
13894
13827
  * Orchestrator-side destination metadata. The orchestrator computes
13895
13828
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13896
13829
  * (admin UI, restore flow) see one canonical key.
@@ -15327,240 +15260,615 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15327
15260
  kind: "mutation",
15328
15261
  auth: "admin"
15329
15262
  });
15330
- var LogLevelSchema = _enum([
15331
- "debug",
15332
- "info",
15333
- "warn",
15334
- "error"
15263
+ /**
15264
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15265
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15266
+ * caps stay wire-compatible without a circular cap→cap import.
15267
+ *
15268
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15269
+ * every transport tier structurally, and failed calls still write usage rows.
15270
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15271
+ */
15272
+ var LlmUsageSchema = object({
15273
+ inputTokens: number(),
15274
+ outputTokens: number()
15275
+ });
15276
+ var LlmErrorCodeSchema = _enum([
15277
+ "timeout",
15278
+ "rate-limited",
15279
+ "auth",
15280
+ "refusal",
15281
+ "bad-request",
15282
+ "unavailable",
15283
+ "no-profile",
15284
+ "budget-exceeded",
15285
+ "adapter-error"
15335
15286
  ]);
15336
- var LogEntrySchema = object({
15337
- timestamp: date(),
15338
- level: LogLevelSchema,
15339
- scope: array(string()),
15287
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15288
+ ok: literal(true),
15289
+ text: string(),
15290
+ model: string(),
15291
+ usage: LlmUsageSchema,
15292
+ truncated: boolean(),
15293
+ latencyMs: number()
15294
+ }), object({
15295
+ ok: literal(false),
15296
+ code: LlmErrorCodeSchema,
15340
15297
  message: string(),
15341
- meta: record(string(), unknown()).optional(),
15342
- tags: record(string(), string()).optional()
15343
- });
15344
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15345
- scope: array(string()).optional(),
15346
- level: LogLevelSchema.optional(),
15347
- since: date().optional(),
15348
- until: date().optional(),
15349
- limit: number().optional(),
15350
- tags: record(string(), string()).optional()
15351
- }), array(LogEntrySchema).readonly());
15352
- var CpuBreakdownSchema = object({
15353
- total: number(),
15354
- user: number(),
15355
- system: number(),
15356
- irq: number(),
15357
- nice: number(),
15358
- loadAvg: tuple([
15359
- number(),
15360
- number(),
15361
- number()
15362
- ]),
15363
- cores: number()
15298
+ retryAfterMs: number().optional()
15299
+ })]);
15300
+ /**
15301
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15302
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15303
+ * notification-output.cap.ts:27-31 precedents).
15304
+ */
15305
+ var LlmImageSchema = object({
15306
+ bytes: _instanceof(Uint8Array),
15307
+ mimeType: string()
15364
15308
  });
15365
- var MemoryInfoSchema = object({
15366
- percent: number(),
15367
- totalBytes: number(),
15368
- usedBytes: number(),
15369
- availableBytes: number(),
15370
- swapUsedBytes: number(),
15371
- swapTotalBytes: number()
15309
+ var LlmGenerateBaseInputSchema = object({
15310
+ /** Collection routing (the notification-output posture). */
15311
+ addonId: string().optional(),
15312
+ /** Explicit profile; else the resolution chain (spec §3). */
15313
+ profileId: string().optional(),
15314
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15315
+ consumer: string(),
15316
+ system: string().optional(),
15317
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15318
+ prompt: string(),
15319
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15320
+ jsonSchema: record(string(), unknown()).optional(),
15321
+ /** Per-call override of the profile default. */
15322
+ maxTokens: number().int().positive().optional(),
15323
+ temperature: number().optional()
15372
15324
  });
15373
- var DiskIoSnapshotSchema = object({
15374
- readBytes: number(),
15375
- writeBytes: number(),
15376
- readOps: number(),
15377
- writeOps: number(),
15378
- timestampMs: number()
15379
- });
15380
- var NetworkIoSnapshotSchema = object({
15381
- rxBytes: number(),
15382
- txBytes: number(),
15383
- rxPackets: number(),
15384
- txPackets: number(),
15385
- rxErrors: number(),
15386
- txErrors: number(),
15387
- timestampMs: number()
15388
- });
15389
- var MetricsGpuInfoSchema = object({
15390
- utilization: number(),
15391
- model: string(),
15392
- memoryUsedBytes: number(),
15393
- memoryTotalBytes: number(),
15394
- temperature: number().nullable()
15395
- });
15396
- var ProcessResourceInfoSchema = object({
15397
- openFds: number(),
15398
- threadCount: number(),
15399
- activeHandles: number(),
15400
- activeRequests: number()
15401
- });
15402
- var PressureAvgsSchema = object({
15403
- avg10: number(),
15404
- avg60: number(),
15405
- avg300: number()
15406
- });
15407
- var PressureInfoSchema = object({
15408
- some: PressureAvgsSchema,
15409
- full: PressureAvgsSchema.nullable()
15410
- });
15411
- var SystemResourceSnapshotSchema = object({
15412
- cpu: CpuBreakdownSchema,
15413
- memory: MemoryInfoSchema,
15414
- gpu: MetricsGpuInfoSchema.nullable(),
15415
- network: NetworkIoSnapshotSchema,
15416
- disk: DiskIoSnapshotSchema,
15417
- pressure: object({
15418
- cpu: PressureInfoSchema.nullable(),
15419
- memory: PressureInfoSchema.nullable(),
15420
- io: PressureInfoSchema.nullable()
15325
+ /**
15326
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15327
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15328
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15329
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15330
+ * this only through the `llm` cap's methods.
15331
+ *
15332
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15333
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15334
+ * watchdog — operator decision #3).
15335
+ */
15336
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15337
+ object({
15338
+ kind: literal("catalog"),
15339
+ catalogId: string()
15421
15340
  }),
15422
- process: ProcessResourceInfoSchema,
15423
- cpuTemperature: number().nullable(),
15424
- timestampMs: number()
15425
- });
15426
- var DiskSpaceInfoSchema = object({
15427
- path: string(),
15428
- totalBytes: number(),
15429
- usedBytes: number(),
15430
- availableBytes: number(),
15431
- percent: number()
15432
- });
15433
- var PidResourceStatsSchema = object({
15434
- pid: number(),
15435
- cpu: number(),
15436
- memory: number(),
15437
- /**
15438
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15439
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15440
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15441
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15442
- * Undefined where /proc is unavailable (e.g. macOS).
15443
- */
15444
- privateBytes: number().optional(),
15445
- /**
15446
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15447
- * code shared copy-on-write across runners. Undefined on macOS.
15448
- */
15449
- sharedBytes: number().optional()
15341
+ object({
15342
+ kind: literal("url"),
15343
+ url: string(),
15344
+ sha256: string().optional()
15345
+ }),
15346
+ object({
15347
+ kind: literal("path"),
15348
+ path: string()
15349
+ })
15350
+ ]);
15351
+ var ManagedRuntimeConfigSchema = object({
15352
+ /** WHERE the runtime lives — hub or any agent. */
15353
+ nodeId: string(),
15354
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15355
+ engine: _enum(["llama-cpp"]),
15356
+ model: ManagedModelRefSchema,
15357
+ contextSize: number().int().default(4096),
15358
+ /** 0 = CPU-only. */
15359
+ gpuLayers: number().int().default(0),
15360
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15361
+ threads: number().int().optional(),
15362
+ /** Concurrent slots. */
15363
+ parallel: number().int().default(1),
15364
+ /** Else lazy: first generate boots it. */
15365
+ autoStart: boolean().default(false),
15366
+ /** 0 = never; frees RAM after quiet periods. */
15367
+ idleStopMinutes: number().int().default(30)
15450
15368
  });
15451
- var AddonInstanceSchema = object({
15452
- addonId: string(),
15369
+ var LlmRuntimeStatusSchema = object({
15370
+ /** Status is ALWAYS node-qualified. */
15453
15371
  nodeId: string(),
15454
- role: _enum(["hub", "worker"]),
15455
- pid: number(),
15456
15372
  state: _enum([
15457
- "starting",
15458
- "running",
15459
- "stopping",
15460
15373
  "stopped",
15461
- "crashed"
15462
- ]),
15463
- uptimeSec: number()
15464
- });
15465
- var NodeProcessSchema = object({
15466
- pid: number(),
15467
- ppid: number(),
15468
- pgid: number(),
15469
- classification: _enum([
15470
- "root",
15471
- "managed",
15472
- "system",
15473
- "ghost"
15374
+ "downloading",
15375
+ "starting",
15376
+ "ready",
15377
+ "crashed",
15378
+ "failed"
15474
15379
  ]),
15475
- /** `$process` addon binding when `managed`, else null. */
15476
- addonId: string().nullable(),
15477
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15478
- nodeId: string().nullable(),
15479
- /** Truncated command line. */
15480
- command: string(),
15481
- cpuPercent: number(),
15482
- memoryRssBytes: number(),
15483
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15484
- uptimeSec: number(),
15485
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15486
- orphaned: boolean()
15487
- });
15488
- var KillProcessInputSchema = object({
15489
- pid: number(),
15490
- /** Force = SIGKILL. Default is SIGTERM. */
15491
- force: boolean().optional()
15492
- });
15493
- var KillProcessResultSchema = object({
15494
- success: boolean(),
15495
- reason: string().optional(),
15496
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15497
- });
15498
- var DumpHeapSnapshotInputSchema = object({
15499
- /** The addon whose runner should dump a heap snapshot. */
15500
- addonId: string() });
15501
- var DumpHeapSnapshotResultSchema = object({
15502
- success: boolean(),
15503
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15504
- path: string().optional(),
15505
- /** Process pid that was signalled. */
15506
15380
  pid: number().optional(),
15507
- reason: string().optional()
15381
+ port: number().optional(),
15382
+ modelPath: string().optional(),
15383
+ modelId: string().optional(),
15384
+ downloadProgress: number().min(0).max(1).optional(),
15385
+ lastError: string().optional(),
15386
+ crashesInWindow: number(),
15387
+ /** Child RSS (sampled best-effort). */
15388
+ memoryBytes: number().optional(),
15389
+ vramBytes: number().optional()
15508
15390
  });
15509
- var SystemMetricsSchema = object({
15510
- cpuPercent: number(),
15511
- memoryPercent: number(),
15512
- memoryUsedMB: number(),
15513
- memoryTotalMB: number(),
15514
- diskPercent: number().optional(),
15515
- temperature: number().optional(),
15516
- gpuPercent: number().optional(),
15517
- gpuMemoryPercent: number().optional()
15391
+ var LlmNodeModelSchema = object({
15392
+ file: string(),
15393
+ sizeBytes: number(),
15394
+ catalogId: string().optional(),
15395
+ installedAt: number().optional()
15518
15396
  });
15519
- 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, {
15397
+ var LlmRuntimeDiskUsageSchema = object({
15398
+ nodeId: string(),
15399
+ modelsBytes: number(),
15400
+ freeBytes: number().optional()
15401
+ });
15402
+ method(LlmGenerateBaseInputSchema.extend({
15403
+ images: array(LlmImageSchema).optional(),
15404
+ runtime: ManagedRuntimeConfigSchema,
15405
+ /** The managed profile's timeout, threaded by the hub provider. */
15406
+ timeoutMs: number().int().positive().optional()
15407
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15520
15408
  kind: "mutation",
15521
15409
  auth: "admin"
15522
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15410
+ }), method(object({}), _void(), {
15523
15411
  kind: "mutation",
15524
15412
  auth: "admin"
15525
- });
15526
- method(object({
15527
- sourceUrl: string(),
15528
- metadata: ModelConvertMetadataSchema,
15529
- targets: array(ConvertTargetSchema).min(1).readonly(),
15530
- calibrationRef: string().optional(),
15531
- sessionId: string().optional()
15532
- }), ConvertResultSchema, {
15413
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15533
15414
  kind: "mutation",
15534
- auth: "admin",
15535
- timeoutMs: 6e5
15536
- });
15537
- method(object({
15538
- nodeId: string(),
15539
- modelId: string(),
15540
- format: _enum(MODEL_FORMATS),
15541
- entry: ModelCatalogEntrySchema
15542
- }), object({
15543
- ok: boolean(),
15544
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15545
- sha256: string(),
15546
- bytes: number(),
15547
- /** The target node's modelsDir the artifact landed in. */
15548
- path: string()
15549
- }), {
15415
+ auth: "admin"
15416
+ }), method(object({ file: string() }), _void(), {
15550
15417
  kind: "mutation",
15551
15418
  auth: "admin"
15552
- });
15419
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15553
15420
  /**
15554
- * `mqtt-broker` — broker-registry cap.
15555
- *
15556
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15557
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15558
- * and (b) the connection details a consumer addon needs to spin up
15559
- * its OWN `mqtt.js` client.
15421
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15422
+ * methods concat-fan across providers; single-row methods route to ONE
15423
+ * provider by the `addonId` in the call input (the notification-output
15424
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15425
+ * (hub-placed); the cap stays open for future providers.
15560
15426
  *
15561
- * Why: pub/sub routing over the system event-bus loses fidelity
15562
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15563
- * refcount bookkeeping that addons would rather own themselves. The
15427
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15428
+ * `apiKey` is a password field providers REDACT it on read and merge on
15429
+ * write; a stored key NEVER round-trips to a client.
15430
+ */
15431
+ var LlmProfileKindSchema = _enum([
15432
+ "openai-compatible",
15433
+ "openai",
15434
+ "anthropic",
15435
+ "google",
15436
+ "managed-local"
15437
+ ]);
15438
+ var LlmProfileSchema = object({
15439
+ id: string(),
15440
+ name: string(),
15441
+ kind: LlmProfileKindSchema,
15442
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15443
+ addonId: string(),
15444
+ enabled: boolean(),
15445
+ /** Vendor model id, or the managed runtime's loaded model. */
15446
+ model: string(),
15447
+ /** Required for openai-compatible; override for cloud kinds. */
15448
+ baseUrl: string().optional(),
15449
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15450
+ apiKey: string().optional(),
15451
+ supportsVision: boolean(),
15452
+ temperature: number().min(0).max(2).optional(),
15453
+ maxTokens: number().int().positive().optional(),
15454
+ timeoutMs: number().int().positive().default(6e4),
15455
+ extraHeaders: record(string(), string()).optional(),
15456
+ /** kind === 'managed-local' only (spec §4). */
15457
+ runtime: ManagedRuntimeConfigSchema.optional()
15458
+ });
15459
+ /** ConfigUISchema tree passed through untyped on the wire (the
15460
+ * notification-output `ConfigSchemaPassthrough` precedent at
15461
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15462
+ var ConfigSchemaPassthrough$1 = unknown();
15463
+ var LlmProfileKindDescriptorSchema = object({
15464
+ kind: LlmProfileKindSchema,
15465
+ label: string(),
15466
+ icon: string(),
15467
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15468
+ addonId: string(),
15469
+ configSchema: ConfigSchemaPassthrough$1
15470
+ });
15471
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15472
+ var LlmDefaultSchema = object({
15473
+ selector: LlmDefaultSelectorSchema,
15474
+ profileId: string()
15475
+ });
15476
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15477
+ var LlmUsageRollupSchema = object({
15478
+ day: string(),
15479
+ consumer: string(),
15480
+ profileId: string(),
15481
+ calls: number(),
15482
+ okCalls: number(),
15483
+ errorCalls: number(),
15484
+ inputTokens: number(),
15485
+ outputTokens: number(),
15486
+ avgLatencyMs: number()
15487
+ });
15488
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15489
+ var ManagedModelCatalogEntrySchema = object({
15490
+ id: string(),
15491
+ label: string(),
15492
+ family: string(),
15493
+ purpose: _enum(["text", "vision"]),
15494
+ url: string(),
15495
+ sha256: string(),
15496
+ sizeBytes: number(),
15497
+ quantization: string(),
15498
+ /** Load-time guidance shown in the picker. */
15499
+ minRamBytes: number(),
15500
+ contextSizeDefault: number().int(),
15501
+ /** Vision models: companion projector file. */
15502
+ mmprojUrl: string().optional()
15503
+ });
15504
+ var LlmRuntimeNodeSchema = object({
15505
+ nodeId: string(),
15506
+ reachable: boolean(),
15507
+ status: LlmRuntimeStatusSchema.optional(),
15508
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15509
+ error: string().optional()
15510
+ });
15511
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15512
+ var ProfileRefInputSchema = object({
15513
+ addonId: string(),
15514
+ profileId: string()
15515
+ });
15516
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15517
+ kind: "mutation",
15518
+ auth: "admin"
15519
+ }), method(ProfileRefInputSchema, _void(), {
15520
+ kind: "mutation",
15521
+ auth: "admin"
15522
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15523
+ kind: "mutation",
15524
+ auth: "admin"
15525
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15526
+ selector: LlmDefaultSelectorSchema,
15527
+ profileId: string().nullable()
15528
+ }), _void(), {
15529
+ kind: "mutation",
15530
+ auth: "admin"
15531
+ }), method(object({
15532
+ since: number().optional(),
15533
+ until: number().optional(),
15534
+ consumer: string().optional(),
15535
+ profileId: string().optional()
15536
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15537
+ nodeId: string(),
15538
+ model: ManagedModelRefSchema
15539
+ }), _void(), {
15540
+ kind: "mutation",
15541
+ auth: "admin"
15542
+ }), method(object({
15543
+ nodeId: string(),
15544
+ file: string()
15545
+ }), _void(), {
15546
+ kind: "mutation",
15547
+ auth: "admin"
15548
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15549
+ kind: "mutation",
15550
+ auth: "admin"
15551
+ }), method(ProfileRefInputSchema, _void(), {
15552
+ kind: "mutation",
15553
+ auth: "admin"
15554
+ });
15555
+ var LogLevelSchema = _enum([
15556
+ "debug",
15557
+ "info",
15558
+ "warn",
15559
+ "error"
15560
+ ]);
15561
+ var LogEntrySchema = object({
15562
+ timestamp: date(),
15563
+ level: LogLevelSchema,
15564
+ scope: array(string()),
15565
+ message: string(),
15566
+ meta: record(string(), unknown()).optional(),
15567
+ tags: record(string(), string()).optional()
15568
+ });
15569
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15570
+ scope: array(string()).optional(),
15571
+ level: LogLevelSchema.optional(),
15572
+ since: date().optional(),
15573
+ until: date().optional(),
15574
+ limit: number().optional(),
15575
+ tags: record(string(), string()).optional()
15576
+ }), array(LogEntrySchema).readonly());
15577
+ /**
15578
+ * `login-method` — collection cap through which auth addons contribute
15579
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15580
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15581
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15582
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15583
+ * procedure aggregates them for the unauthenticated login page.
15584
+ *
15585
+ * A contribution is a discriminated union on `kind`:
15586
+ *
15587
+ * - `redirect` — a declarative button. The login page renders a generic
15588
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15589
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15590
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15591
+ * login page needs NO change.
15592
+ *
15593
+ * - `widget` — a Module-Federation widget the login page mounts (via
15594
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15595
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15596
+ * mechanism kept for future use; no shipped addon uses it on the login
15597
+ * page (the passkey ceremony below runs natively in the shell instead).
15598
+ *
15599
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15600
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15601
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15602
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15603
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15604
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15605
+ * enrollment state is never leaked pre-auth; visibility is a shell
15606
+ * decision.
15607
+ *
15608
+ * Every contribution carries a `stage`:
15609
+ * - `primary` — shown on the first credentials screen (OIDC /
15610
+ * magic-link buttons; a future usernameless passkey).
15611
+ * - `second-factor` — shown AFTER the password leg, gated on the
15612
+ * returned `factors` (passkey-as-2FA today).
15613
+ *
15614
+ * `mount: skip` — the cap is read server-side by the core auth router
15615
+ * (`registry.getCollection('login-method')`), never mounted as its own
15616
+ * tRPC router.
15617
+ */
15618
+ /** When a login method renders in the two-phase login flow. */
15619
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15620
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15621
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15622
+ object({
15623
+ kind: literal("redirect"),
15624
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15625
+ id: string(),
15626
+ /** Operator-facing button label. */
15627
+ label: string(),
15628
+ /** lucide-react icon name. */
15629
+ icon: string().optional(),
15630
+ /** Addon-owned HTTP route the button navigates to (GET). */
15631
+ startUrl: string(),
15632
+ stage: LoginStageEnum
15633
+ }),
15634
+ object({
15635
+ kind: literal("widget"),
15636
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15637
+ id: string(),
15638
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15639
+ addonId: string(),
15640
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15641
+ bundle: string(),
15642
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15643
+ remote: WidgetRemoteSchema,
15644
+ stage: LoginStageEnum
15645
+ }),
15646
+ object({
15647
+ kind: literal("passkey"),
15648
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15649
+ id: string(),
15650
+ /** Operator-facing button label. */
15651
+ label: string(),
15652
+ stage: LoginStageEnum,
15653
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15654
+ rpId: string(),
15655
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15656
+ origin: string().nullable()
15657
+ })
15658
+ ]);
15659
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15660
+ var CpuBreakdownSchema = object({
15661
+ total: number(),
15662
+ user: number(),
15663
+ system: number(),
15664
+ irq: number(),
15665
+ nice: number(),
15666
+ loadAvg: tuple([
15667
+ number(),
15668
+ number(),
15669
+ number()
15670
+ ]),
15671
+ cores: number()
15672
+ });
15673
+ var MemoryInfoSchema = object({
15674
+ percent: number(),
15675
+ totalBytes: number(),
15676
+ usedBytes: number(),
15677
+ availableBytes: number(),
15678
+ swapUsedBytes: number(),
15679
+ swapTotalBytes: number()
15680
+ });
15681
+ var DiskIoSnapshotSchema = object({
15682
+ readBytes: number(),
15683
+ writeBytes: number(),
15684
+ readOps: number(),
15685
+ writeOps: number(),
15686
+ timestampMs: number()
15687
+ });
15688
+ var NetworkIoSnapshotSchema = object({
15689
+ rxBytes: number(),
15690
+ txBytes: number(),
15691
+ rxPackets: number(),
15692
+ txPackets: number(),
15693
+ rxErrors: number(),
15694
+ txErrors: number(),
15695
+ timestampMs: number()
15696
+ });
15697
+ var MetricsGpuInfoSchema = object({
15698
+ utilization: number(),
15699
+ model: string(),
15700
+ memoryUsedBytes: number(),
15701
+ memoryTotalBytes: number(),
15702
+ temperature: number().nullable()
15703
+ });
15704
+ var ProcessResourceInfoSchema = object({
15705
+ openFds: number(),
15706
+ threadCount: number(),
15707
+ activeHandles: number(),
15708
+ activeRequests: number()
15709
+ });
15710
+ var PressureAvgsSchema = object({
15711
+ avg10: number(),
15712
+ avg60: number(),
15713
+ avg300: number()
15714
+ });
15715
+ var PressureInfoSchema = object({
15716
+ some: PressureAvgsSchema,
15717
+ full: PressureAvgsSchema.nullable()
15718
+ });
15719
+ var SystemResourceSnapshotSchema = object({
15720
+ cpu: CpuBreakdownSchema,
15721
+ memory: MemoryInfoSchema,
15722
+ gpu: MetricsGpuInfoSchema.nullable(),
15723
+ network: NetworkIoSnapshotSchema,
15724
+ disk: DiskIoSnapshotSchema,
15725
+ pressure: object({
15726
+ cpu: PressureInfoSchema.nullable(),
15727
+ memory: PressureInfoSchema.nullable(),
15728
+ io: PressureInfoSchema.nullable()
15729
+ }),
15730
+ process: ProcessResourceInfoSchema,
15731
+ cpuTemperature: number().nullable(),
15732
+ timestampMs: number()
15733
+ });
15734
+ var DiskSpaceInfoSchema = object({
15735
+ path: string(),
15736
+ totalBytes: number(),
15737
+ usedBytes: number(),
15738
+ availableBytes: number(),
15739
+ percent: number()
15740
+ });
15741
+ var PidResourceStatsSchema = object({
15742
+ pid: number(),
15743
+ cpu: number(),
15744
+ memory: number(),
15745
+ /**
15746
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15747
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15748
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15749
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15750
+ * Undefined where /proc is unavailable (e.g. macOS).
15751
+ */
15752
+ privateBytes: number().optional(),
15753
+ /**
15754
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15755
+ * code shared copy-on-write across runners. Undefined on macOS.
15756
+ */
15757
+ sharedBytes: number().optional()
15758
+ });
15759
+ var AddonInstanceSchema = object({
15760
+ addonId: string(),
15761
+ nodeId: string(),
15762
+ role: _enum(["hub", "worker"]),
15763
+ pid: number(),
15764
+ state: _enum([
15765
+ "starting",
15766
+ "running",
15767
+ "stopping",
15768
+ "stopped",
15769
+ "crashed"
15770
+ ]),
15771
+ uptimeSec: number()
15772
+ });
15773
+ var NodeProcessSchema = object({
15774
+ pid: number(),
15775
+ ppid: number(),
15776
+ pgid: number(),
15777
+ classification: _enum([
15778
+ "root",
15779
+ "managed",
15780
+ "system",
15781
+ "ghost"
15782
+ ]),
15783
+ /** `$process` addon binding when `managed`, else null. */
15784
+ addonId: string().nullable(),
15785
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15786
+ nodeId: string().nullable(),
15787
+ /** Truncated command line. */
15788
+ command: string(),
15789
+ cpuPercent: number(),
15790
+ memoryRssBytes: number(),
15791
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15792
+ uptimeSec: number(),
15793
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15794
+ orphaned: boolean()
15795
+ });
15796
+ var KillProcessInputSchema = object({
15797
+ pid: number(),
15798
+ /** Force = SIGKILL. Default is SIGTERM. */
15799
+ force: boolean().optional()
15800
+ });
15801
+ var KillProcessResultSchema = object({
15802
+ success: boolean(),
15803
+ reason: string().optional(),
15804
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15805
+ });
15806
+ var DumpHeapSnapshotInputSchema = object({
15807
+ /** The addon whose runner should dump a heap snapshot. */
15808
+ addonId: string() });
15809
+ var DumpHeapSnapshotResultSchema = object({
15810
+ success: boolean(),
15811
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15812
+ path: string().optional(),
15813
+ /** Process pid that was signalled. */
15814
+ pid: number().optional(),
15815
+ reason: string().optional()
15816
+ });
15817
+ var SystemMetricsSchema = object({
15818
+ cpuPercent: number(),
15819
+ memoryPercent: number(),
15820
+ memoryUsedMB: number(),
15821
+ memoryTotalMB: number(),
15822
+ diskPercent: number().optional(),
15823
+ temperature: number().optional(),
15824
+ gpuPercent: number().optional(),
15825
+ gpuMemoryPercent: number().optional()
15826
+ });
15827
+ 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, {
15828
+ kind: "mutation",
15829
+ auth: "admin"
15830
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15831
+ kind: "mutation",
15832
+ auth: "admin"
15833
+ });
15834
+ method(object({
15835
+ sourceUrl: string(),
15836
+ metadata: ModelConvertMetadataSchema,
15837
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15838
+ calibrationRef: string().optional(),
15839
+ sessionId: string().optional()
15840
+ }), ConvertResultSchema, {
15841
+ kind: "mutation",
15842
+ auth: "admin",
15843
+ timeoutMs: 6e5
15844
+ });
15845
+ method(object({
15846
+ nodeId: string(),
15847
+ modelId: string(),
15848
+ format: _enum(MODEL_FORMATS),
15849
+ entry: ModelCatalogEntrySchema
15850
+ }), object({
15851
+ ok: boolean(),
15852
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15853
+ sha256: string(),
15854
+ bytes: number(),
15855
+ /** The target node's modelsDir the artifact landed in. */
15856
+ path: string()
15857
+ }), {
15858
+ kind: "mutation",
15859
+ auth: "admin"
15860
+ });
15861
+ /**
15862
+ * `mqtt-broker` — broker-registry cap.
15863
+ *
15864
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15865
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15866
+ * and (b) the connection details a consumer addon needs to spin up
15867
+ * its OWN `mqtt.js` client.
15868
+ *
15869
+ * Why: pub/sub routing over the system event-bus loses fidelity
15870
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15871
+ * refcount bookkeeping that addons would rather own themselves. The
15564
15872
  * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15565
15873
  * features anyway — give it the connection config, get out of the way.
15566
15874
  *
@@ -15789,389 +16097,585 @@ var TargetKindLevelSchema = object({
15789
16097
  silent: boolean().optional(),
15790
16098
  noPush: boolean().optional()
15791
16099
  }).optional(),
15792
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15793
- requires: array(string()).optional(),
15794
- description: string().optional()
15795
- });
15796
- /** The full capability block consulted before dispatch. */
15797
- var TargetKindCapsSchema = object({
15798
- attachments: object({
15799
- mediaTypes: array(AttachmentMediaTypeSchema),
15800
- mode: _enum([
15801
- "url",
15802
- "bytes",
15803
- "both"
15804
- ]),
15805
- max: number().int().nonnegative(),
15806
- maxBytes: number().int().positive().optional()
15807
- }),
15808
- /** Max action buttons (0 = none). */
15809
- actions: number().int().nonnegative(),
15810
- levels: array(TargetKindLevelSchema),
15811
- format: array(NotificationFormatSchema),
15812
- clickUrl: boolean(),
15813
- sound: boolean(),
15814
- ttl: boolean(),
15815
- bodyMaxLen: number().int().positive()
15816
- });
15817
- /**
15818
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15819
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15820
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
15821
- * the union is large and not meant for runtime validation here; the exported
15822
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15823
- */
15824
- var ConfigSchemaPassthrough$1 = unknown();
15825
- var TargetKindSchema = object({
15826
- kind: string(),
15827
- label: string(),
15828
- icon: string(),
15829
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15830
- addonId: string(),
15831
- configSchema: ConfigSchemaPassthrough$1,
15832
- supportsDiscovery: boolean(),
15833
- caps: TargetKindCapsSchema
15834
- });
15835
- /**
15836
- * A persisted target. `config` holds secrets; providers REDACT secret fields
15837
- * (return a presence marker only) when serving `listTargets` — never
15838
- * round-trip a stored secret to the UI.
15839
- */
15840
- var TargetSchema = object({
15841
- id: string(),
15842
- name: string(),
15843
- kind: string(),
15844
- addonId: string(),
15845
- enabled: boolean(),
15846
- config: record(string(), unknown())
15847
- });
15848
- /** A discovery-surfaced candidate (config is partial + non-secret). */
15849
- var DiscoveredTargetSchema = object({
15850
- kind: string(),
15851
- suggestedName: string(),
15852
- config: record(string(), unknown())
15853
- });
15854
- /** The degrade engine's report — what was resolved / dropped / degraded. */
15855
- var RenderedAsSchema = object({
15856
- level: string(),
15857
- format: NotificationFormatSchema,
15858
- attachmentsSent: number().int().nonnegative(),
15859
- actionsSent: number().int().nonnegative(),
15860
- truncated: boolean(),
15861
- dropped: array(string())
15862
- });
15863
- var SendResultSchema = object({
15864
- success: boolean(),
15865
- error: string().optional(),
15866
- renderedAs: RenderedAsSchema.optional()
15867
- });
15868
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
15869
- var TestResultSchema = SendResultSchema;
15870
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
15871
- kind: string(),
15872
- config: record(string(), unknown()).optional()
15873
- }), array(DiscoveredTargetSchema)), method(object({
15874
- targetId: string(),
15875
- notification: NotificationSchema
15876
- }), SendResultSchema, { kind: "mutation" }), method(object({
15877
- targetId: string(),
15878
- sample: NotificationSchema.optional()
15879
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
15880
- targetId: string(),
15881
- enabled: boolean()
15882
- }), _void(), { kind: "mutation" });
15883
- /**
15884
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15885
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15886
- * caps stay wire-compatible without a circular cap→cap import.
15887
- *
15888
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15889
- * every transport tier structurally, and failed calls still write usage rows.
15890
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15891
- */
15892
- var LlmUsageSchema = object({
15893
- inputTokens: number(),
15894
- outputTokens: number()
15895
- });
15896
- var LlmErrorCodeSchema = _enum([
15897
- "timeout",
15898
- "rate-limited",
15899
- "auth",
15900
- "refusal",
15901
- "bad-request",
15902
- "unavailable",
15903
- "no-profile",
15904
- "budget-exceeded",
15905
- "adapter-error"
15906
- ]);
15907
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15908
- ok: literal(true),
15909
- text: string(),
15910
- model: string(),
15911
- usage: LlmUsageSchema,
15912
- truncated: boolean(),
15913
- latencyMs: number()
15914
- }), object({
15915
- ok: literal(false),
15916
- code: LlmErrorCodeSchema,
15917
- message: string(),
15918
- retryAfterMs: number().optional()
15919
- })]);
15920
- /**
15921
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15922
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15923
- * notification-output.cap.ts:27-31 precedents).
15924
- */
15925
- var LlmImageSchema = object({
15926
- bytes: _instanceof(Uint8Array),
15927
- mimeType: string()
15928
- });
15929
- var LlmGenerateBaseInputSchema = object({
15930
- /** Collection routing (the notification-output posture). */
15931
- addonId: string().optional(),
15932
- /** Explicit profile; else the resolution chain (spec §3). */
15933
- profileId: string().optional(),
15934
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15935
- consumer: string(),
15936
- system: string().optional(),
15937
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15938
- prompt: string(),
15939
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15940
- jsonSchema: record(string(), unknown()).optional(),
15941
- /** Per-call override of the profile default. */
15942
- maxTokens: number().int().positive().optional(),
15943
- temperature: number().optional()
15944
- });
15945
- /**
15946
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15947
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15948
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15949
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15950
- * this only through the `llm` cap's methods.
15951
- *
15952
- * One running llama-server child per node in v1 (models are RAM-heavy).
15953
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15954
- * watchdog — operator decision #3).
15955
- */
15956
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15957
- object({
15958
- kind: literal("catalog"),
15959
- catalogId: string()
15960
- }),
15961
- object({
15962
- kind: literal("url"),
15963
- url: string(),
15964
- sha256: string().optional()
15965
- }),
15966
- object({
15967
- kind: literal("path"),
15968
- path: string()
15969
- })
15970
- ]);
15971
- var ManagedRuntimeConfigSchema = object({
15972
- /** WHERE the runtime lives — hub or any agent. */
15973
- nodeId: string(),
15974
- /** Closed for v1; 'ollama' is a v2 candidate. */
15975
- engine: _enum(["llama-cpp"]),
15976
- model: ManagedModelRefSchema,
15977
- contextSize: number().int().default(4096),
15978
- /** 0 = CPU-only. */
15979
- gpuLayers: number().int().default(0),
15980
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15981
- threads: number().int().optional(),
15982
- /** Concurrent slots. */
15983
- parallel: number().int().default(1),
15984
- /** Else lazy: first generate boots it. */
15985
- autoStart: boolean().default(false),
15986
- /** 0 = never; frees RAM after quiet periods. */
15987
- idleStopMinutes: number().int().default(30)
15988
- });
15989
- var LlmRuntimeStatusSchema = object({
15990
- /** Status is ALWAYS node-qualified. */
15991
- nodeId: string(),
15992
- state: _enum([
15993
- "stopped",
15994
- "downloading",
15995
- "starting",
15996
- "ready",
15997
- "crashed",
15998
- "failed"
15999
- ]),
16000
- pid: number().optional(),
16001
- port: number().optional(),
16002
- modelPath: string().optional(),
16003
- modelId: string().optional(),
16004
- downloadProgress: number().min(0).max(1).optional(),
16005
- lastError: string().optional(),
16006
- crashesInWindow: number(),
16007
- /** Child RSS (sampled best-effort). */
16008
- memoryBytes: number().optional(),
16009
- vramBytes: number().optional()
16100
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16101
+ requires: array(string()).optional(),
16102
+ description: string().optional()
16010
16103
  });
16011
- var LlmNodeModelSchema = object({
16012
- file: string(),
16013
- sizeBytes: number(),
16014
- catalogId: string().optional(),
16015
- installedAt: number().optional()
16104
+ /** The full capability block consulted before dispatch. */
16105
+ var TargetKindCapsSchema = object({
16106
+ attachments: object({
16107
+ mediaTypes: array(AttachmentMediaTypeSchema),
16108
+ mode: _enum([
16109
+ "url",
16110
+ "bytes",
16111
+ "both"
16112
+ ]),
16113
+ max: number().int().nonnegative(),
16114
+ maxBytes: number().int().positive().optional()
16115
+ }),
16116
+ /** Max action buttons (0 = none). */
16117
+ actions: number().int().nonnegative(),
16118
+ levels: array(TargetKindLevelSchema),
16119
+ format: array(NotificationFormatSchema),
16120
+ clickUrl: boolean(),
16121
+ sound: boolean(),
16122
+ ttl: boolean(),
16123
+ bodyMaxLen: number().int().positive()
16016
16124
  });
16017
- var LlmRuntimeDiskUsageSchema = object({
16018
- nodeId: string(),
16019
- modelsBytes: number(),
16020
- freeBytes: number().optional()
16125
+ /**
16126
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16127
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16128
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16129
+ * the union is large and not meant for runtime validation here; the exported
16130
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16131
+ */
16132
+ var ConfigSchemaPassthrough = unknown();
16133
+ var TargetKindSchema = object({
16134
+ kind: string(),
16135
+ label: string(),
16136
+ icon: string(),
16137
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16138
+ addonId: string(),
16139
+ configSchema: ConfigSchemaPassthrough,
16140
+ supportsDiscovery: boolean(),
16141
+ caps: TargetKindCapsSchema
16021
16142
  });
16022
- method(LlmGenerateBaseInputSchema.extend({
16023
- images: array(LlmImageSchema).optional(),
16024
- runtime: ManagedRuntimeConfigSchema,
16025
- /** The managed profile's timeout, threaded by the hub provider. */
16026
- timeoutMs: number().int().positive().optional()
16027
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16028
- kind: "mutation",
16029
- auth: "admin"
16030
- }), method(object({}), _void(), {
16031
- kind: "mutation",
16032
- auth: "admin"
16033
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16034
- kind: "mutation",
16035
- auth: "admin"
16036
- }), method(object({ file: string() }), _void(), {
16037
- kind: "mutation",
16038
- auth: "admin"
16039
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16040
16143
  /**
16041
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16042
- * methods concat-fan across providers; single-row methods route to ONE
16043
- * provider by the `addonId` in the call input (the notification-output
16044
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16045
- * (hub-placed); the cap stays open for future providers.
16046
- *
16047
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16048
- * `apiKey` is a password field — providers REDACT it on read and merge on
16049
- * write; a stored key NEVER round-trips to a client.
16144
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16145
+ * (return a presence marker only) when serving `listTargets` — never
16146
+ * round-trip a stored secret to the UI.
16050
16147
  */
16051
- var LlmProfileKindSchema = _enum([
16052
- "openai-compatible",
16053
- "openai",
16054
- "anthropic",
16055
- "google",
16056
- "managed-local"
16057
- ]);
16058
- var LlmProfileSchema = object({
16148
+ var TargetSchema = object({
16059
16149
  id: string(),
16060
16150
  name: string(),
16061
- kind: LlmProfileKindSchema,
16062
- /** Stamped by the provider — keeps the fanned catalog routable. */
16151
+ kind: string(),
16063
16152
  addonId: string(),
16064
16153
  enabled: boolean(),
16065
- /** Vendor model id, or the managed runtime's loaded model. */
16066
- model: string(),
16067
- /** Required for openai-compatible; override for cloud kinds. */
16068
- baseUrl: string().optional(),
16069
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16070
- apiKey: string().optional(),
16071
- supportsVision: boolean(),
16072
- temperature: number().min(0).max(2).optional(),
16073
- maxTokens: number().int().positive().optional(),
16074
- timeoutMs: number().int().positive().default(6e4),
16075
- extraHeaders: record(string(), string()).optional(),
16076
- /** kind === 'managed-local' only (spec §4). */
16077
- runtime: ManagedRuntimeConfigSchema.optional()
16154
+ config: record(string(), unknown())
16078
16155
  });
16079
- /** ConfigUISchema tree passed through untyped on the wire (the
16080
- * notification-output `ConfigSchemaPassthrough` precedent at
16081
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16082
- var ConfigSchemaPassthrough = unknown();
16083
- var LlmProfileKindDescriptorSchema = object({
16084
- kind: LlmProfileKindSchema,
16085
- label: string(),
16086
- icon: string(),
16087
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16088
- addonId: string(),
16089
- configSchema: ConfigSchemaPassthrough
16156
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16157
+ var DiscoveredTargetSchema = object({
16158
+ kind: string(),
16159
+ suggestedName: string(),
16160
+ config: record(string(), unknown())
16090
16161
  });
16091
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16092
- var LlmDefaultSchema = object({
16093
- selector: LlmDefaultSelectorSchema,
16094
- profileId: string()
16162
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16163
+ var RenderedAsSchema = object({
16164
+ level: string(),
16165
+ format: NotificationFormatSchema,
16166
+ attachmentsSent: number().int().nonnegative(),
16167
+ actionsSent: number().int().nonnegative(),
16168
+ truncated: boolean(),
16169
+ dropped: array(string())
16095
16170
  });
16096
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16097
- var LlmUsageRollupSchema = object({
16098
- day: string(),
16099
- consumer: string(),
16100
- profileId: string(),
16101
- calls: number(),
16102
- okCalls: number(),
16103
- errorCalls: number(),
16104
- inputTokens: number(),
16105
- outputTokens: number(),
16106
- avgLatencyMs: number()
16171
+ var SendResultSchema = object({
16172
+ success: boolean(),
16173
+ error: string().optional(),
16174
+ renderedAs: RenderedAsSchema.optional()
16107
16175
  });
16108
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16109
- var ManagedModelCatalogEntrySchema = object({
16176
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
16177
+ var TestResultSchema = SendResultSchema;
16178
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16179
+ kind: string(),
16180
+ config: record(string(), unknown()).optional()
16181
+ }), array(DiscoveredTargetSchema)), method(object({
16182
+ targetId: string(),
16183
+ notification: NotificationSchema
16184
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16185
+ targetId: string(),
16186
+ sample: NotificationSchema.optional()
16187
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16188
+ targetId: string(),
16189
+ enabled: boolean()
16190
+ }), _void(), { kind: "mutation" });
16191
+ /**
16192
+ * notification-rules — the Notification Center rule surface (P1 core).
16193
+ *
16194
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16195
+ * (operator decisions D-1/D-2/D-3 are binding):
16196
+ *
16197
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16198
+ * `notification-center` module), hooked on the durable persistence
16199
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16200
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16201
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16202
+ * FIRST persisted detection matching the conditions (per-track dedup,
16203
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16204
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16205
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16206
+ * by id; per-backend params are a passthrough blob capped by the
16207
+ * target kind's own caps/degrade engine).
16208
+ *
16209
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16210
+ * server-injected caller identity — the first `caller: 'required'`
16211
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16212
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16213
+ * windows, and the optional label/identity/plate matchers. User rules,
16214
+ * private zones, per-recipient fan-out and the wider condition table are
16215
+ * P2+ (see spec §7).
16216
+ *
16217
+ * All schemas here are the single source of truth — `NcRule` etc. are
16218
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16219
+ * schema/interface drift is explicitly not repeated).
16220
+ */
16221
+ /**
16222
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16223
+ * The value maps 1:1 onto the evaluated record kind:
16224
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16225
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16226
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16227
+ * change of a LINKED device, one row per linked camera)
16228
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16229
+ * delivery / pick-up)
16230
+ *
16231
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16232
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16233
+ * this one field keeps the schema additive — a rule still declares exactly
16234
+ * one trigger.
16235
+ */
16236
+ var NcDeliverySchema = _enum([
16237
+ "immediate",
16238
+ "track-end",
16239
+ "device-event",
16240
+ "package-event"
16241
+ ]);
16242
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16243
+ var NcScheduleSchema = object({
16244
+ windows: array(object({
16245
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16246
+ days: array(number().int().min(0).max(6)).min(1),
16247
+ startMinute: number().int().min(0).max(1439),
16248
+ endMinute: number().int().min(0).max(1439)
16249
+ })).min(1),
16250
+ /** IANA timezone; default = hub host timezone. */
16251
+ timezone: string().optional(),
16252
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16253
+ invert: boolean().optional()
16254
+ });
16255
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16256
+ var NcPlateMatcherSchema = object({
16257
+ values: array(string().min(1)).min(1),
16258
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16259
+ maxDistance: number().int().min(0).max(3).default(1)
16260
+ });
16261
+ /**
16262
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16263
+ * occupancy edge for a device — optionally narrowed to a single admin
16264
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16265
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16266
+ * - `became-free` — count crossed ≥ `count` → below it
16267
+ * - `>=` / `<=` — count is at/over or at/under `count`
16268
+ * `sustainSeconds` requires the condition hold continuously that long
16269
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16270
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16271
+ * the condition never matches. Confirmed edge-state survives addon restarts
16272
+ * (declared SQLite collection, reseeded on boot).
16273
+ */
16274
+ var NcOccupancyConditionSchema = object({
16275
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16276
+ zoneId: string().optional(),
16277
+ /** Object class to count; absent = any class. */
16278
+ className: string().optional(),
16279
+ op: _enum([
16280
+ "became-occupied",
16281
+ "became-free",
16282
+ ">=",
16283
+ "<="
16284
+ ]).default("became-occupied"),
16285
+ count: number().int().min(0).default(1),
16286
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16287
+ });
16288
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16289
+ var NcZoneConditionSchema = object({
16290
+ ids: array(string().min(1)).min(1),
16291
+ /** Quantifier over `ids` — at least one / every one visited. */
16292
+ match: _enum(["any", "all"]).default("any")
16293
+ });
16294
+ /**
16295
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16296
+ * membership lists are OR within the list (spec §2.3).
16297
+ */
16298
+ var NcConditionsSchema = object({
16299
+ /** Device scope — absent = all devices. */
16300
+ devices: array(number()).optional(),
16301
+ /** Detector class names (any overlap with the record's class set). */
16302
+ classes: array(string().min(1)).optional(),
16303
+ /** Veto classes — any overlap fails the rule. */
16304
+ classesExclude: array(string().min(1)).optional(),
16305
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16306
+ minConfidence: number().min(0).max(1).optional(),
16307
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16308
+ zones: NcZoneConditionSchema.optional(),
16309
+ /** Veto zones — any hit fails the rule. */
16310
+ zonesExclude: array(string().min(1)).optional(),
16311
+ /**
16312
+ * Exact (case-insensitive) match on the record's collapsed `label`
16313
+ * (identity name / plate text / subclass).
16314
+ */
16315
+ labelEquals: array(string().min(1)).optional(),
16316
+ /**
16317
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16318
+ * `label` (the identity display name propagated by the face pipeline) —
16319
+ * identity-ID matching rides in P2 when identity ids reach the record.
16320
+ */
16321
+ identities: array(string().min(1)).optional(),
16322
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16323
+ plates: NcPlateMatcherSchema.optional(),
16324
+ /**
16325
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16326
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16327
+ * identity display name). A record with NO label passes (nothing to
16328
+ * exclude), unlike the include variant which fails on an absent label.
16329
+ */
16330
+ identitiesExclude: array(string().min(1)).optional(),
16331
+ /**
16332
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16333
+ * TRACK-END only: importance is scored at track close, so it does not exist
16334
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16335
+ * close the value is threaded via the close-time info (the `Track` clone is
16336
+ * captured before the DB row is updated, so it would otherwise read stale).
16337
+ * Fails when the record carries no importance (never guess quality — the
16338
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16339
+ */
16340
+ minImportance: number().min(0).max(1).optional(),
16341
+ /**
16342
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16343
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16344
+ * lifespan, so a dwell condition never matches immediate delivery
16345
+ * (documented choice — the object-event record carries no `firstSeen`,
16346
+ * so dwell cannot be computed from what the subject actually carries).
16347
+ */
16348
+ minDwellSeconds: number().min(0).optional(),
16349
+ /**
16350
+ * Detection provenance filter. `any` (default / absent) matches every
16351
+ * source; otherwise the subject's source must equal it. Legacy records
16352
+ * with no stamped source are treated as `pipeline`. The union spans both
16353
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16354
+ * tracks carry `sensor`.
16355
+ */
16356
+ source: _enum([
16357
+ "pipeline",
16358
+ "onboard",
16359
+ "sensor",
16360
+ "any"
16361
+ ]).optional(),
16362
+ /**
16363
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16364
+ * detector `minConfidence` (that gates the object-detection score; this
16365
+ * gates the recognition/OCR match score). Fails when the subject carries
16366
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16367
+ * lives on the recognition result and reaches the subject at track close.
16368
+ *
16369
+ * What it measures precisely (plumbed at track close — the closer threads
16370
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16371
+ * `importance`): the BEST recognition match confidence observed for the
16372
+ * label the track carries at close — for a face, the peak cosine similarity
16373
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16374
+ * for a plate, the peak OCR read score of the best-held plate
16375
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16376
+ * one track the higher of the two is used. A track that ended with no
16377
+ * confident identity/plate match carries no value, so the condition fails
16378
+ * closed for it (an un-recognized subject).
16379
+ */
16380
+ minLabelConfidence: number().min(0).max(1).optional(),
16381
+ /**
16382
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16383
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16384
+ * against the token carried on the device-event subject (extracted from the
16385
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16386
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16387
+ * eventType, so gate those with {@link sensorKinds} instead.
16388
+ */
16389
+ eventTypeTokens: array(string().min(1)).optional(),
16390
+ /**
16391
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16392
+ * `contact`, `button`, `device-event`) — matched against the persisted
16393
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16394
+ */
16395
+ sensorKinds: array(string().min(1)).optional(),
16396
+ /**
16397
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16398
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16399
+ * when the subject's phase does not match (a subject always carries a phase
16400
+ * on the package-event trigger).
16401
+ */
16402
+ packagePhase: _enum([
16403
+ "delivered",
16404
+ "picked-up",
16405
+ "both"
16406
+ ]).optional(),
16407
+ /**
16408
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16409
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16410
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16411
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16412
+ */
16413
+ customZones: array(MaskPolygonShapeSchema).optional(),
16414
+ /**
16415
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16416
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16417
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16418
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16419
+ */
16420
+ occupancy: NcOccupancyConditionSchema.optional()
16421
+ });
16422
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16423
+ var NcRuleTargetSchema = object({
16424
+ /** `notification-output` Target id. */
16425
+ targetId: string().min(1),
16426
+ /**
16427
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16428
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16429
+ * degrade engine drops what the backend can't render.
16430
+ */
16431
+ params: record(string(), unknown()).optional()
16432
+ });
16433
+ /**
16434
+ * Media attachment policy (P1 still-image subset).
16435
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16436
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16437
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16438
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16439
+ * (or when the specific crop is missing) degrades to `best`, then
16440
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16441
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16442
+ * name), so the choice never drifts from the record that fired it.
16443
+ * - `keyFrame` — the clean scene frame (no subject box).
16444
+ * - `none` — no attachment.
16445
+ */
16446
+ var NcMediaPolicySchema = object({ attach: _enum([
16447
+ "best",
16448
+ "best-matching",
16449
+ "keyFrame",
16450
+ "none"
16451
+ ]).default("best") });
16452
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16453
+ var NcThrottleSchema = object({
16454
+ cooldownSec: number().int().min(0).max(86400).default(60),
16455
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16456
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16457
+ });
16458
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16459
+ var NcRuleInputSchema = object({
16460
+ name: string().min(1).max(200),
16461
+ enabled: boolean().default(true),
16462
+ delivery: NcDeliverySchema,
16463
+ conditions: NcConditionsSchema.default({}),
16464
+ schedule: NcScheduleSchema.optional(),
16465
+ targets: array(NcRuleTargetSchema).min(1),
16466
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16467
+ throttle: NcThrottleSchema.default({
16468
+ cooldownSec: 60,
16469
+ scope: "rule-device"
16470
+ }),
16471
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16472
+ template: object({
16473
+ title: string().max(500).optional(),
16474
+ body: string().max(2e3).optional()
16475
+ }).optional(),
16476
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16477
+ priority: number().int().min(1).max(5).default(3),
16478
+ /**
16479
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16480
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16481
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16482
+ */
16483
+ ownerUserId: string().optional()
16484
+ });
16485
+ /**
16486
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16487
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16488
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16489
+ * input), so it is added here explicitly to let the store's per-target opt-out
16490
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16491
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16492
+ * `updateRule` patch.
16493
+ */
16494
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16495
+ /** A persisted rule. */
16496
+ var NcRuleSchema = NcRuleInputSchema.extend({
16497
+ id: string(),
16498
+ /** userId of the admin who created the rule (server-stamped caller). */
16499
+ createdBy: string(),
16500
+ createdAt: number(),
16501
+ updatedAt: number(),
16502
+ /**
16503
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16504
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16505
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16506
+ */
16507
+ disabledTargetIds: array(string()).default([])
16508
+ });
16509
+ var NcTestResultSchema = object({
16510
+ recordId: string(),
16511
+ recordKind: _enum([
16512
+ "object-event",
16513
+ "track",
16514
+ "device-event",
16515
+ "package-event"
16516
+ ]),
16517
+ deviceId: number(),
16518
+ timestamp: number(),
16519
+ wouldFire: boolean(),
16520
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16521
+ failedCondition: string().optional(),
16522
+ className: string().optional(),
16523
+ label: string().optional()
16524
+ });
16525
+ var NcConditionDescriptorSchema = object({
16526
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16110
16527
  id: string(),
16528
+ group: _enum([
16529
+ "scope",
16530
+ "class",
16531
+ "zones",
16532
+ "quality",
16533
+ "label",
16534
+ "schedule",
16535
+ "device",
16536
+ "package",
16537
+ "occupancy"
16538
+ ]),
16111
16539
  label: string(),
16112
- family: string(),
16113
- purpose: _enum(["text", "vision"]),
16114
- url: string(),
16115
- sha256: string(),
16116
- sizeBytes: number(),
16117
- quantization: string(),
16118
- /** Load-time guidance shown in the picker. */
16119
- minRamBytes: number(),
16120
- contextSizeDefault: number().int(),
16121
- /** Vision models: companion projector file. */
16122
- mmprojUrl: string().optional()
16540
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16541
+ valueType: _enum([
16542
+ "deviceIdList",
16543
+ "stringList",
16544
+ "number01",
16545
+ "number",
16546
+ "sourceSelect",
16547
+ "zoneSelection",
16548
+ "zoneIdList",
16549
+ "schedule",
16550
+ "plateMatcher",
16551
+ "packagePhase",
16552
+ "polygonDraw",
16553
+ "occupancy"
16554
+ ]),
16555
+ operator: _enum([
16556
+ "in",
16557
+ "notIn",
16558
+ "anyOf",
16559
+ "allOf",
16560
+ "gte",
16561
+ "fuzzyIn",
16562
+ "withinSchedule"
16563
+ ]),
16564
+ /** Which delivery kinds the condition applies to. */
16565
+ appliesTo: array(NcDeliverySchema),
16566
+ phase: string(),
16567
+ description: string().optional()
16123
16568
  });
16124
- var LlmRuntimeNodeSchema = object({
16125
- nodeId: string(),
16126
- reachable: boolean(),
16127
- status: LlmRuntimeStatusSchema.optional(),
16128
- disk: LlmRuntimeDiskUsageSchema.optional(),
16129
- error: string().optional()
16569
+ /**
16570
+ * The delivery lifecycle status of a history row — a straight read of the
16571
+ * durable outbox row's own status (single source of truth):
16572
+ * - `pending` — enqueued, in-flight or retrying with backoff
16573
+ * - `sent` — delivered (terminal)
16574
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16575
+ * backend rejection / a deleted target (terminal; carries
16576
+ * the failure `error`)
16577
+ *
16578
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16579
+ * user dimension (quiet hours / snooze) and are additive when they land.
16580
+ */
16581
+ var NcHistoryStatusSchema = _enum([
16582
+ "pending",
16583
+ "sent",
16584
+ "dead"
16585
+ ]);
16586
+ /** The evaluated record kind a history row descends from (one per trigger). */
16587
+ var NcHistoryRecordKindSchema = _enum([
16588
+ "object-event",
16589
+ "track-end",
16590
+ "device-event",
16591
+ "package-event"
16592
+ ]);
16593
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16594
+ var NcHistorySubjectSchema = object({
16595
+ className: string(),
16596
+ label: string().optional(),
16597
+ confidence: number().optional(),
16598
+ zones: array(string()),
16599
+ timestamp: number()
16600
+ });
16601
+ /**
16602
+ * One delivery-history row. This is a read-only VIEW over the durable
16603
+ * outbox row (single source of truth — the same row the drain loop drives;
16604
+ * NO second write path, so history can never drift from delivery state).
16605
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16606
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16607
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16608
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16609
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16610
+ * P1 (admin scope only).
16611
+ */
16612
+ var NcHistoryEntrySchema = object({
16613
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16614
+ id: string(),
16615
+ ruleId: string(),
16616
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16617
+ ruleName: string(),
16618
+ /** The rule urgency/trigger that produced this delivery. */
16619
+ delivery: NcDeliverySchema,
16620
+ targetId: string(),
16621
+ deviceId: number(),
16622
+ recordKind: NcHistoryRecordKindSchema,
16623
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16624
+ recordId: string(),
16625
+ /** Present for track-scoped deliveries (object-event / track-end). */
16626
+ trackId: string().optional(),
16627
+ status: NcHistoryStatusSchema,
16628
+ /** Delivery attempts made so far. */
16629
+ attempts: number().int(),
16630
+ /** Fire time (outbox enqueue). */
16631
+ createdAt: number(),
16632
+ /** Last transition time (terminal for sent / dead). */
16633
+ updatedAt: number(),
16634
+ /** Failure detail — present on a `dead` row. */
16635
+ error: string().optional(),
16636
+ subject: NcHistorySubjectSchema
16130
16637
  });
16131
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16132
- var ProfileRefInputSchema = object({
16133
- addonId: string(),
16134
- profileId: string()
16638
+ /**
16639
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16640
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16641
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16642
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16643
+ */
16644
+ var NcHistoryFilterSchema = object({
16645
+ ruleId: string().optional(),
16646
+ deviceId: number().optional(),
16647
+ status: NcHistoryStatusSchema.optional(),
16648
+ since: number().optional(),
16649
+ until: number().optional(),
16650
+ limit: number().int().min(1).max(500).default(100)
16135
16651
  });
16136
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16137
- kind: "mutation",
16138
- auth: "admin"
16139
- }), method(ProfileRefInputSchema, _void(), {
16652
+ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
16140
16653
  kind: "mutation",
16141
- auth: "admin"
16142
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16654
+ auth: "admin",
16655
+ caller: "required"
16656
+ }), method(object({
16657
+ ruleId: string(),
16658
+ patch: NcRulePatchSchema
16659
+ }), object({ rule: NcRuleSchema }), {
16143
16660
  kind: "mutation",
16144
- auth: "admin"
16145
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16146
- selector: LlmDefaultSelectorSchema,
16147
- profileId: string().nullable()
16148
- }), _void(), {
16661
+ auth: "admin",
16662
+ caller: "required"
16663
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16149
16664
  kind: "mutation",
16150
16665
  auth: "admin"
16151
16666
  }), method(object({
16152
- since: number().optional(),
16153
- until: number().optional(),
16154
- consumer: string().optional(),
16155
- profileId: string().optional()
16156
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16157
- nodeId: string(),
16158
- model: ManagedModelRefSchema
16159
- }), _void(), {
16667
+ ruleId: string(),
16668
+ enabled: boolean()
16669
+ }), object({ success: literal(true) }), {
16160
16670
  kind: "mutation",
16161
16671
  auth: "admin"
16162
16672
  }), method(object({
16163
- nodeId: string(),
16164
- file: string()
16165
- }), _void(), {
16166
- kind: "mutation",
16167
- auth: "admin"
16168
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16169
- kind: "mutation",
16170
- auth: "admin"
16171
- }), method(ProfileRefInputSchema, _void(), {
16673
+ rule: NcRuleInputSchema,
16674
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16675
+ }), object({ results: array(NcTestResultSchema) }), {
16172
16676
  kind: "mutation",
16173
16677
  auth: "admin"
16174
- });
16678
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16175
16679
  /**
16176
16680
  * Zod schemas for persisted record types.
16177
16681
  *
@@ -16857,7 +17361,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16857
17361
  }), method(object({
16858
17362
  eventId: string(),
16859
17363
  kind: MediaFileKindEnum.optional()
16860
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17364
+ }), array(MediaFileSchema).readonly()), method(object({
17365
+ trackId: string(),
17366
+ kinds: array(MediaFileKindEnum).optional()
17367
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16861
17368
  deviceId: number(),
16862
17369
  timestamp: number(),
16863
17370
  frameWidth: number(),
@@ -16878,76 +17385,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16878
17385
  eventId: string(),
16879
17386
  timestamp: number()
16880
17387
  });
16881
- /**
16882
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16883
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16884
- * caps into per-camera event-kind descriptors.
16885
- *
16886
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16887
- * is NOT duplicated here — every entry is derived from the single
16888
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16889
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16890
- * control cap means adding one line here (and a taxonomy entry); the anti-
16891
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16892
- * eventful cap is missing.
16893
- */
16894
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16895
- var LEGACY_ICON = {
16896
- motion: "motion",
16897
- audio: "audio",
16898
- person: "person",
16899
- vehicle: "vehicle",
16900
- animal: "animal",
16901
- package: "package",
16902
- door: "door",
16903
- pir: "pir",
16904
- smoke: "smoke",
16905
- water: "water",
16906
- button: "button",
16907
- generic: "generic",
16908
- gas: "smoke",
16909
- vibration: "generic",
16910
- tamper: "generic",
16911
- presence: "person",
16912
- lock: "generic",
16913
- siren: "generic",
16914
- switch: "generic",
16915
- doorbell: "button"
16916
- };
16917
- function legacyIcon(iconId) {
16918
- return LEGACY_ICON[iconId] ?? "generic";
16919
- }
16920
- /**
16921
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16922
- * The anti-drift guard cross-checks this against the eventful caps declared
16923
- * in `packages/types/src/capabilities/*.cap.ts`.
16924
- */
16925
- var CAP_TO_KIND = {
16926
- contact: "contact",
16927
- motion: "motion-sensor",
16928
- smoke: "smoke",
16929
- flood: "flood",
16930
- gas: "gas",
16931
- "carbon-monoxide": "carbon-monoxide",
16932
- vibration: "vibration",
16933
- tamper: "tamper",
16934
- presence: "presence",
16935
- "enum-sensor": "enum-sensor",
16936
- "event-emitter": "device-event",
16937
- "lock-control": "lock",
16938
- switch: "switch",
16939
- button: "button",
16940
- doorbell: "doorbell"
16941
- };
16942
- function buildDescriptor(capName, kind) {
16943
- const t = EVENT_TAXONOMY[kind];
16944
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16945
- return {
16946
- ...t,
16947
- icon: legacyIcon(t.iconId)
16948
- };
16949
- }
16950
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16951
17388
  var CameraPipelineConfigSchema = object({
16952
17389
  engine: PipelineEngineChoiceSchema.optional(),
16953
17390
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17433,6 +17870,76 @@ method(object({
17433
17870
  auth: "admin"
17434
17871
  });
17435
17872
  /**
17873
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17874
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17875
+ * caps into per-camera event-kind descriptors.
17876
+ *
17877
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17878
+ * is NOT duplicated here — every entry is derived from the single
17879
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17880
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17881
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17882
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17883
+ * eventful cap is missing.
17884
+ */
17885
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17886
+ var LEGACY_ICON = {
17887
+ motion: "motion",
17888
+ audio: "audio",
17889
+ person: "person",
17890
+ vehicle: "vehicle",
17891
+ animal: "animal",
17892
+ package: "package",
17893
+ door: "door",
17894
+ pir: "pir",
17895
+ smoke: "smoke",
17896
+ water: "water",
17897
+ button: "button",
17898
+ generic: "generic",
17899
+ gas: "smoke",
17900
+ vibration: "generic",
17901
+ tamper: "generic",
17902
+ presence: "person",
17903
+ lock: "generic",
17904
+ siren: "generic",
17905
+ switch: "generic",
17906
+ doorbell: "button"
17907
+ };
17908
+ function legacyIcon(iconId) {
17909
+ return LEGACY_ICON[iconId] ?? "generic";
17910
+ }
17911
+ /**
17912
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17913
+ * The anti-drift guard cross-checks this against the eventful caps declared
17914
+ * in `packages/types/src/capabilities/*.cap.ts`.
17915
+ */
17916
+ var CAP_TO_KIND = {
17917
+ contact: "contact",
17918
+ motion: "motion-sensor",
17919
+ smoke: "smoke",
17920
+ flood: "flood",
17921
+ gas: "gas",
17922
+ "carbon-monoxide": "carbon-monoxide",
17923
+ vibration: "vibration",
17924
+ tamper: "tamper",
17925
+ presence: "presence",
17926
+ "enum-sensor": "enum-sensor",
17927
+ "event-emitter": "device-event",
17928
+ "lock-control": "lock",
17929
+ switch: "switch",
17930
+ button: "button",
17931
+ doorbell: "doorbell"
17932
+ };
17933
+ function buildDescriptor(capName, kind) {
17934
+ const t = EVENT_TAXONOMY[kind];
17935
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17936
+ return {
17937
+ ...t,
17938
+ icon: legacyIcon(t.iconId)
17939
+ };
17940
+ }
17941
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17942
+ /**
17436
17943
  * server-management — per-NODE singleton capability for a node's ROOT
17437
17944
  * package lifecycle (runtime-updatable node packages).
17438
17945
  *
@@ -18887,7 +19394,28 @@ var FaceInfoSchema = object({
18887
19394
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18888
19395
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18889
19396
  * back to the inline `base64` face crop. */
18890
- keyFrameMediaKey: string().optional()
19397
+ keyFrameMediaKey: string().optional(),
19398
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19399
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19400
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19401
+ * faces that were never auto-recognized. */
19402
+ bestMatchScore: number().optional(),
19403
+ /** Native-scale face short side (px) at recognition time, when the runner
19404
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19405
+ * legacy rows / runners that reported no native measure. */
19406
+ nativeFaceShortSidePx: number().optional(),
19407
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19408
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19409
+ * but blocked only by the recognition size floor). Mutually exclusive with
19410
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19411
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19412
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19413
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19414
+ suggestedIdentityId: string().optional(),
19415
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19416
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19417
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19418
+ suggestedMatchScore: number().optional()
18891
19419
  });
18892
19420
  var FaceFilterEnum = _enum([
18893
19421
  "unassigned",
@@ -20930,36 +21458,6 @@ Object.freeze({
20930
21458
  addonId: null,
20931
21459
  access: "view"
20932
21460
  },
20933
- "advancedNotifier.deleteRule": {
20934
- capName: "advanced-notifier",
20935
- capScope: "system",
20936
- addonId: null,
20937
- access: "delete"
20938
- },
20939
- "advancedNotifier.getHistory": {
20940
- capName: "advanced-notifier",
20941
- capScope: "system",
20942
- addonId: null,
20943
- access: "view"
20944
- },
20945
- "advancedNotifier.getRules": {
20946
- capName: "advanced-notifier",
20947
- capScope: "system",
20948
- addonId: null,
20949
- access: "view"
20950
- },
20951
- "advancedNotifier.testRule": {
20952
- capName: "advanced-notifier",
20953
- capScope: "system",
20954
- addonId: null,
20955
- access: "create"
20956
- },
20957
- "advancedNotifier.upsertRule": {
20958
- capName: "advanced-notifier",
20959
- capScope: "system",
20960
- addonId: null,
20961
- access: "create"
20962
- },
20963
21461
  "alarmPanel.arm": {
20964
21462
  capName: "alarm-panel",
20965
21463
  capScope: "device",
@@ -23264,6 +23762,60 @@ Object.freeze({
23264
23762
  addonId: null,
23265
23763
  access: "create"
23266
23764
  },
23765
+ "notificationRules.createRule": {
23766
+ capName: "notification-rules",
23767
+ capScope: "system",
23768
+ addonId: null,
23769
+ access: "create"
23770
+ },
23771
+ "notificationRules.deleteRule": {
23772
+ capName: "notification-rules",
23773
+ capScope: "system",
23774
+ addonId: null,
23775
+ access: "delete"
23776
+ },
23777
+ "notificationRules.getConditionCatalog": {
23778
+ capName: "notification-rules",
23779
+ capScope: "system",
23780
+ addonId: null,
23781
+ access: "view"
23782
+ },
23783
+ "notificationRules.getHistory": {
23784
+ capName: "notification-rules",
23785
+ capScope: "system",
23786
+ addonId: null,
23787
+ access: "view"
23788
+ },
23789
+ "notificationRules.getRule": {
23790
+ capName: "notification-rules",
23791
+ capScope: "system",
23792
+ addonId: null,
23793
+ access: "view"
23794
+ },
23795
+ "notificationRules.listRules": {
23796
+ capName: "notification-rules",
23797
+ capScope: "system",
23798
+ addonId: null,
23799
+ access: "view"
23800
+ },
23801
+ "notificationRules.setRuleEnabled": {
23802
+ capName: "notification-rules",
23803
+ capScope: "system",
23804
+ addonId: null,
23805
+ access: "create"
23806
+ },
23807
+ "notificationRules.testRule": {
23808
+ capName: "notification-rules",
23809
+ capScope: "system",
23810
+ addonId: null,
23811
+ access: "create"
23812
+ },
23813
+ "notificationRules.updateRule": {
23814
+ capName: "notification-rules",
23815
+ capScope: "system",
23816
+ addonId: null,
23817
+ access: "create"
23818
+ },
23267
23819
  "notifier.cancel": {
23268
23820
  capName: "notifier",
23269
23821
  capScope: "device",