rigspark-runtime 2.0.0

Hardware detection, backend adapters, lifecycle, memory and harness runtime for rigspark.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use crate::{
    http::{Request, Transport, read_json},
    identity::{ProcessIdentity, ProcessProbe},
    process_control::{
        ProcessControl, SpawnSpec, listener, minimal_env, same_process, stop_owned, wait_owned,
    },
    state::ServerState,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{path::PathBuf, time::Duration};
use tokio_util::sync::CancellationToken;

#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct BackendError(pub String);
impl From<String> for BackendError {
    fn from(value: String) -> Self {
        Self(value)
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BackendKind {
    #[serde(rename = "ollama")]
    Ollama,
    #[serde(rename = "llamacpp")]
    LlamaCpp,
}
impl BackendKind {
    pub fn name(self) -> &'static str {
        match self {
            Self::Ollama => "ollama",
            Self::LlamaCpp => "llamacpp",
        }
    }
    pub fn port(self) -> u16 {
        match self {
            Self::Ollama => 11434,
            Self::LlamaCpp => 8080,
        }
    }
}
#[derive(Clone)]
pub struct ServeRequest {
    pub model_id: String,
    pub endpoint: String,
    pub model_path: Option<PathBuf>,
    pub context: Option<u32>,
    pub cache: Option<crate::cache::CacheProfile>,
}
#[async_trait::async_trait]
pub trait BackendAdapter: Send + Sync {
    fn name(&self) -> &'static str;
    fn trusts(&self, identity: &ProcessIdentity) -> bool;
    async fn attach_only(
        &self,
        _request: &ServeRequest,
        _cancel: &CancellationToken,
    ) -> Result<ServerState, BackendError> {
        Err(BackendError("attach-only operation is unsupported".into()))
    }
    fn can_embed(&self) -> bool {
        matches!(self.name(), "ollama" | "lmstudio")
    }
    fn can_stream(&self) -> bool {
        self.name() == "ollama"
    }
    async fn chat(
        &self,
        _handle: &ServerState,
        _input: &crate::ollama_inference::ChatInput,
        _cancel: &CancellationToken,
    ) -> Result<crate::ollama_inference::ChatResult, BackendError> {
        Err(BackendError(
            "chat is not implemented for this adapter".into(),
        ))
    }
    async fn chat_stream(
        &self,
        handle: &ServerState,
        input: &crate::ollama_inference::ChatInput,
        cancel: &CancellationToken,
        on_delta: &mut (dyn for<'chunk> FnMut(&'chunk str) + Send),
    ) -> Result<crate::ollama_inference::ChatResult, BackendError> {
        let result = self.chat(handle, input, cancel).await?;
        on_delta(&result.content);
        Ok(result)
    }
    async fn embed(
        &self,
        _handle: &ServerState,
        _model: &str,
        _inputs: &[String],
        _cancel: &CancellationToken,
    ) -> Result<crate::ollama_inference::EmbedResult, BackendError> {
        Err(BackendError(
            "embeddings are unsupported by this adapter".into(),
        ))
    }
    async fn serve(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<ServerState, BackendError>;
    async fn ready(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError>;
    async fn stop(
        &self,
        handle: &ServerState,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError>;
    async fn ready_handle(
        &self,
        request: &ServeRequest,
        _handle: &ServerState,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        self.ready(request, cancel).await
    }
}
pub struct RuntimeAdapter<'runtime> {
    pub kind: BackendKind,
    pub binary: PathBuf,
    pub http: &'runtime dyn Transport,
    pub probe: &'runtime dyn ProcessProbe,
    pub control: &'runtime dyn ProcessControl,
    pub(crate) ollama_models: Option<PathBuf>,
}
pub fn model_id(value: &str) -> Result<(), BackendError> {
    if value.is_empty()
        || value.len() > 8192
        || !value.as_bytes()[0].is_ascii_alphanumeric()
        || !value.bytes().all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"._:/-".contains(&byte)
        })
        || value.split('/').any(|part| part == "..")
    {
        return Err(BackendError("invalid runtime model id".into()));
    }
    Ok(())
}
impl<'runtime> RuntimeAdapter<'runtime> {
    pub fn new(
        kind: BackendKind,
        binary: PathBuf,
        http: &'runtime dyn Transport,
        probe: &'runtime dyn ProcessProbe,
        control: &'runtime dyn ProcessControl,
    ) -> Self {
        Self {
            kind,
            binary,
            http,
            probe,
            control,
            ollama_models: None,
        }
    }
    pub fn with_ollama_models(mut self, models: PathBuf) -> Result<Self, BackendError> {
        if self.kind != BackendKind::Ollama {
            return Err(BackendError(
                "model store configuration requires Ollama".into(),
            ));
        }
        crate::command::OllamaCommandContext::new("http://127.0.0.1:11434", &models)?;
        self.ollama_models = Some(models);
        Ok(self)
    }
    async fn json(
        &self,
        endpoint: &str,
        path: &str,
        cancel: &CancellationToken,
    ) -> Result<Value, BackendError> {
        let request = Request::new(endpoint, path, None, None)
            .map_err(|error| BackendError(error.to_string()))?;
        tokio::time::timeout(
            Duration::from_secs(5),
            read_json(self.http, request, cancel, 4 * 1024 * 1024),
        )
        .await
        .map_err(|_| BackendError("readiness request timed out".into()))?
        .map_err(|error| BackendError(error.to_string()))
    }
    fn validate(&self, request: &ServeRequest) -> Result<url::Url, BackendError> {
        model_id(&request.model_id)?;
        if !self.binary.is_absolute()
            || request
                .context
                .is_some_and(|value| !(1..=10000000).contains(&value))
        {
            return Err(BackendError("invalid runtime configuration".into()));
        }
        crate::state::loopback(&request.endpoint).map_err(|error| BackendError(error.to_string()))
    }
    async fn ready_once(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        self.validate(request)?;
        match self.kind {
            BackendKind::Ollama => {
                let version = self.json(&request.endpoint, "/api/version", cancel).await?;
                if !version
                    .get("version")
                    .and_then(Value::as_str)
                    .is_some_and(|version| !version.is_empty() && version.len() <= 100)
                {
                    return Err(BackendError("listener is not Ollama".into()));
                }
                crate::ollama_installed::parse_inventory(
                    self.json(&request.endpoint, "/api/tags", cancel).await?,
                )
                .map_err(|error| BackendError(error.to_string()))?;
            }
            BackendKind::LlamaCpp => {
                let health = self.json(&request.endpoint, "/health", cancel).await?;
                if health.get("status").and_then(Value::as_str) != Some("ok") {
                    return Err(BackendError("llama.cpp model is not ready".into()));
                }
                let props = self.json(&request.endpoint, "/props", cancel).await?;
                let path = props.get("model_path").and_then(Value::as_str);
                let alias = props.get("model_alias").and_then(Value::as_str);
                if request
                    .model_path
                    .as_ref()
                    .is_some_and(|expected| path != expected.to_str())
                    || alias != Some(request.model_id.as_str())
                {
                    return Err(BackendError(
                        "llama.cpp loaded artifact or alias differs".into(),
                    ));
                }
            }
        }
        Ok(())
    }
    pub async fn ready(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        let operation = async {
            let mut last = BackendError("runtime is not ready".into());
            for attempt in 0..20 {
                match self.ready_once(request, cancel).await {
                    Ok(()) => return Ok(()),
                    Err(error) => last = error,
                }
                tokio::time::sleep(Duration::from_millis((100u64 << attempt.min(4)).min(2000)))
                    .await;
            }
            Err(last)
        };
        tokio::select! {biased;_=cancel.cancelled()=>Err(BackendError("cancelled".into())),result=tokio::time::timeout(Duration::from_secs(30),operation)=>result.map_err(|_|BackendError("runtime readiness timed out".into()))?}
    }
    pub async fn serve(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<ServerState, BackendError> {
        let url = self.validate(request)?;
        if cancel.is_cancelled() {
            return Err(BackendError("cancelled".into()));
        }
        let occupied = tokio::select! {biased;_=cancel.cancelled()=>return Err(BackendError("cancelled".into())),result=self.control.occupied(&request.endpoint)=>result?};
        let executable = self
            .binary
            .to_str()
            .ok_or_else(|| BackendError("invalid executable path".into()))?;
        let (observed, owned) = if occupied {
            if crate::cache::effective(request.cache.as_ref()).is_some() {
                return Err(BackendError(format!(
                    "cache settings apply only to a {} runtime rigspark starts; stop the running server or omit the cache options",
                    self.kind.name()
                )));
            }
            let before = listener(self.probe, &request.endpoint, cancel).await?;
            if before.identity.executable != executable {
                return Err(BackendError(
                    "refusing untrusted listener executable".into(),
                ));
            }
            self.ready_once(request, cancel).await?;
            let after = listener(self.probe, &request.endpoint, cancel).await?;
            if !same_process(&before.identity, &after.identity) {
                return Err(BackendError("listener changed during attach".into()));
            }
            (after, false)
        } else {
            let host = url
                .host_str()
                .ok_or_else(|| BackendError("missing runtime host".into()))?
                .trim_matches(['[', ']']);
            let port = url
                .port_or_known_default()
                .ok_or_else(|| BackendError("missing port".into()))?;
            let mut env = minimal_env();
            let delta = crate::cache::launch_delta(request.cache.as_ref(), self.kind.name(), true)
                .map_err(|error| BackendError(error.to_string()))?;
            let mut args = match self.kind {
                BackendKind::Ollama => {
                    if let Some(models) = &self.ollama_models {
                        let context =
                            crate::command::OllamaCommandContext::new(&request.endpoint, models)?;
                        env.extend(context.environment().clone());
                    }
                    env.insert(
                        "OLLAMA_HOST".into(),
                        format!(
                            "{}:{port}",
                            if host.contains(':') {
                                format!("[{host}]")
                            } else {
                                host.into()
                            }
                        ),
                    );
                    vec!["serve".into()]
                }
                BackendKind::LlamaCpp => {
                    let path = request
                        .model_path
                        .as_ref()
                        .filter(|path| path.is_absolute() && path.is_file())
                        .ok_or_else(|| {
                            BackendError("verified absolute GGUF path required".into())
                        })?;
                    let mut args = vec![
                        "-m".into(),
                        path.to_string_lossy().into_owned(),
                        "--host".into(),
                        host.into(),
                        "--port".into(),
                        port.to_string(),
                        "--alias".into(),
                        request.model_id.clone(),
                    ];
                    if let Some(context) = request.context {
                        args.extend(["--ctx-size".into(), context.to_string()]);
                    }
                    args
                }
            };
            args.extend(delta.args);
            env.extend(delta.env);
            if cancel.is_cancelled() {
                return Err(BackendError("cancelled".into()));
            }
            let child = self
                .control
                .spawn(&SpawnSpec {
                    binary: self.binary.clone(),
                    args,
                    env,
                })
                .await?;
            let observed = wait_owned(
                child,
                &request.endpoint,
                executable,
                self.probe,
                cancel,
                || async { self.ready(request, cancel).await.map_err(|error| error.0) },
            )
            .await?;
            (observed, true)
        };
        let state = ServerState {
            backend: self.kind.name().into(),
            model_id: request.model_id.clone(),
            endpoint: request.endpoint.clone(),
            port: observed.port,
            owned_by_us: owned,
            pid: Some(observed.identity.pid),
            runtime_model_id: None,
            context: request.context,
            integrity: None,
            local_manifest_digest: None,
            model_path: None,
            process_executable: Some(observed.identity.executable),
            process_started_at: Some(observed.identity.started),
            auth_token: None,
            cache: if owned {
                crate::cache::effective(request.cache.as_ref())
            } else {
                None
            },
        };
        state
            .validate()
            .map_err(|error| BackendError(error.to_string()))?;
        Ok(state)
    }
    pub async fn stop(
        &self,
        handle: &ServerState,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        handle
            .validate()
            .map_err(|error| BackendError(error.to_string()))?;
        if handle.backend != self.kind.name() {
            return Err(BackendError("backend handle mismatch".into()));
        }
        if !handle.owned_by_us {
            return Ok(());
        }
        let expected = ProcessIdentity {
            pid: handle
                .pid
                .ok_or_else(|| BackendError("missing PID".into()))?,
            process: String::new(),
            executable: handle
                .process_executable
                .clone()
                .ok_or_else(|| BackendError("missing executable identity".into()))?,
            started: handle
                .process_started_at
                .clone()
                .ok_or_else(|| BackendError("missing start identity".into()))?,
        };
        if self.binary.to_str() != Some(&expected.executable) {
            return Err(BackendError("untrusted stop executable".into()));
        }
        stop_owned(
            &handle.endpoint,
            &expected,
            self.probe,
            self.control,
            cancel,
        )
        .await
        .map_err(BackendError)
    }
}
#[async_trait::async_trait]
impl BackendAdapter for RuntimeAdapter<'_> {
    async fn attach_only(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<ServerState, BackendError> {
        self.validate(request)?;
        if cancel.is_cancelled() {
            return Err(BackendError("cancelled".into()));
        }
        if !self.control.occupied(&request.endpoint).await? {
            return Err(BackendError(
                "existing runtime required; refusing to spawn".into(),
            ));
        }
        let before = listener(self.probe, &request.endpoint, cancel).await?;
        if !self.trusts(&before.identity) {
            return Err(BackendError("untrusted attached executable".into()));
        }
        self.ready_once(request, cancel).await?;
        let after = listener(self.probe, &request.endpoint, cancel).await?;
        if !same_process(&before.identity, &after.identity) {
            return Err(BackendError("listener changed during attachment".into()));
        }
        let state=crate::state::RuntimeState::parse(&serde_json::json!({"schemaVersion":2,"active":{"backend":self.name(),"modelId":request.model_id,"endpoint":request.endpoint,"port":after.port,"ownedByUs":false,"pid":after.identity.pid,"processExecutable":after.identity.executable,"processStartedAt":after.identity.started}}).to_string()).map_err(|error|BackendError(error.to_string()))?;
        state
            .active
            .ok_or_else(|| BackendError("missing attached state".into()))
    }
    async fn ready_handle(
        &self,
        request: &ServeRequest,
        handle: &ServerState,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        handle
            .validate()
            .map_err(|error| BackendError(error.to_string()))?;
        if handle.backend != self.name() || handle.endpoint != request.endpoint {
            return Err(BackendError("readiness handle mismatch".into()));
        }
        let before = listener(self.probe, &handle.endpoint, cancel).await?;
        crate::identity::capture(handle, &before, self.trusts(&before.identity))
            .map_err(|error| BackendError(error.to_string()))?;
        self.ready(request, cancel).await?;
        let models = self.json(&handle.endpoint, "/v1/models", cancel).await?;
        #[derive(Deserialize)]
        struct Model {
            id: String,
        }
        #[derive(Deserialize)]
        struct Models {
            data: Vec<Model>,
        }
        let models: Models = serde_json::from_value(models)
            .map_err(|_| BackendError("invalid OpenAI models response".into()))?;
        if models.data.len() > 10000
            || models
                .data
                .iter()
                .any(|model| model.id.is_empty() || model.id.len() > 8192)
        {
            return Err(BackendError("invalid OpenAI models".into()));
        }
        let after = listener(self.probe, &handle.endpoint, cancel).await?;
        if !same_process(&before.identity, &after.identity) {
            return Err(BackendError("readiness listener changed".into()));
        }
        Ok(())
    }
    fn name(&self) -> &'static str {
        self.kind.name()
    }
    fn trusts(&self, identity: &ProcessIdentity) -> bool {
        self.binary.to_str() == Some(identity.executable.as_str())
    }
    async fn chat(
        &self,
        handle: &ServerState,
        input: &crate::ollama_inference::ChatInput,
        cancel: &CancellationToken,
    ) -> Result<crate::ollama_inference::ChatResult, BackendError> {
        if self.kind == BackendKind::LlamaCpp {
            return crate::openai::OpenAiInference {
                http: self.http,
                probe: self.probe,
                adapter: self,
                token: None,
            }
            .chat(handle, input, cancel)
            .await;
        }
        let expected = expected_process(handle)?;
        let mut input = input.clone();
        input.model = handle.runtime_model_id.clone().unwrap_or(input.model);
        crate::ollama_inference::OllamaInference::new(
            self.http,
            self.probe,
            self.binary
                .to_str()
                .ok_or_else(|| BackendError("invalid executable".into()))?,
        )
        .chat(&handle.endpoint, &expected, &input, cancel)
        .await
        .map_err(|error| BackendError(error.to_string()))
    }
    async fn chat_stream(
        &self,
        handle: &ServerState,
        input: &crate::ollama_inference::ChatInput,
        cancel: &CancellationToken,
        on_delta: &mut (dyn for<'chunk> FnMut(&'chunk str) + Send),
    ) -> Result<crate::ollama_inference::ChatResult, BackendError> {
        if self.kind == BackendKind::LlamaCpp {
            let result = self.chat(handle, input, cancel).await?;
            on_delta(&result.content);
            return Ok(result);
        }
        let expected = expected_process(handle)?;
        let mut input = input.clone();
        input.model = handle.runtime_model_id.clone().unwrap_or(input.model);
        crate::ollama_inference::OllamaInference::new(
            self.http,
            self.probe,
            self.binary
                .to_str()
                .ok_or_else(|| BackendError("invalid executable".into()))?,
        )
        .chat_stream(&handle.endpoint, &expected, &input, cancel, on_delta)
        .await
        .map_err(|error| BackendError(error.to_string()))
    }
    async fn embed(
        &self,
        handle: &ServerState,
        model: &str,
        inputs: &[String],
        cancel: &CancellationToken,
    ) -> Result<crate::ollama_inference::EmbedResult, BackendError> {
        if self.kind != BackendKind::Ollama {
            return Err(BackendError("llama.cpp does not serve embeddings".into()));
        }
        let expected = expected_process(handle)?;
        crate::ollama_inference::OllamaInference::new(
            self.http,
            self.probe,
            self.binary
                .to_str()
                .ok_or_else(|| BackendError("invalid executable".into()))?,
        )
        .embed(&handle.endpoint, &expected, model, inputs, cancel)
        .await
        .map_err(|error| BackendError(error.to_string()))
    }
    async fn serve(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<ServerState, BackendError> {
        RuntimeAdapter::serve(self, request, cancel).await
    }
    async fn ready(
        &self,
        request: &ServeRequest,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        RuntimeAdapter::ready(self, request, cancel).await
    }
    async fn stop(
        &self,
        handle: &ServerState,
        cancel: &CancellationToken,
    ) -> Result<(), BackendError> {
        RuntimeAdapter::stop(self, handle, cancel).await
    }
}
fn expected_process(handle: &ServerState) -> Result<ProcessIdentity, BackendError> {
    handle
        .validate()
        .map_err(|error| BackendError(error.to_string()))?;
    if handle.backend != "ollama" {
        return Err(BackendError("Ollama handle required".into()));
    }
    Ok(ProcessIdentity {
        pid: handle
            .pid
            .ok_or_else(|| BackendError("expected PID required".into()))?,
        process: String::new(),
        executable: handle
            .process_executable
            .clone()
            .ok_or_else(|| BackendError("expected executable required".into()))?,
        started: handle
            .process_started_at
            .clone()
            .ok_or_else(|| BackendError("expected start identity required".into()))?,
    })
}