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