@camstack/addon-ai 0.4.3 → 0.4.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.
package/dist/addon.js CHANGED
@@ -8,9 +8,9 @@ let node_path$1 = require_chunk.__toESM(node_path, 1);
8
8
  node_path = require_chunk.__toESM(node_path);
9
9
  let node_crypto = require("node:crypto");
10
10
  let node_net = require("node:net");
11
- let node_util = require("node:util");
12
11
  let node_fs = require("node:fs");
13
12
  node_fs = require_chunk.__toESM(node_fs, 1);
13
+ let node_util = require("node:util");
14
14
  let node_zlib = require("node:zlib");
15
15
  let node_fs_promises = require("node:fs/promises");
16
16
  node_fs_promises = require_chunk.__toESM(node_fs_promises);
@@ -11021,6 +11021,8 @@ var QueryFilterSchema = object({
11021
11021
  where: record(string(), unknown()).optional(),
11022
11022
  whereIn: record(string(), array(unknown())).optional(),
11023
11023
  whereBetween: record(string(), tuple([unknown(), unknown()])).optional(),
11024
+ /** NULL-safe exclusion: matches rows whose field is NULL OR != the value. */
11025
+ whereNot: record(string(), unknown()).optional(),
11024
11026
  orderBy: object({
11025
11027
  field: string(),
11026
11028
  direction: _enum(["asc", "desc"])
@@ -11040,7 +11042,8 @@ var QueryFilterSchema = object({
11040
11042
  var MutationFilterSchema = object({
11041
11043
  where: record(string(), unknown()).optional(),
11042
11044
  whereIn: record(string(), array(unknown())).optional(),
11043
- whereBetween: record(string(), tuple([unknown(), unknown()])).optional()
11045
+ whereBetween: record(string(), tuple([unknown(), unknown()])).optional(),
11046
+ whereNot: record(string(), unknown()).optional()
11044
11047
  });
11045
11048
  /** A single stored record: `{ id, data }`. */
11046
11049
  var SettingsRecordSchema = object({
@@ -12474,6 +12477,18 @@ var LlmGenerateBaseInputSchema = object({
12474
12477
  * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
12475
12478
  * watchdog — operator decision #3).
12476
12479
  */
12480
+ /**
12481
+ * A companion artifact that MUST land beside the main GGUF: the `mmproj`
12482
+ * projector of a vision model, or shards 2..N of a split GGUF. Carried on the
12483
+ * REF rather than looked up at install time, so what the operator approved in
12484
+ * the preview is exactly what the node downloads.
12485
+ */
12486
+ var ManagedModelExtraFileSchema = object({
12487
+ url: string(),
12488
+ filename: string(),
12489
+ sizeBytes: number$1(),
12490
+ sha256: string().optional()
12491
+ });
12477
12492
  var ManagedModelRefSchema = discriminatedUnion("kind", [
12478
12493
  object({
12479
12494
  kind: literal("catalog"),
@@ -12482,7 +12497,11 @@ var ManagedModelRefSchema = discriminatedUnion("kind", [
12482
12497
  object({
12483
12498
  kind: literal("url"),
12484
12499
  url: string(),
12485
- sha256: string().optional()
12500
+ sha256: string().optional(),
12501
+ /** Picker/status label; the file basename when absent. */
12502
+ label: string().optional(),
12503
+ sizeBytes: number$1().optional(),
12504
+ extraFiles: array(ManagedModelExtraFileSchema).optional()
12486
12505
  }),
12487
12506
  object({
12488
12507
  kind: literal("path"),
@@ -12543,11 +12562,39 @@ var ManagedRuntimeConfigSchema = object({
12543
12562
  "q4_1",
12544
12563
  "q4_0"
12545
12564
  ]).optional(),
12565
+ /**
12566
+ * Escape hatch for llama-server flags this schema does NOT model — `--jinja`
12567
+ * (which most vision chat templates need and some language-only models
12568
+ * dislike), `--cont-batching`, `--rope-scaling`, …
12569
+ *
12570
+ * It is NOT a second place to set the flags above. A token that collides
12571
+ * with a typed field is REJECTED at start, naming the field that owns it
12572
+ * (`assertNoOwnedFlags`), because two knobs writing the same argv is exactly
12573
+ * the "two switches that disagree" failure this repo has already shipped
12574
+ * twice (D62).
12575
+ */
12576
+ extraArgs: array(string()).default([]),
12546
12577
  /** Else lazy: first generate boots it. */
12547
12578
  autoStart: boolean().default(false),
12548
12579
  /** 0 = never; frees RAM after quiet periods. */
12549
12580
  idleStopMinutes: number$1().int().default(30)
12550
12581
  });
12582
+ /**
12583
+ * Where a multi-GB install currently is. A single 0..1 fraction cannot answer
12584
+ * "is it stuck?" for an install that is three files (shards + mmproj) followed
12585
+ * by a sha256 pass over 22 GB — during which the fraction sat at 1.0 and the
12586
+ * node looked hung. Phase + file + bytes is the smallest shape that does.
12587
+ */
12588
+ var LlmDownloadProgressSchema = object({
12589
+ phase: _enum(["downloading", "verifying"]),
12590
+ /** The artifact currently moving, e.g. `mmproj-F16.gguf`. */
12591
+ file: string(),
12592
+ fileIndex: number$1().int(),
12593
+ fileCount: number$1().int(),
12594
+ /** Across the WHOLE install, not the current file. */
12595
+ downloadedBytes: number$1(),
12596
+ totalBytes: number$1().optional()
12597
+ });
12551
12598
  var LlmRuntimeStatusSchema = object({
12552
12599
  /** Status is ALWAYS node-qualified. */
12553
12600
  nodeId: string(),
@@ -12564,6 +12611,8 @@ var LlmRuntimeStatusSchema = object({
12564
12611
  modelPath: string().optional(),
12565
12612
  modelId: string().optional(),
12566
12613
  downloadProgress: number$1().min(0).max(1).optional(),
12614
+ /** Detail behind `downloadProgress`; present for the same lifetime. */
12615
+ download: LlmDownloadProgressSchema.optional(),
12567
12616
  lastError: string().optional(),
12568
12617
  crashesInWindow: number$1(),
12569
12618
  /** Child RSS (sampled best-effort). */
@@ -12574,7 +12623,14 @@ var LlmNodeModelSchema = object({
12574
12623
  file: string(),
12575
12624
  sizeBytes: number$1(),
12576
12625
  catalogId: string().optional(),
12577
- installedAt: number$1().optional()
12626
+ installedAt: number$1().optional(),
12627
+ /**
12628
+ * Absolute path on the node. Present so a file that is on disk but matches
12629
+ * no catalog entry — a custom Hugging Face install, or a GGUF the operator
12630
+ * copied in by hand — is still SELECTABLE, as a `{kind:'path'}` ref. Without
12631
+ * it the picker could list such a file and do nothing with it.
12632
+ */
12633
+ path: string().optional()
12578
12634
  });
12579
12635
  var LlmRuntimeDiskUsageSchema = object({
12580
12636
  nodeId: string(),
@@ -12735,6 +12791,36 @@ var ManagedModelCatalogEntrySchema = object({
12735
12791
  /** Vision models: companion projector file. */
12736
12792
  mmprojUrl: string().optional()
12737
12793
  });
12794
+ /**
12795
+ * The outcome of turning one operator-typed Hugging Face reference into a
12796
+ * download plan. A RESULT, never a throw: "this repo has 24 quantizations and
12797
+ * I will not pick for you" is a normal answer the UI has to render, not an
12798
+ * exception.
12799
+ *
12800
+ * `candidates` is the whole reason the refusal is usable — every string in it
12801
+ * is a tag that resolves when pasted back as `<org>/<repo>:<TAG>`.
12802
+ */
12803
+ var HfModelResolutionSchema = discriminatedUnion("ok", [object({
12804
+ ok: literal(true),
12805
+ /** Ready to hand to `installModel` unchanged. */
12806
+ model: ManagedModelRefSchema,
12807
+ label: string(),
12808
+ repo: string(),
12809
+ quantization: string(),
12810
+ purpose: _enum(["text", "vision"]),
12811
+ totalBytes: number$1(),
12812
+ /** mmproj + shards, for the preview: an operator approving 23 GB should
12813
+ * see that 0.9 GB of it is a projector they did not name. */
12814
+ extraFilenames: array(string())
12815
+ }), object({
12816
+ ok: literal(false),
12817
+ code: string(),
12818
+ message: string(),
12819
+ candidates: array(string()).optional(),
12820
+ /** Set when the refusal was only the ceiling: re-calling with
12821
+ * `maxBytes: requiredBytes` is the operator's explicit override. */
12822
+ requiredBytes: number$1().optional()
12823
+ })]);
12738
12824
  var LlmRuntimeNodeSchema = object({
12739
12825
  nodeId: string(),
12740
12826
  reachable: boolean(),
@@ -12802,6 +12888,25 @@ var llmCapability = {
12802
12888
  listModelCatalog: method(object({}), array(ManagedModelCatalogEntrySchema)),
12803
12889
  listRuntimeNodes: method(object({}), array(LlmRuntimeNodeSchema)),
12804
12890
  listNodeModels: method(object({ nodeId: string() }), array(LlmNodeModelSchema)),
12891
+ /**
12892
+ * One typed Hugging Face reference → a pinned, verified `ManagedModelRef`.
12893
+ *
12894
+ * Runs on the HUB, not on the target node: resolution needs egress to
12895
+ * huggingface.co, and an agent that cannot reach it still installs fine
12896
+ * through the model-distributor relay. Nothing is downloaded here — this is
12897
+ * a tree read plus a HEAD, so the operator sees the size, the quantization
12898
+ * and the mmproj BEFORE approving a multi-GB pull.
12899
+ */
12900
+ resolveModelRef: method(object({
12901
+ /** `https://huggingface.co/<org>/<repo>/resolve/main/<f>.gguf`,
12902
+ * `<org>/<repo>/<f>.gguf`, `<org>/<repo>` or `<org>/<repo>:<QUANT>`. */
12903
+ ref: string(),
12904
+ /** Explicit ceiling override, in bytes. Absent = the built-in ceiling. */
12905
+ maxBytes: number$1().positive().optional()
12906
+ }), HfModelResolutionSchema, {
12907
+ kind: "mutation",
12908
+ auth: "admin"
12909
+ }),
12805
12910
  installModel: method(object({
12806
12911
  nodeId: string(),
12807
12912
  model: ManagedModelRefSchema
@@ -16895,7 +17000,10 @@ var RecentTracksQueryInput = object({
16895
17000
  * Encodes the (lastSeen, trackId) sort position — treat as opaque. */
16896
17001
  cursor: string().optional(),
16897
17002
  /** See {@link TrackProjectionSchema}. Default `full`. */
16898
- projection: TrackProjectionSchema.optional()
17003
+ projection: TrackProjectionSchema.optional(),
17004
+ /** Include stationary-promoted rows (parked objects). Default false: the
17005
+ * feed lists passages; parking records live on the stationary registry. */
17006
+ includeStationary: boolean().optional()
16899
17007
  });
16900
17008
  var RecentTracksPageSchema = object({
16901
17009
  /** Merged page, ordered by (`lastSeen` DESC, `trackId` DESC). */
@@ -17113,7 +17221,11 @@ DeviceType.Camera, method(object({ deviceId: number$1() }), array(TrackSchema).r
17113
17221
  zone: TrackZoneFilterSchema.optional(),
17114
17222
  /** See {@link TrackProjectionSchema}. Default `full` (backward
17115
17223
  * compatible — omitting the field keeps today's exact behaviour). */
17116
- projection: TrackProjectionSchema.optional()
17224
+ projection: TrackProjectionSchema.optional(),
17225
+ /** Include stationary-promoted rows (parked objects handed to the
17226
+ * stationary registry). Default false: the timeline lists passages,
17227
+ * not parking records (operator decision, 2026-08-15). */
17228
+ includeStationary: boolean().optional()
17117
17229
  }), array(TrackSchema).readonly()), method(RecentTracksQueryInput, RecentTracksPageSchema), method(object({ deviceId: number$1() }), _void(), {
17118
17230
  kind: "mutation",
17119
17231
  auth: "admin"
@@ -17277,11 +17389,16 @@ DeviceType.Camera, method(object({ deviceId: number$1() }), array(TrackSchema).r
17277
17389
  auth: "admin"
17278
17390
  }), method(object({
17279
17391
  eventId: string(),
17280
- kind: MediaFileKindEnum.optional()
17392
+ kind: MediaFileKindEnum.optional(),
17393
+ deviceId: number$1()
17394
+ }), array(MediaFileSchema).readonly()), method(object({
17395
+ trackId: string(),
17396
+ kinds: array(MediaFileKindEnum).optional(),
17397
+ deviceId: number$1()
17281
17398
  }), array(MediaFileSchema).readonly()), method(object({
17282
17399
  trackId: string(),
17283
- kinds: array(MediaFileKindEnum).optional()
17284
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
17400
+ deviceId: number$1()
17401
+ }), array(MediaFileInfoSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), method(object({}), WipeObjectEmbeddingsResultSchema, {
17285
17402
  kind: "mutation",
17286
17403
  auth: "admin"
17287
17404
  }), method(RebuildObjectEmbeddingsInput, RebuildObjectEmbeddingsResultSchema, {
@@ -17941,6 +18058,17 @@ var maxSessionHoldMsField = {
17941
18058
  default: 12e4,
17942
18059
  step: 5e3
17943
18060
  };
18061
+ /**
18062
+ * Quiet period that closes an `audioMode: 'on-motion'` audio window. Floor of
18063
+ * 5s so a rearm can never degenerate into per-event stream churn; default 90s
18064
+ * comfortably outlives the gap between two PIR wakes on a battery camera.
18065
+ */
18066
+ var audioMotionWindowMsField = {
18067
+ min: 5e3,
18068
+ max: 6e5,
18069
+ default: 9e4,
18070
+ step: 5e3
18071
+ };
17944
18072
  var motionFpsField = {
17945
18073
  min: 1,
17946
18074
  max: 30,
@@ -18117,6 +18245,27 @@ var RunnerCameraConfigSchema = object({
18117
18245
  * resolved `CameraDetectionConfig`.
18118
18246
  */
18119
18247
  maxSessionHoldMs: number$1().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
18248
+ /**
18249
+ * Orchestrator-side quiet period (ms) that closes an `audioMode:
18250
+ * 'on-motion'` audio window, measured from the LAST motion event.
18251
+ *
18252
+ * This exists because the falling edge cannot be relied on. Camera-native
18253
+ * providers emit motion as a RISING EDGE ONLY (Reolink's Baichuan push and
18254
+ * its email-push SMTP path both emit `detected: true` and never the
18255
+ * counterpart); only the frame-diff analyzer emits falls. So on an
18256
+ * onboard-only camera a window that closed only on `detected: false` never
18257
+ * closed at all, and `on-motion` silently behaved as `always-on` — on a
18258
+ * battery camera, the one failure mode the mode exists to prevent.
18259
+ *
18260
+ * Every motion event rearms this timer WITHOUT restarting the stream, so a
18261
+ * burst of re-fires costs nothing. A falling edge, when one does arrive,
18262
+ * still closes earlier via `motionCooldownMs` — whichever comes first wins.
18263
+ *
18264
+ * Not consumed by the runner: carried here so it shares the per-camera
18265
+ * device-settings surface with `motionCooldownMs`, exactly like
18266
+ * `maxSessionHoldMs`.
18267
+ */
18268
+ audioMotionWindowMs: number$1().min(audioMotionWindowMsField.min).max(audioMotionWindowMsField.max).optional(),
18120
18269
  motionFps: number$1().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
18121
18270
  detectionFps: number$1().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
18122
18271
  motionStreamId: string(),
@@ -18212,7 +18361,7 @@ var RunnerCameraConfigSchema = object({
18212
18361
  */
18213
18362
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
18214
18363
  });
18215
- 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;
18364
+ 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, audioMotionWindowMsField.min, audioMotionWindowMsField.max, audioMotionWindowMsField.step, audioMotionWindowMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
18216
18365
  /**
18217
18366
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
18218
18367
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -19228,7 +19377,16 @@ targets: array(object({
19228
19377
  /** A sleeping battery camera: the frame is deliberately stale and will
19229
19378
  * NOT refresh in the background. A surface should say so rather than
19230
19379
  * present it as current. */
19231
- sleeping: boolean()
19380
+ sleeping: boolean(),
19381
+ /** Current device state rendered over the cached frame. State images
19382
+ * remain authoritative even when their photographic background is
19383
+ * old; null means the link must carry a current camera frame. */
19384
+ stateReason: _enum([
19385
+ "disabled",
19386
+ "sleeping",
19387
+ "unreachable",
19388
+ "waking"
19389
+ ]).nullable()
19232
19390
  })));
19233
19391
  /**
19234
19392
  * `sso-bridge` — internal hub-only cap that lets SSO-style auth
@@ -20750,6 +20908,25 @@ var BatteryStatusSchema = object({
20750
20908
  /** Ms epoch of the last observation. Lets consumers reason about freshness. */
20751
20909
  lastUpdated: number$1(),
20752
20910
  /**
20911
+ * Ms epoch of the last time the device PROVED it was reachable — a
20912
+ * completed firmware round-trip, an observed wake, or an inbound push
20913
+ * (firmware event, email). `0`/absent = never since this slice was born.
20914
+ *
20915
+ * This is the ONLY input that separates "asleep" from "gone", and it is
20916
+ * fed exclusively by PASSIVE signals: nothing may write it by reaching
20917
+ * for the radio, because a poll that confirms reachability is the same
20918
+ * poll that drains the battery. See {@link deriveBatteryPresence} — the
20919
+ * single derivation every consumer must use; no surface computes its own.
20920
+ *
20921
+ * It is deliberately NOT a clock in the
20922
+ * `scripts/check-runtime-state-durability.ts` sense: it is the
20923
+ * observation itself, and it is the only thing a 30-hour silence is
20924
+ * visible in. Writers quantise it (see `CONTACT_WRITE_QUANTUM_MS` in the
20925
+ * Reolink provider) so a value that means "recently" cannot cost a
20926
+ * SQLite commit per round-trip.
20927
+ */
20928
+ lastContactAt: number$1().optional(),
20929
+ /**
20753
20930
  * True when the source is a BINARY low-battery indicator (HA
20754
20931
  * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
20755
20932
  * charge level — `percentage` is then a coarse stand-in (100 = normal,
@@ -25027,6 +25204,16 @@ var CamStreamDescriptorSchema = object({
25027
25204
  /** Transport-specific opaque metadata (e.g. rfc4571 SDP). */
25028
25205
  metadata: record(string(), unknown()).optional()
25029
25206
  });
25207
+ object({
25208
+ /** The descriptors as last built from a real camera response. Never a guess:
25209
+ * a failed or refused build writes NOTHING, so a restored catalog is always
25210
+ * one the camera itself once produced. */
25211
+ descriptors: array(CamStreamDescriptorSchema),
25212
+ /** Ms epoch of the build that produced {@link descriptors}. Lets the wake
25213
+ * path decide whether the camera's own awake window is worth spending on a
25214
+ * re-read. */
25215
+ lastFetchedAt: number$1()
25216
+ });
25030
25217
  DeviceType.Camera, method(object({ deviceId: number$1().int().nonnegative() }), array(CamStreamDescriptorSchema).readonly());
25031
25218
  /** One of the camera's stream profiles. */
25032
25219
  var StreamProfileSchema = _enum([
@@ -28059,6 +28246,12 @@ Object.freeze({
28059
28246
  addonId: null,
28060
28247
  access: "view"
28061
28248
  },
28249
+ "llm.resolveModelRef": {
28250
+ capName: "llm",
28251
+ capScope: "system",
28252
+ addonId: null,
28253
+ access: "create"
28254
+ },
28062
28255
  "llm.setDefault": {
28063
28256
  capName: "llm",
28064
28257
  capScope: "system",
@@ -32451,6 +32644,11 @@ Object.freeze({
32451
32644
  form: "single",
32452
32645
  optional: false
32453
32646
  }],
32647
+ "pipelineAnalytics.getEventMedia": [{
32648
+ name: "deviceId",
32649
+ form: "single",
32650
+ optional: false
32651
+ }],
32454
32652
  "pipelineAnalytics.getKeyEvents": [{
32455
32653
  name: "deviceId",
32456
32654
  form: "single",
@@ -32481,6 +32679,11 @@ Object.freeze({
32481
32679
  form: "single",
32482
32680
  optional: false
32483
32681
  }],
32682
+ "pipelineAnalytics.getTrackMedia": [{
32683
+ name: "deviceId",
32684
+ form: "single",
32685
+ optional: false
32686
+ }],
32484
32687
  "pipelineAnalytics.getTrainingExportSummary": [{
32485
32688
  name: "deviceIds",
32486
32689
  form: "array",
@@ -32516,6 +32719,11 @@ Object.freeze({
32516
32719
  form: "array",
32517
32720
  optional: true
32518
32721
  }],
32722
+ "pipelineAnalytics.listTrackMedia": [{
32723
+ name: "deviceId",
32724
+ form: "single",
32725
+ optional: false
32726
+ }],
32519
32727
  "pipelineAnalytics.listTracks": [{
32520
32728
  name: "deviceId",
32521
32729
  form: "single",
@@ -32956,6 +33164,12 @@ Object.freeze({
32956
33164
  form: "single",
32957
33165
  optional: false
32958
33166
  }],
33167
+ "snapshot.getSnapshotLinks": [{
33168
+ name: "targets",
33169
+ form: "object-array",
33170
+ optional: false,
33171
+ itemField: "deviceId"
33172
+ }],
32959
33173
  "snapshot.getSnapshotOverview": [{
32960
33174
  name: "deviceIds",
32961
33175
  form: "array",
@@ -45767,7 +45981,7 @@ function inferDocMediaType(uriOrName) {
45767
45981
  for (const [ext, media] of Object.entries(KNOWN_DOC_EXTENSIONS)) if (lower.endsWith(`.${ext}`)) return media;
45768
45982
  return "application/octet-stream";
45769
45983
  }
45770
- function basename$1(uriOrName) {
45984
+ function basename$2(uriOrName) {
45771
45985
  const parts = uriOrName.split("/");
45772
45986
  const last = parts[parts.length - 1];
45773
45987
  return last && last.length > 0 ? last : void 0;
@@ -45797,7 +46011,7 @@ function annotationToSource({ annotation, generateId: generateId3 }) {
45797
46011
  url: uri,
45798
46012
  ...fileCitation.file_name != null ? { title: fileCitation.file_name } : {}
45799
46013
  };
45800
- const filename = (_c = fileCitation.file_name) != null ? _c : basename$1(uri);
46014
+ const filename = (_c = fileCitation.file_name) != null ? _c : basename$2(uri);
45801
46015
  const mediaType = inferDocMediaType(uri);
45802
46016
  return {
45803
46017
  type: "source",
@@ -45886,7 +46100,7 @@ function builtinToolResultToSources({ block, generateId: generateId3 }) {
45886
46100
  });
45887
46101
  continue;
45888
46102
  }
45889
- const filename = (_h = entry.file_name) != null ? _h : basename$1(uri);
46103
+ const filename = (_h = entry.file_name) != null ? _h : basename$2(uri);
45890
46104
  const mediaType = inferDocMediaType(uri);
45891
46105
  sources.push({
45892
46106
  type: "source",
@@ -70093,6 +70307,469 @@ function resolveProfile(profiles, defaults, input) {
70093
70307
  };
70094
70308
  }
70095
70309
  //#endregion
70310
+ //#region src/runtime/hf-ref.ts
70311
+ /**
70312
+ * Hugging Face model references — parse, then resolve against the HF API.
70313
+ *
70314
+ * The operator types ONE string and gets a fully-pinned download plan. That is
70315
+ * the whole surface: this is not an HF browser, and it deliberately cannot
70316
+ * discover a model for you — it can only turn a reference you already have
70317
+ * into something the node can fetch and verify.
70318
+ *
70319
+ * ## Why resolution can REFUSE
70320
+ *
70321
+ * A GGUF repo is not one model. `unsloth/Qwen3.6-35B-A3B-GGUF` ships 25
70322
+ * quantizations between 10 GB and 50 GB, and none of them is named `Q4_K_M`
70323
+ * (they are `UD-Q4_K_M`, Unsloth's dynamic quant). Any code that "defaults to
70324
+ * Q4_K_M" would either fail or, worse, pick a neighbouring file and hand the
70325
+ * operator a model they did not ask for after a 20 GB download. So: a repo
70326
+ * with more than one candidate is an ERROR that NAMES the candidates, never a
70327
+ * guess. The only silent pick is the mmproj precision (F16 over F32) — that
70328
+ * choice costs a few hundred MB of projector, not a different model, and the
70329
+ * file it picked is reported back.
70330
+ *
70331
+ * ## The error taxonomy is read from headers, not from the status
70332
+ *
70333
+ * Probed live on 2026-08-15: huggingface.co answers **401** both for a gated
70334
+ * repo and for a repo that does not exist (it refuses to leak whether a
70335
+ * private repo is there). The two are distinguishable only by
70336
+ * `x-error-code: GatedRepo`. Reading the status alone would tell a
70337
+ * typo'd repo name that it needs a token, which is the wrong instruction.
70338
+ *
70339
+ * ## What is verified before a byte is downloaded
70340
+ *
70341
+ * host is huggingface.co · extension is `.gguf` · every file exists in the
70342
+ * tree · the split-GGUF shard set is COMPLETE · the total (main + shards +
70343
+ * mmproj) is under the ceiling · a HEAD confirms the file is reachable with
70344
+ * the credentials at hand and that its size agrees with the tree. The sha256
70345
+ * comes free: HF's LFS `oid` IS the sha256 of the file, and `x-linked-etag`
70346
+ * repeats it on the HEAD.
70347
+ */
70348
+ /** The only hosts a reference may point at. */
70349
+ var HF_HOSTS = ["huggingface.co", "www.huggingface.co"];
70350
+ var HF_API = "https://huggingface.co/api/models";
70351
+ var HF_RESOLVE = "https://huggingface.co";
70352
+ /** Where an operator puts a Hugging Face token, named in the gated error. */
70353
+ var HF_TOKEN_ENV = "HF_TOKEN";
70354
+ var SEGMENT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
70355
+ function fail(code, message, candidates) {
70356
+ return {
70357
+ code,
70358
+ message,
70359
+ ...candidates !== void 0 ? { candidates } : {}
70360
+ };
70361
+ }
70362
+ function badParse(code, message, candidates) {
70363
+ return {
70364
+ ok: false,
70365
+ error: fail(code, message, candidates)
70366
+ };
70367
+ }
70368
+ var EXPECTED = "expected https://huggingface.co/<org>/<repo>/resolve/main/<file>.gguf, or <org>/<repo>/<file>.gguf, or <org>/<repo>[:<QUANT>]";
70369
+ /**
70370
+ * Reference string → a repo/file reference. Pure: no network, no environment.
70371
+ * Every rejection names the form that WAS expected, because the operator is
70372
+ * pasting from a browser and a bare "invalid" tells them nothing.
70373
+ */
70374
+ function parseHfRef(input) {
70375
+ const raw = input.trim();
70376
+ if (raw === "") return badParse("malformed", `empty model reference — ${EXPECTED}`);
70377
+ return raw.includes("://") ? parseUrlForm(raw) : parseBareForm(raw);
70378
+ }
70379
+ function parseUrlForm(raw) {
70380
+ let url;
70381
+ try {
70382
+ url = new URL(raw);
70383
+ } catch {
70384
+ return badParse("malformed", `not a URL: ${raw} — ${EXPECTED}`);
70385
+ }
70386
+ if (!HF_HOSTS.includes(url.hostname)) return badParse("not-huggingface", `only huggingface.co models can be installed this way; got host "${url.hostname}"`);
70387
+ const parts = url.pathname.split("/").filter((p) => p !== "");
70388
+ const marker = parts.findIndex((p) => p === "resolve" || p === "blob");
70389
+ if (marker !== 2 || parts.length < marker + 3) return badParse("malformed", `unrecognised Hugging Face URL: ${raw} — ${EXPECTED}`);
70390
+ return finishParse(`${String(parts[0])}/${String(parts[1])}`, String(parts[marker + 1]), parts.slice(marker + 2).join("/"), raw);
70391
+ }
70392
+ function parseBareForm(raw) {
70393
+ const [beforeTag, ...tagRest] = raw.split(":");
70394
+ const body = String(beforeTag);
70395
+ if (tagRest.length > 1) return badParse("malformed", `too many ":" in ${raw} — ${EXPECTED}`);
70396
+ const quant = tagRest[0]?.trim();
70397
+ const parts = body.split("/");
70398
+ if (parts.length < 2) return badParse("malformed", `not an <org>/<repo> reference: ${raw} — ${EXPECTED}`);
70399
+ if (parts.some((p) => p === "" || p === "." || p === "..")) return badParse("malformed", `illegal path segment in ${raw} — ${EXPECTED}`);
70400
+ const org = String(parts[0]);
70401
+ const name = String(parts[1]);
70402
+ if (!SEGMENT_RE.test(org) || !SEGMENT_RE.test(name)) return badParse("malformed", `illegal repo name in ${raw} — ${EXPECTED}`);
70403
+ const repo = `${org}/${name}`;
70404
+ if (parts.length === 2) {
70405
+ if (quant !== void 0 && quant === "") return badParse("malformed", `empty quantization tag in ${raw} — ${EXPECTED}`);
70406
+ return {
70407
+ ok: true,
70408
+ ref: {
70409
+ kind: "repo",
70410
+ repo,
70411
+ revision: "main",
70412
+ ...quant !== void 0 ? { quant } : {}
70413
+ }
70414
+ };
70415
+ }
70416
+ if (quant !== void 0) return badParse("malformed", `a quantization tag cannot follow an explicit file: ${raw}`);
70417
+ return finishParse(repo, "main", parts.slice(2).join("/"), raw);
70418
+ }
70419
+ function finishParse(repo, revision, filePath, raw) {
70420
+ if (filePath.split("/").some((p) => p === "" || p === "." || p === "..")) return badParse("malformed", `illegal path segment in ${raw} — ${EXPECTED}`);
70421
+ if (!filePath.toLowerCase().endsWith(".gguf")) return badParse("not-gguf", `the managed local runtime loads GGUF only; "${filePath}" is not a .gguf file`);
70422
+ return {
70423
+ ok: true,
70424
+ ref: {
70425
+ kind: "file",
70426
+ repo,
70427
+ revision,
70428
+ filePath
70429
+ }
70430
+ };
70431
+ }
70432
+ /** `-00001-of-00002` — llama.cpp's split-GGUF naming. */
70433
+ var SHARD_RE = /^(.*)-(\d{5})-of-(\d{5})$/;
70434
+ /**
70435
+ * One `-`-delimited segment that is a quantization, e.g. `Q4_K_M`, `IQ2_XXS`,
70436
+ * `BF16`, `fp16`. The `FP` spellings are not cosmetic: `Qwen/*-GGUF` names its
70437
+ * unquantized file `…-fp16.gguf`, and a tag list that cannot name it offers
70438
+ * the operator a suggestion that does not parse.
70439
+ */
70440
+ var QUANT_RE = /^(?:I?Q\d[A-Z0-9_]*|TQ\d_\d|BF16|FP?16|FP?32|FP8|MXFP4(?:_MOE)?)$/i;
70441
+ /** Shard coordinates of a split GGUF filename, or `null` when unsharded. */
70442
+ function shardInfoOf(filename) {
70443
+ const m = SHARD_RE.exec(stripGguf(filename));
70444
+ if (m === null) return null;
70445
+ return {
70446
+ stem: String(m[1]),
70447
+ index: Number(m[2]),
70448
+ total: Number(m[3])
70449
+ };
70450
+ }
70451
+ function stripGguf(filename) {
70452
+ return filename.replace(/\.gguf$/i, "");
70453
+ }
70454
+ /**
70455
+ * The quantization tag of a GGUF filename, uppercased, `UD-` prefix kept —
70456
+ * `''` when the name carries no recognisable tag. Shard coordinates are
70457
+ * stripped first so `X-BF16-00001-of-00002.gguf` reads as `BF16`.
70458
+ */
70459
+ function quantizationOf(filename) {
70460
+ const segments = (shardInfoOf(filename)?.stem ?? stripGguf(filename)).split("-");
70461
+ for (let i = segments.length - 1; i >= 0; i--) {
70462
+ const seg = String(segments[i]);
70463
+ if (!QUANT_RE.test(seg)) continue;
70464
+ return (i > 0 ? String(segments[i - 1]) : "").toUpperCase() === "UD" ? `UD-${seg.toUpperCase()}` : seg.toUpperCase();
70465
+ }
70466
+ return "";
70467
+ }
70468
+ function isMmproj(filePath) {
70469
+ return basename$1(filePath).toLowerCase().startsWith("mmproj");
70470
+ }
70471
+ function basename$1(filePath) {
70472
+ return filePath.slice(filePath.lastIndexOf("/") + 1);
70473
+ }
70474
+ function dirname(filePath) {
70475
+ const i = filePath.lastIndexOf("/");
70476
+ return i < 0 ? "" : filePath.slice(0, i);
70477
+ }
70478
+ function headersFor(token) {
70479
+ return {
70480
+ "User-Agent": "CamStack/1.0",
70481
+ ...token !== void 0 && token !== "" ? { Authorization: `Bearer ${token}` } : {}
70482
+ };
70483
+ }
70484
+ /** HF's 401-for-everything is only decodable through `x-error-code`. */
70485
+ function authError(response, repo) {
70486
+ const code = response.headers.get("x-error-code") ?? "";
70487
+ if (code === "GatedRepo" || code === "GatedRepoAccessDenied") return fail("gated", `${repo} is a gated Hugging Face repo: accept its licence with your HF account, then set a token in the ${HF_TOKEN_ENV} environment variable on the hub and on the runtime node (${HF_TOKEN_ENV} or HUGGING_FACE_HUB_TOKEN), and restart them.`);
70488
+ return fail("repo-not-found", `${repo} does not exist on huggingface.co, or is private (Hugging Face answers 401 for both). Check the org/repo spelling.`);
70489
+ }
70490
+ async function readTree(ref, fetchFn, token) {
70491
+ const url = `${HF_API}/${ref.repo}/tree/${ref.revision}?recursive=1`;
70492
+ let response;
70493
+ try {
70494
+ response = await fetchFn(url, {
70495
+ method: "GET",
70496
+ headers: headersFor(token)
70497
+ });
70498
+ } catch (err) {
70499
+ return {
70500
+ ok: false,
70501
+ error: fail("network", `could not reach huggingface.co: ${message(err)}`)
70502
+ };
70503
+ }
70504
+ if (response.status === 401 || response.status === 403) return {
70505
+ ok: false,
70506
+ error: authError(response, ref.repo)
70507
+ };
70508
+ if (response.status === 404) return {
70509
+ ok: false,
70510
+ error: fail("repo-not-found", `${ref.repo} has no revision "${ref.revision}"`)
70511
+ };
70512
+ if (!response.ok) return {
70513
+ ok: false,
70514
+ error: fail("network", `huggingface.co answered ${String(response.status)} for ${ref.repo}`)
70515
+ };
70516
+ let body;
70517
+ try {
70518
+ body = await response.json();
70519
+ } catch (err) {
70520
+ return {
70521
+ ok: false,
70522
+ error: fail("network", `unreadable tree for ${ref.repo}: ${message(err)}`)
70523
+ };
70524
+ }
70525
+ if (!Array.isArray(body)) return {
70526
+ ok: false,
70527
+ error: fail("network", `unexpected tree payload for ${ref.repo}`)
70528
+ };
70529
+ return {
70530
+ ok: true,
70531
+ files: body.map(toTreeEntry).filter((e) => e !== null)
70532
+ };
70533
+ }
70534
+ function toTreeEntry(raw) {
70535
+ if (typeof raw !== "object" || raw === null) return null;
70536
+ const record = { ...raw };
70537
+ if (record["type"] !== "file") return null;
70538
+ const filePath = record["path"];
70539
+ if (typeof filePath !== "string" || !filePath.toLowerCase().endsWith(".gguf")) return null;
70540
+ const lfs = typeof record["lfs"] === "object" && record["lfs"] !== null ? { ...record["lfs"] } : {};
70541
+ const lfsSize = lfs["size"];
70542
+ const oid = lfs["oid"];
70543
+ const plainSize = record["size"];
70544
+ return {
70545
+ path: filePath,
70546
+ sizeBytes: typeof lfsSize === "number" ? lfsSize : typeof plainSize === "number" ? plainSize : 0,
70547
+ ...typeof oid === "string" && oid.length === 64 ? { sha256: oid } : {}
70548
+ };
70549
+ }
70550
+ function message(err) {
70551
+ return err instanceof Error ? err.message : String(err);
70552
+ }
70553
+ /** Files that can be THE model: not a projector, not a follow-on shard. */
70554
+ function modelCandidates(files) {
70555
+ return files.filter((f) => {
70556
+ if (isMmproj(f.path)) return false;
70557
+ const shard = shardInfoOf(basename$1(f.path));
70558
+ return shard === null || shard.index === 1;
70559
+ });
70560
+ }
70561
+ function labelFor(file) {
70562
+ const quant = quantizationOf(basename$1(file.path));
70563
+ return quant === "" ? basename$1(file.path) : quant;
70564
+ }
70565
+ function selectMain(ref, files) {
70566
+ const candidates = modelCandidates(files);
70567
+ if (ref.kind === "file") {
70568
+ const wanted = ref.filePath.toLowerCase();
70569
+ const hit = files.find((f) => f.path.toLowerCase() === wanted);
70570
+ if (hit === void 0) return {
70571
+ ok: false,
70572
+ error: fail("file-not-found", `${ref.repo} has no file "${ref.filePath}" at revision ${ref.revision}`, candidates.map(labelFor))
70573
+ };
70574
+ return {
70575
+ ok: true,
70576
+ file: hit
70577
+ };
70578
+ }
70579
+ if (candidates.length === 0) return {
70580
+ ok: false,
70581
+ error: fail("not-gguf", `${ref.repo} publishes no GGUF weights (only projectors or no GGUF at all)`)
70582
+ };
70583
+ if (ref.quant !== void 0) {
70584
+ const wanted = ref.quant.toUpperCase();
70585
+ const wantedFile = stripGguf(ref.quant).toUpperCase();
70586
+ const matches = candidates.filter((f) => quantizationOf(basename$1(f.path)) === wanted || stripGguf(basename$1(f.path)).toUpperCase() === wantedFile);
70587
+ if (matches.length === 0) return {
70588
+ ok: false,
70589
+ error: fail("file-not-found", `${ref.repo} has no "${ref.quant}" quantization. Available: ${candidates.map(labelFor).join(", ")}`, dedupe(candidates.map(labelFor)))
70590
+ };
70591
+ const only = matches[0];
70592
+ if (matches.length > 1 || only === void 0) return {
70593
+ ok: false,
70594
+ error: fail("ambiguous", `"${ref.quant}" matches ${String(matches.length)} files in ${ref.repo}: ${matches.map((f) => basename$1(f.path)).join(", ")}. Name the file explicitly.`, matches.map((f) => basename$1(f.path)))
70595
+ };
70596
+ return {
70597
+ ok: true,
70598
+ file: only
70599
+ };
70600
+ }
70601
+ const solo = candidates[0];
70602
+ if (candidates.length > 1 || solo === void 0) {
70603
+ const tags = dedupe(candidates.map(labelFor));
70604
+ return {
70605
+ ok: false,
70606
+ error: fail("ambiguous", `${ref.repo} publishes ${String(candidates.length)} quantizations and picking one for you would be a guess. Re-enter it as ${ref.repo}:<TAG>, or paste the full file URL. Available: ${tags.join(", ")}`, tags)
70607
+ };
70608
+ }
70609
+ return {
70610
+ ok: true,
70611
+ file: solo
70612
+ };
70613
+ }
70614
+ function dedupe(values) {
70615
+ return [...new Set(values)];
70616
+ }
70617
+ /** Shards 2..N of `main`, or an error naming the first one that is missing. */
70618
+ function collectShards(main, files) {
70619
+ const shard = shardInfoOf(basename$1(main.path));
70620
+ if (shard === null || shard.total <= 1) return {
70621
+ ok: true,
70622
+ shards: []
70623
+ };
70624
+ const dir = dirname(main.path);
70625
+ const out = [];
70626
+ for (let i = 2; i <= shard.total; i++) {
70627
+ const wanted = `${shard.stem}-${String(i).padStart(5, "0")}-of-${String(shard.total).padStart(5, "0")}.gguf`;
70628
+ const full = dir === "" ? wanted : `${dir}/${wanted}`;
70629
+ const hit = files.find((f) => f.path === full);
70630
+ if (hit === void 0) return {
70631
+ ok: false,
70632
+ error: fail("incomplete-shards", `split GGUF is incomplete: ${wanted} is missing from the repo (llama.cpp needs all ${String(shard.total)} shards)`)
70633
+ };
70634
+ out.push(hit);
70635
+ }
70636
+ return {
70637
+ ok: true,
70638
+ shards: out
70639
+ };
70640
+ }
70641
+ /** F16 over BF16 over F32 over whatever came first — reported, never hidden. */
70642
+ var MMPROJ_PREFERENCE = [
70643
+ "F16",
70644
+ "BF16",
70645
+ "F32"
70646
+ ];
70647
+ function selectMmproj(files) {
70648
+ const projectors = files.filter((f) => isMmproj(f.path));
70649
+ if (projectors.length === 0) return null;
70650
+ for (const want of MMPROJ_PREFERENCE) {
70651
+ const hit = projectors.find((f) => quantizationOf(basename$1(f.path)) === want);
70652
+ if (hit !== void 0) return hit;
70653
+ }
70654
+ return projectors[0] ?? null;
70655
+ }
70656
+ function resolveUrl(repo, revision, filePath) {
70657
+ return `${HF_RESOLVE}/${repo}/resolve/${revision}/${filePath}`;
70658
+ }
70659
+ async function verifyHead(url, repo, declaredBytes, fetchFn, token) {
70660
+ let response;
70661
+ try {
70662
+ response = await fetchFn(url, {
70663
+ method: "HEAD",
70664
+ redirect: "manual",
70665
+ headers: headersFor(token)
70666
+ });
70667
+ } catch (err) {
70668
+ return {
70669
+ ok: false,
70670
+ error: fail("network", `HEAD ${url} failed: ${message(err)}`)
70671
+ };
70672
+ }
70673
+ if (response.status === 401 || response.status === 403) return {
70674
+ ok: false,
70675
+ error: authError(response, repo)
70676
+ };
70677
+ if (response.status === 404) return {
70678
+ ok: false,
70679
+ error: fail("file-not-found", `${url} is gone (404)`)
70680
+ };
70681
+ if (response.status >= 400) return {
70682
+ ok: false,
70683
+ error: fail("network", `HEAD ${url} answered ${String(response.status)}`)
70684
+ };
70685
+ const linked = response.headers.get("x-linked-size") ?? response.headers.get("content-length");
70686
+ const headBytes = linked === null ? void 0 : Number(linked);
70687
+ if (headBytes !== void 0 && Number.isFinite(headBytes) && headBytes !== declaredBytes) return {
70688
+ ok: false,
70689
+ error: fail("size-mismatch", `huggingface.co reports ${String(headBytes)} bytes for ${url} but its tree declared ${String(declaredBytes)} — refusing to download a file that changed under the reference`)
70690
+ };
70691
+ const etag = response.headers.get("x-linked-etag")?.replace(/"/g, "");
70692
+ return {
70693
+ ok: true,
70694
+ ...etag !== void 0 && etag.length === 64 ? { sha256: etag } : {}
70695
+ };
70696
+ }
70697
+ function toResolved(repo, revision, entry) {
70698
+ return {
70699
+ url: resolveUrl(repo, revision, entry.path),
70700
+ filename: basename$1(entry.path),
70701
+ sizeBytes: entry.sizeBytes,
70702
+ ...entry.sha256 !== void 0 ? { sha256: entry.sha256 } : {}
70703
+ };
70704
+ }
70705
+ function gb$1(bytes) {
70706
+ return `${(bytes / 1e9).toFixed(1)} GB`;
70707
+ }
70708
+ /** Reference → a pinned, size-checked, HEAD-verified download plan. */
70709
+ async function resolveHfRef(ref, deps) {
70710
+ const fetchFn = deps.fetchFn ?? fetch;
70711
+ const maxBytes = deps.maxBytes ?? 21474836480;
70712
+ const tree = await readTree(ref, fetchFn, deps.token);
70713
+ if (!tree.ok) return {
70714
+ ok: false,
70715
+ error: tree.error
70716
+ };
70717
+ const picked = selectMain(ref, tree.files);
70718
+ if (!picked.ok) return {
70719
+ ok: false,
70720
+ error: picked.error
70721
+ };
70722
+ const main = picked.file;
70723
+ const shards = collectShards(main, tree.files);
70724
+ if (!shards.ok) return {
70725
+ ok: false,
70726
+ error: shards.error
70727
+ };
70728
+ const projector = isMmproj(main.path) ? null : selectMmproj(tree.files);
70729
+ const extraEntries = [...shards.shards, ...projector === null ? [] : [projector]];
70730
+ const totalBytes = [main, ...extraEntries].reduce((sum, f) => sum + f.sizeBytes, 0);
70731
+ if (totalBytes > maxBytes) return {
70732
+ ok: false,
70733
+ error: {
70734
+ ...fail("too-large", `this install is ${String(totalBytes)} bytes (${gb$1(totalBytes)}), over the ${String(maxBytes)} byte ceiling (${gb$1(maxBytes)}). Raise the ceiling explicitly if the node really has the disk and RAM for it.`),
70735
+ requiredBytes: totalBytes
70736
+ }
70737
+ };
70738
+ const head = await verifyHead(resolveUrl(ref.repo, ref.revision, main.path), ref.repo, main.sizeBytes, fetchFn, deps.token);
70739
+ if (!head.ok) return {
70740
+ ok: false,
70741
+ error: head.error
70742
+ };
70743
+ const mainResolved = toResolved(ref.repo, ref.revision, {
70744
+ ...main,
70745
+ ...main.sha256 === void 0 && head.sha256 !== void 0 ? { sha256: head.sha256 } : {}
70746
+ });
70747
+ const quantization = quantizationOf(mainResolved.filename);
70748
+ const repoName = ref.repo.slice(ref.repo.indexOf("/") + 1);
70749
+ return {
70750
+ ok: true,
70751
+ resolution: {
70752
+ repo: ref.repo,
70753
+ revision: ref.revision,
70754
+ label: quantization === "" ? repoName : `${repoName} · ${quantization}`,
70755
+ quantization,
70756
+ purpose: projector === null ? "text" : "vision",
70757
+ main: mainResolved,
70758
+ extras: extraEntries.map((e) => toResolved(ref.repo, ref.revision, e)),
70759
+ totalBytes
70760
+ }
70761
+ };
70762
+ }
70763
+ /** `parseHfRef` then {@link resolveHfRef} — the form the cap method calls. */
70764
+ async function resolveHfReference(input, deps) {
70765
+ const parsed = parseHfRef(input);
70766
+ if (!parsed.ok) return {
70767
+ ok: false,
70768
+ error: parsed.error
70769
+ };
70770
+ return resolveHfRef(parsed.ref, deps);
70771
+ }
70772
+ //#endregion
70096
70773
  //#region src/secrets.ts
70097
70774
  /** Same marker as addon-notifiers/src/secrets.ts — UI contract. */
70098
70775
  var REDACTED_MARKER = "__redacted__";
@@ -70316,6 +70993,64 @@ function createLlmProvider(deps) {
70316
70993
  }));
70317
70994
  },
70318
70995
  listNodeModels: async ({ nodeId }) => requireRuntime(deps.runtime).listLocalModels(nodeId),
70996
+ /**
70997
+ * Hugging Face reference → a pinned `ManagedModelRef`, on the HUB.
70998
+ *
70999
+ * Never throws: a refusal ("this repo has 24 quantizations", "this is
71000
+ * gated", "23 GB is over the ceiling") is an ANSWER the operator has to
71001
+ * read and act on, and turning it into a tRPC error would reduce all of
71002
+ * them to a red toast with no candidate list and no override.
71003
+ */
71004
+ resolveModelRef: async ({ ref, maxBytes }) => {
71005
+ const token = deps.hfToken?.();
71006
+ const outcome = await resolveHfReference(ref, {
71007
+ ...maxBytes !== void 0 ? { maxBytes } : {},
71008
+ ...token !== void 0 && token !== "" ? { token } : {}
71009
+ });
71010
+ if (!outcome.ok) {
71011
+ deps.logger?.info("llm model reference refused", { meta: {
71012
+ ref,
71013
+ code: outcome.error.code
71014
+ } });
71015
+ return {
71016
+ ok: false,
71017
+ code: outcome.error.code,
71018
+ message: outcome.error.message,
71019
+ ...outcome.error.candidates !== void 0 ? { candidates: [...outcome.error.candidates] } : {},
71020
+ ...outcome.error.requiredBytes !== void 0 ? { requiredBytes: outcome.error.requiredBytes } : {}
71021
+ };
71022
+ }
71023
+ const { resolution } = outcome;
71024
+ deps.logger?.info("llm model reference resolved", { meta: {
71025
+ ref,
71026
+ repo: resolution.repo,
71027
+ quantization: resolution.quantization,
71028
+ purpose: resolution.purpose,
71029
+ totalBytes: resolution.totalBytes
71030
+ } });
71031
+ return {
71032
+ ok: true,
71033
+ model: {
71034
+ kind: "url",
71035
+ url: resolution.main.url,
71036
+ ...resolution.main.sha256 !== void 0 ? { sha256: resolution.main.sha256 } : {},
71037
+ label: resolution.label,
71038
+ sizeBytes: resolution.main.sizeBytes,
71039
+ extraFiles: resolution.extras.map((e) => ({
71040
+ url: e.url,
71041
+ filename: e.filename,
71042
+ sizeBytes: e.sizeBytes,
71043
+ ...e.sha256 !== void 0 ? { sha256: e.sha256 } : {}
71044
+ }))
71045
+ },
71046
+ label: resolution.label,
71047
+ repo: resolution.repo,
71048
+ quantization: resolution.quantization,
71049
+ purpose: resolution.purpose,
71050
+ totalBytes: resolution.totalBytes,
71051
+ extraFilenames: resolution.extras.map((e) => e.filename)
71052
+ };
71053
+ },
70319
71054
  installModel: async ({ nodeId, model }) => {
70320
71055
  const runtime = requireRuntime(deps.runtime);
70321
71056
  try {
@@ -70349,13 +71084,29 @@ function createLlmProvider(deps) {
70349
71084
  //#endregion
70350
71085
  //#region src/runtime/llm-model-catalog.ts
70351
71086
  /**
70352
- * Curated managed-model catalog (operator decision #4): ~2 small text GGUFs
70353
- * (2-4B, Q4) + 1 small vision GGUF with its companion mmproj, sized to the
70354
- * weakest runtime node (the N100 agent). Each entry carries BOTH the LLM-facing
70355
- * picker view (`meta`) and the REUSED download-plane `ModelCatalogEntry`
70356
- * (`entry`) so GGUFs ride `ensureModel` + `model-distributor` untouched — no
70357
- * bespoke fetcher (spec §4.2). Digests/sizes pinned via
70358
- * scratchpad/pin-llm-models.mjs (HF LFS `lfs.oid`).
71087
+ * Curated managed-model catalog (operator decision #4). Each entry carries BOTH
71088
+ * the LLM-facing picker view (`meta`) and the REUSED download-plane
71089
+ * `ModelCatalogEntry` (`entry`) so GGUFs ride `ensureModel` +
71090
+ * `model-distributor` untouched no bespoke fetcher (spec §4.2).
71091
+ * Digests/sizes pinned via scratchpad/pin-llm-models.mjs (HF LFS `lfs.oid`,
71092
+ * which IS the file's sha256).
71093
+ *
71094
+ * ## Two tiers, and `minRamBytes` is what separates them
71095
+ *
71096
+ * The first three entries are sized to the WEAKEST runtime node (the N100
71097
+ * agent): 1-4 GB, Q4. `QWEN36_35B` is not — it is 23 GB and only a big node
71098
+ * can hold it. The catalog does not refuse to show it; `minRamBytes` is the
71099
+ * guidance, and the picker prints the size. Keeping the tiers in one list is
71100
+ * deliberate: an operator with a 64 GB box should not have to discover the
71101
+ * free-text field to run something real.
71102
+ *
71103
+ * ## This list is no longer the boundary of what can run
71104
+ *
71105
+ * Anything on Hugging Face is installable through `llm.resolveModelRef` +
71106
+ * `installModel` without a code change ({@link ./hf-ref.ts}). An entry here
71107
+ * buys exactly two things over typing the reference: a pinned digest nobody
71108
+ * has to re-verify, and a `contextSizeDefault`/`minRamBytes` somebody checked.
71109
+ * Add one only when both are true.
70359
71110
  */
70360
71111
  var GIB = 1024 * 1024 * 1024;
70361
71112
  function mb(bytes) {
@@ -70407,30 +71158,117 @@ var LLAMA = textEntry({
70407
71158
  var SMOLVLM_MODEL_BYTES = 1112602656;
70408
71159
  var SMOLVLM_MMPROJ_BYTES = 872303680;
70409
71160
  var SMOLVLM_MMPROJ_URL = "https://huggingface.co/ggml-org/SmolVLM2-2.2B-Instruct-GGUF/resolve/main/mmproj-SmolVLM2-2.2B-Instruct-f16.gguf";
71161
+ var SMOLVLM = {
71162
+ meta: {
71163
+ id: "llm-smolvlm2-2.2b-instruct-q4",
71164
+ label: "SmolVLM2 2.2B Instruct (vision)",
71165
+ family: "smolvlm2",
71166
+ purpose: "vision",
71167
+ url: "https://huggingface.co/ggml-org/SmolVLM2-2.2B-Instruct-GGUF/resolve/main/SmolVLM2-2.2B-Instruct-Q4_K_M.gguf",
71168
+ sha256: "0cf76814555b8665149075b74ab6b5c1d428ea1d3d01c1918c12012e8d7c9f58",
71169
+ sizeBytes: SMOLVLM_MODEL_BYTES,
71170
+ quantization: "Q4_K_M",
71171
+ minRamBytes: 4 * GIB,
71172
+ contextSizeDefault: 4096,
71173
+ mmprojUrl: SMOLVLM_MMPROJ_URL
71174
+ },
71175
+ entry: {
71176
+ id: "llm-smolvlm2-2.2b-instruct-q4",
71177
+ name: "SmolVLM2 2.2B Instruct (vision)",
71178
+ description: "smolvlm2 · Q4_K_M · +mmproj",
71179
+ formats: { gguf: {
71180
+ url: "https://huggingface.co/ggml-org/SmolVLM2-2.2B-Instruct-GGUF/resolve/main/SmolVLM2-2.2B-Instruct-Q4_K_M.gguf",
71181
+ sizeMB: mb(SMOLVLM_MODEL_BYTES)
71182
+ } },
71183
+ inputSize: {
71184
+ width: 0,
71185
+ height: 0
71186
+ },
71187
+ labels: [],
71188
+ extraFiles: [{
71189
+ url: SMOLVLM_MMPROJ_URL,
71190
+ filename: "mmproj-SmolVLM2-2.2B-Instruct-f16.gguf",
71191
+ sizeMB: mb(SMOLVLM_MMPROJ_BYTES)
71192
+ }]
71193
+ }
71194
+ };
71195
+ var QWEN3VL2B_MODEL_BYTES = 1107410624;
71196
+ var QWEN3VL2B_MMPROJ_BYTES = 819395232;
71197
+ var QWEN3VL2B_BASE = "https://huggingface.co/unsloth/Qwen3-VL-2B-Instruct-GGUF/resolve/main";
71198
+ var QWEN3VL2B_MMPROJ_URL = `${QWEN3VL2B_BASE}/mmproj-F16.gguf`;
71199
+ var QWEN3VL2B_URL = `${QWEN3VL2B_BASE}/Qwen3-VL-2B-Instruct-Q4_K_M.gguf`;
71200
+ /**
71201
+ * The light vision tier the operator asked for by weight class (~2 GB all in):
71202
+ * same Qwen3-VL family as the LM Studio 8B profile already in daily use, so
71203
+ * prompts and behaviour carry over — at a tenth of the 35B's disk and a RAM
71204
+ * floor a hub-adjacent node can always afford. This is the sensible default
71205
+ * for the NC confirm gates and summary judges.
71206
+ */
71207
+ var QWEN3VL_2B = {
71208
+ meta: {
71209
+ id: "llm-qwen3-vl-2b-instruct-q4",
71210
+ label: "Qwen3-VL 2B Instruct (vision, light)",
71211
+ family: "qwen3-vl",
71212
+ purpose: "vision",
71213
+ url: QWEN3VL2B_URL,
71214
+ sha256: "858fcf2a39dc73b26dd86592cb0a5f949b59d1edb365d1dea98e46b02e955e56",
71215
+ sizeBytes: QWEN3VL2B_MODEL_BYTES,
71216
+ quantization: "Q4_K_M",
71217
+ minRamBytes: 3 * GIB,
71218
+ contextSizeDefault: 8192,
71219
+ mmprojUrl: QWEN3VL2B_MMPROJ_URL
71220
+ },
71221
+ entry: {
71222
+ id: "llm-qwen3-vl-2b-instruct-q4",
71223
+ name: "Qwen3-VL 2B Instruct (vision, light)",
71224
+ description: "qwen3-vl · Q4_K_M · +mmproj",
71225
+ formats: { gguf: {
71226
+ url: QWEN3VL2B_URL,
71227
+ sizeMB: mb(QWEN3VL2B_MODEL_BYTES)
71228
+ } },
71229
+ inputSize: {
71230
+ width: 0,
71231
+ height: 0
71232
+ },
71233
+ labels: [],
71234
+ extraFiles: [{
71235
+ url: QWEN3VL2B_MMPROJ_URL,
71236
+ filename: "mmproj-F16.gguf",
71237
+ sizeMB: mb(QWEN3VL2B_MMPROJ_BYTES)
71238
+ }]
71239
+ }
71240
+ };
71241
+ var QWEN36_MODEL_BYTES = 22134528992;
71242
+ var QWEN36_MMPROJ_BYTES = 899283680;
71243
+ var QWEN36_BASE = "https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF/resolve/main";
71244
+ var QWEN36_MMPROJ_URL = `${QWEN36_BASE}/mmproj-F16.gguf`;
71245
+ var QWEN36_URL = `${QWEN36_BASE}/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf`;
70410
71246
  var LLM_MODEL_CATALOG = [
70411
71247
  QWEN,
70412
71248
  LLAMA,
71249
+ SMOLVLM,
71250
+ QWEN3VL_2B,
70413
71251
  {
70414
71252
  meta: {
70415
- id: "llm-smolvlm2-2.2b-instruct-q4",
70416
- label: "SmolVLM2 2.2B Instruct (vision)",
70417
- family: "smolvlm2",
71253
+ id: "llm-qwen3.6-35b-a3b-ud-q4",
71254
+ label: "Qwen3.6 35B-A3B (vision)",
71255
+ family: "qwen3.6",
70418
71256
  purpose: "vision",
70419
- url: "https://huggingface.co/ggml-org/SmolVLM2-2.2B-Instruct-GGUF/resolve/main/SmolVLM2-2.2B-Instruct-Q4_K_M.gguf",
70420
- sha256: "0cf76814555b8665149075b74ab6b5c1d428ea1d3d01c1918c12012e8d7c9f58",
70421
- sizeBytes: SMOLVLM_MODEL_BYTES,
70422
- quantization: "Q4_K_M",
70423
- minRamBytes: 4 * GIB,
70424
- contextSizeDefault: 4096,
70425
- mmprojUrl: SMOLVLM_MMPROJ_URL
71257
+ url: QWEN36_URL,
71258
+ sha256: "ac0e2c1189e055faa36eff361580e79c5bd6f8e76bffb4ce547f167d53e31a61",
71259
+ sizeBytes: QWEN36_MODEL_BYTES,
71260
+ quantization: "UD-Q4_K_M",
71261
+ minRamBytes: 26 * GIB,
71262
+ contextSizeDefault: 32768,
71263
+ mmprojUrl: QWEN36_MMPROJ_URL
70426
71264
  },
70427
71265
  entry: {
70428
- id: "llm-smolvlm2-2.2b-instruct-q4",
70429
- name: "SmolVLM2 2.2B Instruct (vision)",
70430
- description: "smolvlm2 · Q4_K_M · +mmproj",
71266
+ id: "llm-qwen3.6-35b-a3b-ud-q4",
71267
+ name: "Qwen3.6 35B-A3B (vision)",
71268
+ description: "qwen3.6 · UD-Q4_K_M · +mmproj",
70431
71269
  formats: { gguf: {
70432
- url: "https://huggingface.co/ggml-org/SmolVLM2-2.2B-Instruct-GGUF/resolve/main/SmolVLM2-2.2B-Instruct-Q4_K_M.gguf",
70433
- sizeMB: mb(SMOLVLM_MODEL_BYTES)
71270
+ url: QWEN36_URL,
71271
+ sizeMB: mb(QWEN36_MODEL_BYTES)
70434
71272
  } },
70435
71273
  inputSize: {
70436
71274
  width: 0,
@@ -70438,9 +71276,9 @@ var LLM_MODEL_CATALOG = [
70438
71276
  },
70439
71277
  labels: [],
70440
71278
  extraFiles: [{
70441
- url: SMOLVLM_MMPROJ_URL,
70442
- filename: "mmproj-SmolVLM2-2.2B-Instruct-f16.gguf",
70443
- sizeMB: mb(SMOLVLM_MMPROJ_BYTES)
71279
+ url: QWEN36_MMPROJ_URL,
71280
+ filename: "mmproj-F16.gguf",
71281
+ sizeMB: mb(QWEN36_MMPROJ_BYTES)
70444
71282
  }]
70445
71283
  }
70446
71284
  }
@@ -70457,19 +71295,25 @@ function entryForRef(ref) {
70457
71295
  }
70458
71296
  if (ref.kind === "url") {
70459
71297
  const id = `llm-custom-${(0, node_crypto.createHash)("sha1").update(ref.url).digest("hex").slice(0, 12)}`;
71298
+ const extraFiles = (ref.extraFiles ?? []).map((f) => ({
71299
+ url: f.url,
71300
+ filename: f.filename,
71301
+ sizeMB: mb(f.sizeBytes)
71302
+ }));
70460
71303
  return { entry: {
70461
71304
  id,
70462
- name: id,
71305
+ name: ref.label ?? id,
70463
71306
  description: "custom GGUF",
70464
71307
  formats: { gguf: {
70465
71308
  url: ref.url,
70466
- sizeMB: 0
71309
+ sizeMB: ref.sizeBytes === void 0 ? 0 : mb(ref.sizeBytes)
70467
71310
  } },
70468
71311
  inputSize: {
70469
71312
  width: 0,
70470
71313
  height: 0
70471
71314
  },
70472
- labels: []
71315
+ labels: [],
71316
+ ...extraFiles.length > 0 ? { extraFiles } : {}
70473
71317
  } };
70474
71318
  }
70475
71319
  const id = `llm-path-${(0, node_crypto.createHash)("sha1").update(ref.path).digest("hex").slice(0, 12)}`;
@@ -70507,10 +71351,6 @@ function isNonEmptyFile(filePath) {
70507
71351
  function siblingFilesFor(formatEntry) {
70508
71352
  return formatEntry.isDirectory ? [] : formatEntry.files ?? [];
70509
71353
  }
70510
- /** Resolve a sibling's remote URL relative to the main file's directory. */
70511
- function siblingUrl(mainUrl, sibling) {
70512
- return mainUrl.replace(/[^/]+$/, sibling);
70513
- }
70514
71354
  /** Build fetch headers, including HF auth token for huggingface.co URLs */
70515
71355
  function buildHeaders(url) {
70516
71356
  const headers = { "User-Agent": "CamStack/1.0" };
@@ -70563,77 +71403,6 @@ async function downloadFile(url, destPath, onProgress) {
70563
71403
  throw err;
70564
71404
  }
70565
71405
  }
70566
- /**
70567
- * Download every file in a HuggingFace directory bundle (e.g.,
70568
- * `.mlpackage` / OpenVINO IR pair) atomically. `knownFiles` lists the
70569
- * relative paths inside the directory; the function fetches each from
70570
- * `${url}/${file}` and renames the staging directory only on full
70571
- * success. Mirrors `ModelDownloadService.downloadDirectory` but
70572
- * exposed as a standalone for catalog-less callers.
70573
- */
70574
- async function downloadDirectory(url, destDir, knownFiles, onProgress) {
70575
- const match = url.match(/huggingface\.co\/([^/]+\/[^/]+)\/resolve\/main\/(.+)/);
70576
- if (!match) throw new Error(`Cannot parse HuggingFace URL: ${url}`);
70577
- const [, repo, dirPath] = match;
70578
- const files = (knownFiles ?? []).map((f) => ({
70579
- relativePath: f,
70580
- fileUrl: `https://huggingface.co/${repo}/resolve/main/${dirPath}/${f}`
70581
- }));
70582
- if (files.length === 0) throw new Error(`Directory bundle requires explicit \`files\` list (got none for ${url})`);
70583
- const tmpDir = destDir + ".downloading";
70584
- node_fs.rmSync(tmpDir, {
70585
- recursive: true,
70586
- force: true
70587
- });
70588
- node_fs.mkdirSync(tmpDir, { recursive: true });
70589
- let totalDownloaded = 0;
70590
- try {
70591
- for (const file of files) {
70592
- const destPath = node_path$1.join(tmpDir, file.relativePath);
70593
- node_fs.mkdirSync(node_path$1.dirname(destPath), { recursive: true });
70594
- await downloadFile(file.fileUrl, destPath, (downloaded, _total) => {
70595
- onProgress?.(totalDownloaded + downloaded, void 0);
70596
- });
70597
- totalDownloaded += node_fs.statSync(destPath).size;
70598
- }
70599
- node_fs.rmSync(destDir, {
70600
- recursive: true,
70601
- force: true
70602
- });
70603
- node_fs.renameSync(tmpDir, destDir);
70604
- } catch (err) {
70605
- node_fs.rmSync(tmpDir, {
70606
- recursive: true,
70607
- force: true
70608
- });
70609
- throw err;
70610
- }
70611
- }
70612
- /**
70613
- * Resolve a `ModelCatalogEntry` against `modelsDir`: download model file
70614
- * (or directory bundle) + extra files (labels JSON, charset dict, …),
70615
- * skip if already on disk. Returns the local model path.
70616
- */
70617
- async function ensureModel(modelsDir, entry, format, onProgress) {
70618
- const formatEntry = entry.formats[format];
70619
- if (!formatEntry) throw new Error(`Model "${entry.id}" has no ${format} format. Available: ${Object.keys(entry.formats).join(", ")}`);
70620
- if (entry.extraFiles) for (const extra of entry.extraFiles) await downloadFile(extra.url, node_path$1.join(modelsDir, extra.filename));
70621
- const filename = formatEntry.url.split("/").pop() ?? `${entry.id}.${format}`;
70622
- const modelPath = node_path$1.join(modelsDir, filename);
70623
- const siblings = siblingFilesFor(formatEntry);
70624
- if (node_fs.existsSync(modelPath)) if (formatEntry.isDirectory && !node_fs.existsSync(node_path$1.join(modelPath, "Manifest.json"))) node_fs.rmSync(modelPath, {
70625
- recursive: true,
70626
- force: true
70627
- });
70628
- else if (siblings.some((f) => !isNonEmptyFile(node_path$1.join(modelsDir, f)))) {} else return modelPath;
70629
- node_fs.mkdirSync(modelsDir, { recursive: true });
70630
- if (formatEntry.isDirectory) await downloadDirectory(formatEntry.url, modelPath, formatEntry.files, onProgress);
70631
- else {
70632
- await downloadFile(formatEntry.url, modelPath, (downloaded, total) => onProgress?.(downloaded, total === 0 ? void 0 : total));
70633
- for (const sibling of siblings) await downloadFile(siblingUrl(formatEntry.url, sibling), node_path$1.join(modelsDir, sibling));
70634
- }
70635
- return modelPath;
70636
- }
70637
71406
  /** Compute the on-disk path for a given model + format, even when not yet downloaded. */
70638
71407
  function getModelFilePath(modelsDir, entry, format) {
70639
71408
  const formatEntry = entry.formats[format];
@@ -70677,13 +71446,79 @@ function deleteModelFromDisk(modelsDir, entry, format) {
70677
71446
  * Default `RuntimeModelOps` — the ONLY place the reused object-detection model
70678
71447
  * mechanism is imported (the documented `@camstack/system/addon-utils`
70679
71448
  * build-time-dep waiver that addon-post-analysis/addon-pipeline already use).
70680
- * GGUFs ride `ensureModel`/`isModelDownloaded`/`deleteModelFromDisk` untouched
70681
- * (spec §4.2) — no bespoke fetcher.
71449
+ * GGUFs ride the SHARED `downloadFile` (atomic `.downloading` + rename, HF
71450
+ * token headers, redirect following) — no bespoke fetcher (spec §4.2).
71451
+ *
71452
+ * ## Why this drives the file loop instead of calling `ensureModel`
71453
+ *
71454
+ * `ensureModel` downloads `extraFiles` FIRST and passes them NO progress
71455
+ * callback. That is invisible for a 40 kB labels JSON and unacceptable here: a
71456
+ * GGUF install is a 22 GB main file, up to N shards, and a 0.9 GB mmproj, and
71457
+ * under `ensureModel` every byte outside the main file moves in silence. A
71458
+ * multi-GB download that reports nothing reads as a hung node — the repo rule
71459
+ * is that a branch doing real work says so.
71460
+ *
71461
+ * So the loop is here, over the SAME `downloadFile`. What is gained: bytes
71462
+ * aggregated across the whole install, the name of the file currently moving,
71463
+ * and files already on disk excluded from the total rather than counted as
71464
+ * instantly-complete.
70682
71465
  */
70683
71466
  var GGUF = "gguf";
71467
+ var BYTES_PER_MB = 1024 * 1024;
71468
+ /**
71469
+ * Main file first, then shards/mmproj. Deliberate: a gated or mistyped URL
71470
+ * fails on the file that matters before 0.9 GB of projector is spent on it.
71471
+ */
71472
+ function planFiles(modelsDir, entry) {
71473
+ const out = [];
71474
+ const formatEntry = entry.formats[GGUF];
71475
+ if (formatEntry !== void 0) {
71476
+ const filename = formatEntry.url.split("/").pop() ?? `${entry.id}.${GGUF}`;
71477
+ out.push({
71478
+ url: formatEntry.url,
71479
+ destPath: node_path.join(modelsDir, filename),
71480
+ filename,
71481
+ expectedBytes: formatEntry.sizeMB * BYTES_PER_MB
71482
+ });
71483
+ }
71484
+ for (const extra of entry.extraFiles ?? []) out.push({
71485
+ url: extra.url,
71486
+ destPath: node_path.join(modelsDir, extra.filename),
71487
+ filename: extra.filename,
71488
+ expectedBytes: extra.sizeMB * BYTES_PER_MB
71489
+ });
71490
+ return out;
71491
+ }
70684
71492
  function createDefaultModelOps(modelsDir) {
70685
71493
  return {
70686
- ensure: (entry, onProgress) => ensureModel(modelsDir, entry, GGUF, (downloaded, total) => onProgress(total !== void 0 && total > 0 ? downloaded / total : 0)),
71494
+ ensure: async (entry, onProgress) => {
71495
+ if (entry.formats[GGUF] === void 0) throw new Error(`model ${entry.id} declares no gguf format`);
71496
+ const missing = planFiles(modelsDir, entry).filter((f) => !(0, node_fs.existsSync)(f.destPath));
71497
+ const totalBytes = missing.reduce((sum, f) => sum + f.expectedBytes, 0);
71498
+ let carried = 0;
71499
+ for (const [index, file] of missing.entries()) {
71500
+ onProgress({
71501
+ file: file.filename,
71502
+ fileIndex: index + 1,
71503
+ fileCount: missing.length,
71504
+ downloadedBytes: carried,
71505
+ ...totalBytes > 0 ? { totalBytes } : {}
71506
+ });
71507
+ await downloadFile(file.url, file.destPath, (downloaded) => {
71508
+ onProgress({
71509
+ file: file.filename,
71510
+ fileIndex: index + 1,
71511
+ fileCount: missing.length,
71512
+ downloadedBytes: carried + downloaded,
71513
+ ...totalBytes > 0 ? { totalBytes } : {}
71514
+ });
71515
+ });
71516
+ carried += (0, node_fs.existsSync)(file.destPath) ? (0, node_fs.statSync)(file.destPath).size : file.expectedBytes;
71517
+ }
71518
+ const main = getModelFilePath(modelsDir, entry, GGUF);
71519
+ if (main === null) throw new Error(`no gguf path for model ${entry.id}`);
71520
+ return main;
71521
+ },
70687
71522
  isDownloaded: (entry) => isModelDownloaded(modelsDir, entry, GGUF),
70688
71523
  pathFor: (entry) => {
70689
71524
  const p = getModelFilePath(modelsDir, entry, GGUF);
@@ -70697,318 +71532,6 @@ function createDefaultModelOps(modelsDir) {
70697
71532
  };
70698
71533
  }
70699
71534
  //#endregion
70700
- //#region src/runtime/sha256.ts
70701
- /**
70702
- * File sha256 — a local copy of the private `computeSha256` at
70703
- * model-downloader.ts (not exported from @camstack/system), streamed so it
70704
- * never buffers a multi-GB artifact.
70705
- */
70706
- function fileSha256(filePath) {
70707
- return new Promise((resolve, reject) => {
70708
- const hash = (0, node_crypto.createHash)("sha256");
70709
- const stream = (0, node_fs.createReadStream)(filePath);
70710
- stream.on("error", reject);
70711
- stream.on("data", (chunk) => hash.update(chunk));
70712
- stream.on("end", () => resolve(hash.digest("hex")));
70713
- });
70714
- }
70715
- //#endregion
70716
- //#region src/runtime/runtime-provider.ts
70717
- /**
70718
- * `llm-runtime` provider — the node-side managed executor. Reuses the
70719
- * object-detection model plane (ensureModel/isModelDownloaded/delete via the
70720
- * injected `RuntimeModelOps`) for GGUF artifacts, the `LlamaSupervisor` for the
70721
- * llama-server child, and the SHARED {@link LlmClient} for the local inference
70722
- * wire (only lifecycle + locality differ — spec §2). GGUFs are
70723
- * multi-GB, so a missing model is an EXPLICIT-install error, never an auto-pull.
70724
- * Usage rows are written hub-side only (single accounting point).
70725
- */
70726
- function basename(url) {
70727
- const clean = url.split("?")[0] ?? url;
70728
- return clean.slice(clean.lastIndexOf("/") + 1);
70729
- }
70730
- function catalogIdForFile(file) {
70731
- return LLM_MODEL_CATALOG.find((m) => basename(m.meta.url) === file)?.meta.id;
70732
- }
70733
- function mmprojFilename(entry) {
70734
- return entry.extraFiles?.[0]?.filename;
70735
- }
70736
- function createLlmRuntimeProvider(deps) {
70737
- let downloadProgress;
70738
- async function resolvePaths(runtime) {
70739
- const resolution = entryForRef(runtime.model);
70740
- if (resolution === null) throw new Error("unknown model reference");
70741
- const { entry, localPathOverride } = resolution;
70742
- const modelPath = localPathOverride ?? deps.modelOps.pathFor(entry);
70743
- const mmproj = mmprojFilename(entry);
70744
- return {
70745
- modelId: entry.id,
70746
- modelPath,
70747
- ...mmproj !== void 0 ? { mmprojPath: deps.modelOps.extraFilePath(entry, mmproj) } : {}
70748
- };
70749
- }
70750
- function installedGuard(runtime) {
70751
- const resolution = entryForRef(runtime.model);
70752
- if (resolution === null) return {
70753
- ok: false,
70754
- message: "unknown model reference"
70755
- };
70756
- if (resolution.localPathOverride !== void 0) return { ok: true };
70757
- if (!deps.modelOps.isDownloaded(resolution.entry)) return {
70758
- ok: false,
70759
- message: `model ${resolution.entry.id} not installed on node ${deps.nodeId}`
70760
- };
70761
- return { ok: true };
70762
- }
70763
- async function ensureStartedInternal(runtime) {
70764
- const binaryPath = await deps.ensureBinary();
70765
- const paths = await resolvePaths(runtime);
70766
- const startCfg = {
70767
- nodeId: deps.nodeId,
70768
- modelId: paths.modelId,
70769
- modelPath: paths.modelPath,
70770
- ...paths.mmprojPath !== void 0 ? { mmprojPath: paths.mmprojPath } : {},
70771
- contextSize: runtime.contextSize,
70772
- gpuLayers: runtime.gpuLayers,
70773
- ...runtime.threads !== void 0 ? { threads: runtime.threads } : {},
70774
- parallel: runtime.parallel,
70775
- ...runtime.batchSize !== void 0 ? { batchSize: runtime.batchSize } : {},
70776
- ...runtime.ubatchSize !== void 0 ? { ubatchSize: runtime.ubatchSize } : {},
70777
- flashAttention: runtime.flashAttention,
70778
- mlock: runtime.mlock,
70779
- noMmap: runtime.noMmap,
70780
- ...runtime.cacheTypeK !== void 0 ? { cacheTypeK: runtime.cacheTypeK } : {},
70781
- ...runtime.cacheTypeV !== void 0 ? { cacheTypeV: runtime.cacheTypeV } : {},
70782
- idleStopMinutes: runtime.idleStopMinutes,
70783
- binaryPath
70784
- };
70785
- return deps.supervisor.start(startCfg);
70786
- }
70787
- function status() {
70788
- return {
70789
- ...deps.supervisor.status(),
70790
- nodeId: deps.nodeId,
70791
- ...downloadProgress !== void 0 ? { downloadProgress } : {}
70792
- };
70793
- }
70794
- return {
70795
- complete: async (input) => {
70796
- const guard = installedGuard(input.runtime);
70797
- if (!guard.ok) return {
70798
- ok: false,
70799
- code: "unavailable",
70800
- message: guard.message
70801
- };
70802
- await ensureStartedInternal(input.runtime);
70803
- const port = deps.supervisor.port;
70804
- if (port === void 0) return {
70805
- ok: false,
70806
- code: "unavailable",
70807
- message: "llama-server has no port"
70808
- };
70809
- const paths = await resolvePaths(input.runtime);
70810
- const timeoutMs = input.timeoutMs ?? 12e4;
70811
- const localProfile = {
70812
- id: "managed-local",
70813
- name: "managed-local",
70814
- kind: "openai-compatible",
70815
- addonId: "ai",
70816
- enabled: true,
70817
- model: paths.modelId,
70818
- baseUrl: `http://127.0.0.1:${String(port)}/v1`,
70819
- supportsVision: paths.mmprojPath !== void 0,
70820
- timeoutMs,
70821
- connectTimeoutMs: LlmTimeoutDefaults.connectMs,
70822
- firstTokenTimeoutMs: LlmTimeoutDefaults.firstTokenMs,
70823
- idleTimeoutMs: LlmTimeoutDefaults.idleMs,
70824
- retry: {
70825
- enabled: false,
70826
- maxAttempts: 1
70827
- },
70828
- toolsEnabled: false
70829
- };
70830
- const result = await deps.client.generate({
70831
- profile: localProfile,
70832
- ...input.system !== void 0 ? { system: input.system } : {},
70833
- prompt: input.prompt,
70834
- ...input.images !== void 0 ? { images: input.images } : {},
70835
- ...input.jsonSchema !== void 0 ? { jsonSchema: input.jsonSchema } : {},
70836
- ...input.maxTokens !== void 0 ? { maxTokens: input.maxTokens } : {},
70837
- ...input.temperature !== void 0 ? { temperature: input.temperature } : {},
70838
- ...input.topP !== void 0 ? { topP: input.topP } : {},
70839
- ...input.topK !== void 0 ? { topK: input.topK } : {},
70840
- signal: new AbortController().signal
70841
- }, timeoutMs);
70842
- deps.supervisor.noteActivity();
70843
- return result;
70844
- },
70845
- ensureStarted: async ({ runtime }) => {
70846
- const guard = installedGuard(runtime);
70847
- if (!guard.ok) return {
70848
- nodeId: deps.nodeId,
70849
- state: "stopped",
70850
- lastError: guard.message,
70851
- crashesInWindow: 0
70852
- };
70853
- return ensureStartedInternal(runtime);
70854
- },
70855
- stop: async () => {
70856
- await deps.supervisor.stop();
70857
- },
70858
- status: async () => status(),
70859
- installModel: async ({ model }) => {
70860
- const resolution = entryForRef(model);
70861
- if (resolution === null) throw new Error("unknown model reference");
70862
- if (resolution.localPathOverride !== void 0) return;
70863
- downloadProgress = 0;
70864
- try {
70865
- await deps.modelOps.ensure(resolution.entry, (frac) => {
70866
- downloadProgress = frac;
70867
- });
70868
- if (model.kind === "url" && model.sha256 !== void 0) {
70869
- const filePath = deps.modelOps.pathFor(resolution.entry);
70870
- if (await (deps.fileSha256 ?? fileSha256)(filePath) !== model.sha256) {
70871
- await deps.modelOps.delete(resolution.entry);
70872
- throw new Error(`sha256 mismatch for ${model.url}`);
70873
- }
70874
- }
70875
- } finally {
70876
- downloadProgress = void 0;
70877
- }
70878
- },
70879
- deleteModel: async ({ file }) => {
70880
- const loaded = deps.supervisor.status().modelPath;
70881
- if (loaded !== void 0 && basename(loaded) === file) throw new Error(`cannot delete ${file}: loaded by the running runtime`);
70882
- await node_fs_promises.rm(node_path.join(deps.modelsDir, file), { force: true });
70883
- },
70884
- listLocalModels: async () => {
70885
- return (await listGgufFiles(deps.modelsDir)).map((f) => {
70886
- const catalogId = catalogIdForFile(f.file);
70887
- return {
70888
- file: f.file,
70889
- sizeBytes: f.sizeBytes,
70890
- ...catalogId !== void 0 ? { catalogId } : {}
70891
- };
70892
- });
70893
- },
70894
- getDiskUsage: async () => {
70895
- const modelsBytes = (await listGgufFiles(deps.modelsDir)).reduce((sum, f) => sum + f.sizeBytes, 0);
70896
- return {
70897
- nodeId: deps.nodeId,
70898
- modelsBytes
70899
- };
70900
- }
70901
- };
70902
- }
70903
- async function listGgufFiles(dir) {
70904
- let names;
70905
- try {
70906
- names = await node_fs_promises.readdir(dir);
70907
- } catch {
70908
- return [];
70909
- }
70910
- const out = [];
70911
- for (const name of names) {
70912
- if (!name.endsWith(".gguf")) continue;
70913
- try {
70914
- const stat = await node_fs_promises.stat(node_path.join(dir, name));
70915
- out.push({
70916
- file: name,
70917
- sizeBytes: stat.size
70918
- });
70919
- } catch {}
70920
- }
70921
- return out;
70922
- }
70923
- //#endregion
70924
- //#region src/runtime-client.ts
70925
- /**
70926
- * `RuntimeClient` over the cap plane — every verb pins the target node with
70927
- * `nodePin(nodeId)` (transport-level, never a hand-rolled routing field). The
70928
- * CapRouteResolver classifies the pin into hub-local-uds / remote-moleculer /
70929
- * agent-child-forward transparently (spec §4.1; the model-studio cross-node
70930
- * convert precedent). Node enumeration is the `nodes.topology` roster filtered
70931
- * to nodes advertising the `llm-runtime` cap — never a shadow registry.
70932
- */
70933
- var LLM_RUNTIME_CAP = "llm-runtime";
70934
- function createRuntimeClient(api) {
70935
- return {
70936
- complete: (nodeId, input) => api.llmRuntime.complete.mutate(input, nodePin(nodeId)),
70937
- ensureStarted: (nodeId, runtime) => api.llmRuntime.ensureStarted.mutate({ runtime }, nodePin(nodeId)),
70938
- stopRuntime: (nodeId) => api.llmRuntime.stop.mutate({}, nodePin(nodeId)),
70939
- status: (nodeId) => api.llmRuntime.status.query({}, nodePin(nodeId)),
70940
- installModel: (nodeId, model) => api.llmRuntime.installModel.mutate({ model }, nodePin(nodeId)),
70941
- deleteModel: (nodeId, file) => api.llmRuntime.deleteModel.mutate({ file }, nodePin(nodeId)),
70942
- listLocalModels: (nodeId) => api.llmRuntime.listLocalModels.query({}, nodePin(nodeId)),
70943
- getDiskUsage: (nodeId) => api.llmRuntime.getDiskUsage.query({}, nodePin(nodeId)),
70944
- listRuntimeNodeIds: async () => {
70945
- const topology = await api.nodes.topology.query();
70946
- const ids = /* @__PURE__ */ new Set();
70947
- for (const node of topology) if (node.addons.some((a) => a.capabilities.includes(LLM_RUNTIME_CAP))) ids.add(node.id);
70948
- return [...ids];
70949
- }
70950
- };
70951
- }
70952
- //#endregion
70953
- //#region src/assembly.ts
70954
- /**
70955
- * Registration assembly (the hub/agent split, spec §1). Every node running
70956
- * addon-ai registers `llm-runtime`; ONLY the hub also registers the consumer
70957
- * `llm` surface (profiles/usage need outbound internet + API keys).
70958
- * Extracted from the addon class so the split + seeding is unit-testable
70959
- * without a full AddonContext.
70960
- */
70961
- async function assembleAi(deps) {
70962
- const client = deps.client ?? createLlmClient();
70963
- const runtimeProvider = createLlmRuntimeProvider({
70964
- nodeId: deps.nodeId,
70965
- modelsDir: deps.modelsDir,
70966
- ensureBinary: deps.ensureBinary,
70967
- supervisor: deps.supervisor,
70968
- modelOps: createDefaultModelOps(deps.modelsDir),
70969
- client,
70970
- logger: deps.logger.child("llm-runtime")
70971
- });
70972
- const registrations = [{
70973
- capability: llmRuntimeCapability,
70974
- provider: runtimeProvider
70975
- }];
70976
- if (!deps.isHub) return {
70977
- registrations,
70978
- runtimeProvider
70979
- };
70980
- const { UsageStore } = await Promise.resolve().then(() => require("./usage-store-Q34FDPSq.js")).then((n) => n.usage_store_exports);
70981
- const store = new ProfileStore(deps.settingsPort);
70982
- const defaults = new DefaultsStore(deps.settingsPort);
70983
- const usage = new UsageStore(deps.settingsPort, Date.now, deps.logger.child("llm-usage"));
70984
- await store.init();
70985
- await defaults.init();
70986
- await usage.init();
70987
- await store.ensureSeeded();
70988
- const llmProvider = createLlmProvider({
70989
- store,
70990
- defaults,
70991
- usage,
70992
- client,
70993
- ...deps.runtimeApi !== void 0 ? { runtime: createRuntimeClient(deps.runtimeApi) } : {},
70994
- ...deps.distributeModel !== void 0 ? { distributeModel: deps.distributeModel } : {},
70995
- catalog: LLM_MODEL_CATALOG.map((m) => m.meta),
70996
- logger: deps.logger.child("llm")
70997
- });
70998
- registrations.push({
70999
- capability: llmCapability,
71000
- provider: llmProvider
71001
- });
71002
- return {
71003
- registrations,
71004
- runtimeProvider,
71005
- llmProvider,
71006
- store,
71007
- usage,
71008
- prune: (retentionDays) => usage.prune(retentionDays)
71009
- };
71010
- }
71011
- //#endregion
71012
71535
  //#region src/runtime/crash-policy.ts
71013
71536
  var CrashPolicy = class {
71014
71537
  opts;
@@ -71058,6 +71581,63 @@ var DEFAULT_CRASH_POLICY = {
71058
71581
  * v1: at most one running child. Resource ceiling = llama-server flags +
71059
71582
  * idleStopMinutes ONLY (no RSS watchdog — operator decision #3).
71060
71583
  */
71584
+ /**
71585
+ * Every llama-server flag a TYPED field above already owns, mapped to the
71586
+ * field that owns it.
71587
+ *
71588
+ * This map is the whole reconciliation between the typed tuning surface and
71589
+ * the free-text "additional arguments" box. Both exist because neither is
71590
+ * sufficient — the typed fields give the common knobs a validated control and
71591
+ * a default, and llama.cpp has a hundred flags nobody is going to model — but
71592
+ * a flag settable from BOTH is a bug generator: whichever one loses is a
71593
+ * control the operator watched do nothing. So the box is an escape hatch for
71594
+ * what is NOT modelled, and reaching into it for something that is gets
71595
+ * rejected by name.
71596
+ */
71597
+ var OWNED_FLAGS = {
71598
+ "-m": "model",
71599
+ "--model": "model",
71600
+ "--host": "fixed to 127.0.0.1",
71601
+ "--port": "assigned by the supervisor",
71602
+ "-c": "contextSize",
71603
+ "--ctx-size": "contextSize",
71604
+ "-ngl": "gpuLayers",
71605
+ "--gpu-layers": "gpuLayers",
71606
+ "--n-gpu-layers": "gpuLayers",
71607
+ "-t": "threads",
71608
+ "--threads": "threads",
71609
+ "--parallel": "parallel",
71610
+ "-np": "parallel",
71611
+ "-b": "batchSize",
71612
+ "--batch-size": "batchSize",
71613
+ "-ub": "ubatchSize",
71614
+ "--ubatch-size": "ubatchSize",
71615
+ "-fa": "flashAttention",
71616
+ "--flash-attn": "flashAttention",
71617
+ "--mlock": "mlock",
71618
+ "--no-mmap": "noMmap",
71619
+ "-ctk": "cacheTypeK",
71620
+ "--cache-type-k": "cacheTypeK",
71621
+ "-ctv": "cacheTypeV",
71622
+ "--cache-type-v": "cacheTypeV",
71623
+ "--mmproj": "the vision model’s projector"
71624
+ };
71625
+ /**
71626
+ * Reject an `extraArgs` list that reaches for a flag a typed field owns.
71627
+ * `--flag=value` counts as `--flag`.
71628
+ */
71629
+ function checkExtraArgs(extraArgs) {
71630
+ for (const token of extraArgs) {
71631
+ if (!token.startsWith("-")) continue;
71632
+ const flag = token.split("=")[0] ?? token;
71633
+ const owner = OWNED_FLAGS[flag];
71634
+ if (owner !== void 0) return {
71635
+ ok: false,
71636
+ message: `"${flag}" is already set by the runtime field "${owner}" — set it there, not in additional arguments (a flag with two owners is a control that silently does nothing)`
71637
+ };
71638
+ }
71639
+ return { ok: true };
71640
+ }
71061
71641
  var HEALTH_GATE_INTERVAL_MS = 500;
71062
71642
  function defaultPickPort() {
71063
71643
  return new Promise((resolve, reject) => {
@@ -71108,6 +71688,7 @@ function buildLlamaArgs(cfg, port) {
71108
71688
  if (cfg.cacheTypeK !== void 0) args.push("--cache-type-k", cfg.cacheTypeK);
71109
71689
  if (cfg.cacheTypeV !== void 0) args.push("--cache-type-v", cfg.cacheTypeV);
71110
71690
  if (cfg.mmprojPath !== void 0) args.push("--mmproj", cfg.mmprojPath);
71691
+ args.push(...cfg.extraArgs ?? []);
71111
71692
  return args;
71112
71693
  }
71113
71694
  var LlamaSupervisor = class {
@@ -71332,6 +71913,463 @@ var LlamaSupervisor = class {
71332
71913
  }
71333
71914
  };
71334
71915
  //#endregion
71916
+ //#region src/runtime/sha256.ts
71917
+ /**
71918
+ * File sha256 — a local copy of the private `computeSha256` at
71919
+ * model-downloader.ts (not exported from @camstack/system), streamed so it
71920
+ * never buffers a multi-GB artifact.
71921
+ */
71922
+ function fileSha256(filePath) {
71923
+ return new Promise((resolve, reject) => {
71924
+ const hash = (0, node_crypto.createHash)("sha256");
71925
+ const stream = (0, node_fs.createReadStream)(filePath);
71926
+ stream.on("error", reject);
71927
+ stream.on("data", (chunk) => hash.update(chunk));
71928
+ stream.on("end", () => resolve(hash.digest("hex")));
71929
+ });
71930
+ }
71931
+ //#endregion
71932
+ //#region src/runtime/runtime-provider.ts
71933
+ /**
71934
+ * `llm-runtime` provider — the node-side managed executor. Reuses the
71935
+ * object-detection model plane (ensureModel/isModelDownloaded/delete via the
71936
+ * injected `RuntimeModelOps`) for GGUF artifacts, the `LlamaSupervisor` for the
71937
+ * llama-server child, and the SHARED {@link LlmClient} for the local inference
71938
+ * wire (only lifecycle + locality differ — spec §2). GGUFs are
71939
+ * multi-GB, so a missing model is an EXPLICIT-install error, never an auto-pull.
71940
+ * Usage rows are written hub-side only (single accounting point).
71941
+ */
71942
+ function basename(url) {
71943
+ const clean = url.split("?")[0] ?? url;
71944
+ return clean.slice(clean.lastIndexOf("/") + 1);
71945
+ }
71946
+ function catalogIdForFile(file) {
71947
+ return LLM_MODEL_CATALOG.find((m) => basename(m.meta.url) === file)?.meta.id;
71948
+ }
71949
+ /**
71950
+ * The projector among the extra files — matched by NAME, not by position.
71951
+ *
71952
+ * `extraFiles[0]` was safe while the only extra a GGUF entry ever had was an
71953
+ * mmproj. A split GGUF puts shards 2..N in the same list, so index 0 is now
71954
+ * routinely a weights shard, and passing one to `--mmproj` starts llama-server
71955
+ * against a file that is not a projector.
71956
+ */
71957
+ function mmprojFilename(entry) {
71958
+ return entry.extraFiles?.find((f) => f.filename.toLowerCase().startsWith("mmproj"))?.filename;
71959
+ }
71960
+ function gb(bytes) {
71961
+ return `${(bytes / 1e9).toFixed(2)} GB`;
71962
+ }
71963
+ function createLlmRuntimeProvider(deps) {
71964
+ let downloadProgress;
71965
+ let download;
71966
+ async function resolvePaths(runtime) {
71967
+ const resolution = entryForRef(runtime.model);
71968
+ if (resolution === null) throw new Error("unknown model reference");
71969
+ const { entry, localPathOverride } = resolution;
71970
+ const modelPath = localPathOverride ?? deps.modelOps.pathFor(entry);
71971
+ const mmproj = mmprojFilename(entry);
71972
+ return {
71973
+ modelId: entry.id,
71974
+ modelPath,
71975
+ ...mmproj !== void 0 ? { mmprojPath: deps.modelOps.extraFilePath(entry, mmproj) } : {}
71976
+ };
71977
+ }
71978
+ function installedGuard(runtime) {
71979
+ const resolution = entryForRef(runtime.model);
71980
+ if (resolution === null) return {
71981
+ ok: false,
71982
+ message: "unknown model reference"
71983
+ };
71984
+ if (resolution.localPathOverride !== void 0) return { ok: true };
71985
+ if (!deps.modelOps.isDownloaded(resolution.entry)) return {
71986
+ ok: false,
71987
+ message: `model ${resolution.entry.id} not installed on node ${deps.nodeId}`
71988
+ };
71989
+ return { ok: true };
71990
+ }
71991
+ async function ensureStartedInternal(runtime) {
71992
+ const argCheck = checkExtraArgs(runtime.extraArgs);
71993
+ if (!argCheck.ok) throw new Error(argCheck.message);
71994
+ const binaryPath = await deps.ensureBinary();
71995
+ const paths = await resolvePaths(runtime);
71996
+ const startCfg = {
71997
+ nodeId: deps.nodeId,
71998
+ modelId: paths.modelId,
71999
+ modelPath: paths.modelPath,
72000
+ ...paths.mmprojPath !== void 0 ? { mmprojPath: paths.mmprojPath } : {},
72001
+ contextSize: runtime.contextSize,
72002
+ gpuLayers: runtime.gpuLayers,
72003
+ ...runtime.threads !== void 0 ? { threads: runtime.threads } : {},
72004
+ parallel: runtime.parallel,
72005
+ ...runtime.batchSize !== void 0 ? { batchSize: runtime.batchSize } : {},
72006
+ ...runtime.ubatchSize !== void 0 ? { ubatchSize: runtime.ubatchSize } : {},
72007
+ flashAttention: runtime.flashAttention,
72008
+ mlock: runtime.mlock,
72009
+ noMmap: runtime.noMmap,
72010
+ ...runtime.cacheTypeK !== void 0 ? { cacheTypeK: runtime.cacheTypeK } : {},
72011
+ ...runtime.cacheTypeV !== void 0 ? { cacheTypeV: runtime.cacheTypeV } : {},
72012
+ extraArgs: runtime.extraArgs,
72013
+ idleStopMinutes: runtime.idleStopMinutes,
72014
+ binaryPath
72015
+ };
72016
+ return deps.supervisor.start(startCfg);
72017
+ }
72018
+ /**
72019
+ * sha256 every artifact whose digest the reference pinned — the main file
72020
+ * AND the extras.
72021
+ *
72022
+ * Verifying only the main file was the gap: a truncated or swapped mmproj is
72023
+ * exactly as fatal to llama-server as a bad weights file, and a resolved HF
72024
+ * reference carries a digest for every artifact (LFS `oid`) so there is no
72025
+ * reason to check one and trust the rest.
72026
+ *
72027
+ * This pass reads tens of GB and takes minutes; it is a REPORTED phase, not
72028
+ * a silent tail, because a progress bar frozen at 100% is the shape of a
72029
+ * hang.
72030
+ */
72031
+ async function verifyDigests(entry, model, startedAt) {
72032
+ if (model.kind !== "url") return;
72033
+ const targets = [];
72034
+ if (model.sha256 !== void 0) targets.push({
72035
+ filePath: deps.modelOps.pathFor(entry),
72036
+ sha256: model.sha256,
72037
+ name: basename(model.url)
72038
+ });
72039
+ for (const extra of model.extraFiles ?? []) {
72040
+ if (extra.sha256 === void 0) continue;
72041
+ targets.push({
72042
+ filePath: deps.modelOps.extraFilePath(entry, extra.filename),
72043
+ sha256: extra.sha256,
72044
+ name: extra.filename
72045
+ });
72046
+ }
72047
+ if (targets.length === 0) return;
72048
+ const sha256 = deps.fileSha256 ?? fileSha256;
72049
+ for (const [index, target] of targets.entries()) {
72050
+ download = {
72051
+ phase: "verifying",
72052
+ file: target.name,
72053
+ fileIndex: index + 1,
72054
+ fileCount: targets.length,
72055
+ downloadedBytes: 0
72056
+ };
72057
+ deps.logger.info("llm model verifying digest", { meta: {
72058
+ nodeId: deps.nodeId,
72059
+ modelId: entry.id,
72060
+ file: target.name
72061
+ } });
72062
+ const digest = await sha256(target.filePath);
72063
+ if (digest !== target.sha256) {
72064
+ deps.logger.error("llm model digest mismatch; discarding the download", { meta: {
72065
+ nodeId: deps.nodeId,
72066
+ modelId: entry.id,
72067
+ file: target.name,
72068
+ expected: target.sha256,
72069
+ actual: digest,
72070
+ elapsedMs: Date.now() - startedAt
72071
+ } });
72072
+ await deps.modelOps.delete(entry);
72073
+ await node_fs_promises.rm(target.filePath, { force: true });
72074
+ throw new Error(`sha256 mismatch for ${target.name}: expected ${target.sha256}, got ${digest}`);
72075
+ }
72076
+ }
72077
+ }
72078
+ function status() {
72079
+ return {
72080
+ ...deps.supervisor.status(),
72081
+ nodeId: deps.nodeId,
72082
+ ...downloadProgress !== void 0 ? { downloadProgress } : {},
72083
+ ...download !== void 0 ? { download } : {}
72084
+ };
72085
+ }
72086
+ return {
72087
+ complete: async (input) => {
72088
+ const guard = installedGuard(input.runtime);
72089
+ if (!guard.ok) return {
72090
+ ok: false,
72091
+ code: "unavailable",
72092
+ message: guard.message
72093
+ };
72094
+ await ensureStartedInternal(input.runtime);
72095
+ const port = deps.supervisor.port;
72096
+ if (port === void 0) return {
72097
+ ok: false,
72098
+ code: "unavailable",
72099
+ message: "llama-server has no port"
72100
+ };
72101
+ const paths = await resolvePaths(input.runtime);
72102
+ const timeoutMs = input.timeoutMs ?? 12e4;
72103
+ const localProfile = {
72104
+ id: "managed-local",
72105
+ name: "managed-local",
72106
+ kind: "openai-compatible",
72107
+ addonId: "ai",
72108
+ enabled: true,
72109
+ model: paths.modelId,
72110
+ baseUrl: `http://127.0.0.1:${String(port)}/v1`,
72111
+ supportsVision: paths.mmprojPath !== void 0,
72112
+ timeoutMs,
72113
+ connectTimeoutMs: LlmTimeoutDefaults.connectMs,
72114
+ firstTokenTimeoutMs: LlmTimeoutDefaults.firstTokenMs,
72115
+ idleTimeoutMs: LlmTimeoutDefaults.idleMs,
72116
+ retry: {
72117
+ enabled: false,
72118
+ maxAttempts: 1
72119
+ },
72120
+ toolsEnabled: false
72121
+ };
72122
+ const result = await deps.client.generate({
72123
+ profile: localProfile,
72124
+ ...input.system !== void 0 ? { system: input.system } : {},
72125
+ prompt: input.prompt,
72126
+ ...input.images !== void 0 ? { images: input.images } : {},
72127
+ ...input.jsonSchema !== void 0 ? { jsonSchema: input.jsonSchema } : {},
72128
+ ...input.maxTokens !== void 0 ? { maxTokens: input.maxTokens } : {},
72129
+ ...input.temperature !== void 0 ? { temperature: input.temperature } : {},
72130
+ ...input.topP !== void 0 ? { topP: input.topP } : {},
72131
+ ...input.topK !== void 0 ? { topK: input.topK } : {},
72132
+ signal: new AbortController().signal
72133
+ }, timeoutMs);
72134
+ deps.supervisor.noteActivity();
72135
+ return result;
72136
+ },
72137
+ ensureStarted: async ({ runtime }) => {
72138
+ const guard = installedGuard(runtime);
72139
+ if (!guard.ok) return {
72140
+ nodeId: deps.nodeId,
72141
+ state: "stopped",
72142
+ lastError: guard.message,
72143
+ crashesInWindow: 0
72144
+ };
72145
+ return ensureStartedInternal(runtime);
72146
+ },
72147
+ stop: async () => {
72148
+ await deps.supervisor.stop();
72149
+ },
72150
+ status: async () => status(),
72151
+ /**
72152
+ * Install a model on THIS node.
72153
+ *
72154
+ * Loud on purpose. This is the longest-running operation the addon has —
72155
+ * tens of minutes for a 23 GB vision model — and until now it emitted not
72156
+ * one log line, so an install that stalled on a gated URL or a full disk
72157
+ * was indistinguishable from one that was simply slow. Every phase
72158
+ * transition is a line, and every line carries the node.
72159
+ */
72160
+ installModel: async ({ model }) => {
72161
+ const resolution = entryForRef(model);
72162
+ if (resolution === null) throw new Error("unknown model reference");
72163
+ if (resolution.localPathOverride !== void 0) {
72164
+ deps.logger.info("llm model is pre-provisioned; nothing to download", { meta: {
72165
+ nodeId: deps.nodeId,
72166
+ path: resolution.localPathOverride
72167
+ } });
72168
+ return;
72169
+ }
72170
+ const { entry } = resolution;
72171
+ const declaredBytes = model.kind === "url" ? model.sizeBytes : void 0;
72172
+ const startedAt = Date.now();
72173
+ deps.logger.info("llm model install started", { meta: {
72174
+ nodeId: deps.nodeId,
72175
+ modelId: entry.id,
72176
+ url: entry.formats.gguf?.url,
72177
+ extraFiles: (entry.extraFiles ?? []).map((f) => f.filename),
72178
+ ...declaredBytes !== void 0 ? {
72179
+ declaredBytes,
72180
+ declaredSize: gb(declaredBytes)
72181
+ } : {}
72182
+ } });
72183
+ downloadProgress = 0;
72184
+ download = {
72185
+ phase: "downloading",
72186
+ file: "",
72187
+ fileIndex: 0,
72188
+ fileCount: 0,
72189
+ downloadedBytes: 0
72190
+ };
72191
+ let lastLoggedDecile = -1;
72192
+ try {
72193
+ await deps.modelOps.ensure(entry, (progress) => {
72194
+ const fraction = progress.totalBytes !== void 0 && progress.totalBytes > 0 ? Math.min(1, progress.downloadedBytes / progress.totalBytes) : void 0;
72195
+ downloadProgress = fraction;
72196
+ download = {
72197
+ phase: "downloading",
72198
+ file: progress.file,
72199
+ fileIndex: progress.fileIndex,
72200
+ fileCount: progress.fileCount,
72201
+ downloadedBytes: progress.downloadedBytes,
72202
+ ...progress.totalBytes !== void 0 ? { totalBytes: progress.totalBytes } : {}
72203
+ };
72204
+ const decile = fraction === void 0 ? -1 : Math.floor(fraction * 10);
72205
+ if (decile > lastLoggedDecile) {
72206
+ lastLoggedDecile = decile;
72207
+ deps.logger.info("llm model download progress", { meta: {
72208
+ nodeId: deps.nodeId,
72209
+ modelId: entry.id,
72210
+ file: progress.file,
72211
+ fileIndex: progress.fileIndex,
72212
+ fileCount: progress.fileCount,
72213
+ downloadedBytes: progress.downloadedBytes,
72214
+ downloaded: gb(progress.downloadedBytes),
72215
+ ...progress.totalBytes !== void 0 ? { total: gb(progress.totalBytes) } : {}
72216
+ } });
72217
+ }
72218
+ });
72219
+ await verifyDigests(entry, model, startedAt);
72220
+ deps.logger.info("llm model install complete", { meta: {
72221
+ nodeId: deps.nodeId,
72222
+ modelId: entry.id,
72223
+ elapsedMs: Date.now() - startedAt
72224
+ } });
72225
+ } catch (err) {
72226
+ deps.logger.error("llm model install failed", { meta: {
72227
+ nodeId: deps.nodeId,
72228
+ modelId: entry.id,
72229
+ elapsedMs: Date.now() - startedAt,
72230
+ error: err instanceof Error ? err.message : String(err)
72231
+ } });
72232
+ throw err;
72233
+ } finally {
72234
+ downloadProgress = void 0;
72235
+ download = void 0;
72236
+ }
72237
+ },
72238
+ deleteModel: async ({ file }) => {
72239
+ const loaded = deps.supervisor.status().modelPath;
72240
+ if (loaded !== void 0 && basename(loaded) === file) throw new Error(`cannot delete ${file}: loaded by the running runtime`);
72241
+ await node_fs_promises.rm(node_path.join(deps.modelsDir, file), { force: true });
72242
+ },
72243
+ listLocalModels: async () => {
72244
+ return (await listGgufFiles(deps.modelsDir)).map((f) => {
72245
+ const catalogId = catalogIdForFile(f.file);
72246
+ return {
72247
+ file: f.file,
72248
+ sizeBytes: f.sizeBytes,
72249
+ path: node_path.join(deps.modelsDir, f.file),
72250
+ ...catalogId !== void 0 ? { catalogId } : {}
72251
+ };
72252
+ });
72253
+ },
72254
+ getDiskUsage: async () => {
72255
+ const modelsBytes = (await listGgufFiles(deps.modelsDir)).reduce((sum, f) => sum + f.sizeBytes, 0);
72256
+ return {
72257
+ nodeId: deps.nodeId,
72258
+ modelsBytes
72259
+ };
72260
+ }
72261
+ };
72262
+ }
72263
+ async function listGgufFiles(dir) {
72264
+ let names;
72265
+ try {
72266
+ names = await node_fs_promises.readdir(dir);
72267
+ } catch {
72268
+ return [];
72269
+ }
72270
+ const out = [];
72271
+ for (const name of names) {
72272
+ if (!name.endsWith(".gguf")) continue;
72273
+ try {
72274
+ const stat = await node_fs_promises.stat(node_path.join(dir, name));
72275
+ out.push({
72276
+ file: name,
72277
+ sizeBytes: stat.size
72278
+ });
72279
+ } catch {}
72280
+ }
72281
+ return out;
72282
+ }
72283
+ //#endregion
72284
+ //#region src/runtime-client.ts
72285
+ /**
72286
+ * `RuntimeClient` over the cap plane — every verb pins the target node with
72287
+ * `nodePin(nodeId)` (transport-level, never a hand-rolled routing field). The
72288
+ * CapRouteResolver classifies the pin into hub-local-uds / remote-moleculer /
72289
+ * agent-child-forward transparently (spec §4.1; the model-studio cross-node
72290
+ * convert precedent). Node enumeration is the `nodes.topology` roster filtered
72291
+ * to nodes advertising the `llm-runtime` cap — never a shadow registry.
72292
+ */
72293
+ var LLM_RUNTIME_CAP = "llm-runtime";
72294
+ function createRuntimeClient(api) {
72295
+ return {
72296
+ complete: (nodeId, input) => api.llmRuntime.complete.mutate(input, nodePin(nodeId)),
72297
+ ensureStarted: (nodeId, runtime) => api.llmRuntime.ensureStarted.mutate({ runtime }, nodePin(nodeId)),
72298
+ stopRuntime: (nodeId) => api.llmRuntime.stop.mutate({}, nodePin(nodeId)),
72299
+ status: (nodeId) => api.llmRuntime.status.query({}, nodePin(nodeId)),
72300
+ installModel: (nodeId, model) => api.llmRuntime.installModel.mutate({ model }, nodePin(nodeId)),
72301
+ deleteModel: (nodeId, file) => api.llmRuntime.deleteModel.mutate({ file }, nodePin(nodeId)),
72302
+ listLocalModels: (nodeId) => api.llmRuntime.listLocalModels.query({}, nodePin(nodeId)),
72303
+ getDiskUsage: (nodeId) => api.llmRuntime.getDiskUsage.query({}, nodePin(nodeId)),
72304
+ listRuntimeNodeIds: async () => {
72305
+ const topology = await api.nodes.topology.query();
72306
+ const ids = /* @__PURE__ */ new Set();
72307
+ for (const node of topology) if (node.addons.some((a) => a.capabilities.includes(LLM_RUNTIME_CAP))) ids.add(node.id);
72308
+ return [...ids];
72309
+ }
72310
+ };
72311
+ }
72312
+ //#endregion
72313
+ //#region src/assembly.ts
72314
+ /**
72315
+ * Registration assembly (the hub/agent split, spec §1). Every node running
72316
+ * addon-ai registers `llm-runtime`; ONLY the hub also registers the consumer
72317
+ * `llm` surface (profiles/usage need outbound internet + API keys).
72318
+ * Extracted from the addon class so the split + seeding is unit-testable
72319
+ * without a full AddonContext.
72320
+ */
72321
+ async function assembleAi(deps) {
72322
+ const client = deps.client ?? createLlmClient();
72323
+ const runtimeProvider = createLlmRuntimeProvider({
72324
+ nodeId: deps.nodeId,
72325
+ modelsDir: deps.modelsDir,
72326
+ ensureBinary: deps.ensureBinary,
72327
+ supervisor: deps.supervisor,
72328
+ modelOps: createDefaultModelOps(deps.modelsDir),
72329
+ client,
72330
+ logger: deps.logger.child("llm-runtime")
72331
+ });
72332
+ const registrations = [{
72333
+ capability: llmRuntimeCapability,
72334
+ provider: runtimeProvider
72335
+ }];
72336
+ if (!deps.isHub) return {
72337
+ registrations,
72338
+ runtimeProvider
72339
+ };
72340
+ const { UsageStore } = await Promise.resolve().then(() => require("./usage-store-Q34FDPSq.js")).then((n) => n.usage_store_exports);
72341
+ const store = new ProfileStore(deps.settingsPort);
72342
+ const defaults = new DefaultsStore(deps.settingsPort);
72343
+ const usage = new UsageStore(deps.settingsPort, Date.now, deps.logger.child("llm-usage"));
72344
+ await store.init();
72345
+ await defaults.init();
72346
+ await usage.init();
72347
+ await store.ensureSeeded();
72348
+ const llmProvider = createLlmProvider({
72349
+ store,
72350
+ defaults,
72351
+ usage,
72352
+ client,
72353
+ ...deps.runtimeApi !== void 0 ? { runtime: createRuntimeClient(deps.runtimeApi) } : {},
72354
+ ...deps.distributeModel !== void 0 ? { distributeModel: deps.distributeModel } : {},
72355
+ catalog: LLM_MODEL_CATALOG.map((m) => m.meta),
72356
+ hfToken: () => process.env["HF_TOKEN"] ?? process.env["HUGGING_FACE_HUB_TOKEN"],
72357
+ logger: deps.logger.child("llm")
72358
+ });
72359
+ registrations.push({
72360
+ capability: llmCapability,
72361
+ provider: llmProvider
72362
+ });
72363
+ return {
72364
+ registrations,
72365
+ runtimeProvider,
72366
+ llmProvider,
72367
+ store,
72368
+ usage,
72369
+ prune: (retentionDays) => usage.prune(retentionDays)
72370
+ };
72371
+ }
72372
+ //#endregion
71335
72373
  //#region src/settings-store-port.ts
71336
72374
  function createApiSettingsStorePort(api) {
71337
72375
  return {
@@ -71436,7 +72474,9 @@ var TestChatImageRefSchema = discriminatedUnion("kind", [object({
71436
72474
  deviceId: number$1().int().positive()
71437
72475
  }), object({
71438
72476
  kind: literal("track"),
71439
- trackId: string().min(1)
72477
+ trackId: string().min(1),
72478
+ /** Owning device — `getTrackMedia` requires it as the read's scope. */
72479
+ deviceId: number$1().int().positive()
71440
72480
  })]);
71441
72481
  /**
71442
72482
  * `.strict()`, and it is load-bearing.
@@ -71662,7 +72702,7 @@ async function resolveImage(deps, ref) {
71662
72702
  }
71663
72703
  let rows;
71664
72704
  try {
71665
- rows = await deps.getTrackMedia(ref.trackId, TRACK_MEDIA_PREFERENCE);
72705
+ rows = await deps.getTrackMedia(ref.trackId, TRACK_MEDIA_PREFERENCE, ref.deviceId);
71666
72706
  } catch (cause) {
71667
72707
  const message = cause instanceof Error ? cause.message : String(cause);
71668
72708
  deps.logger.warn("ai test chat: track media read failed — turn dropped", { meta: {
@@ -72257,9 +73297,10 @@ var AiAddon = class extends BaseAddon {
72257
73297
  });
72258
73298
  },
72259
73299
  getSnapshot: (deviceId) => api.snapshot.getSnapshot.query({ deviceId }),
72260
- getTrackMedia: (trackId, kinds) => api.pipelineAnalytics.getTrackMedia.query({
73300
+ getTrackMedia: (trackId, kinds, deviceId) => api.pipelineAnalytics.getTrackMedia.query({
72261
73301
  trackId,
72262
- kinds: [...kinds]
73302
+ kinds: [...kinds],
73303
+ deviceId
72263
73304
  }),
72264
73305
  recordUsage: (row) => usage.record(row),
72265
73306
  logger,