greentic-runner-host 1.2.0

Host runtime shim for Greentic runner: config, pack loading, activity handling
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
//! Knowledge retrieval from a Greentic-operated Chronicle index server.
//!
//! The runner-host edge of the `provider.knowledge.chronicle-index` binding:
//! instead of a corpus shipped inside the pack (`knowledge_corpus`) or a
//! customer's service reached through an extension tool (`knowledge_ext`), the
//! worker's documents live in one or more named indexes on a central server,
//! built by the designer's sync. Each turn embeds the query with the binding's
//! embedding provider, searches every bound index, and merges the hits.
//!
//! ## Why this wraps rather than replaces
//!
//! Same reason as `knowledge_ext`: `with_knowledge` overwrites the runtime's
//! backend, so [`attach`] takes whatever is mounted and delegates to it for
//! every binding that is not [`PROVIDER_ID`] — and for every `ingest`, which is
//! how a boot-ingested corpus keeps working underneath.
//!
//! ## Failure is always `Backend`
//!
//! Every failure surfaces as [`KnowledgeError::Backend`], which the turn loop
//! already turns into a warning, a failed retrieval trace step, and a turn run
//! without knowledge. Messages never carry a credential, a vector, or chunk
//! text. One index failing among several is only a warning: the others' hits
//! are still returned.

mod client;

use std::sync::{Arc, OnceLock};
use std::time::Duration;

use greentic_aw_runtime::AgentRuntime;
use greentic_aw_runtime::config::MemoryProviderRef;
use greentic_aw_runtime::knowledge::{
    IngestOutcome, Knowledge, KnowledgeChunk, KnowledgeError, KnowledgeQuery, KnowledgeResult,
    RetrievedChunk,
};
use greentic_aw_runtime::scoped_secrets::read_secret_for_unit;
use greentic_types::TenantCtx;
use url::{Host, Url};

use crate::secrets::DynSecretsManager;

/// The provider id a knowledge binding carries when retrieval goes to a
/// Chronicle index server. Written by the designer's composer; matched here.
pub const PROVIDER_ID: &str = "provider.knowledge.chronicle-index";

/// Identifies this backend within a wrapper chain (see
/// `knowledge_ext::corpus_backend`).
pub(crate) const BACKEND_ID: &str = "runner-host.knowledge_index";

/// Secret category both credentials are sealed under.
const SECRET_CATEGORY: &str = "knowledge";
/// Bearer for the index server.
const INDEX_KEY: &str = "chronicle_index_key";
/// Bearer for the embedding provider.
const EMBEDDING_KEY: &str = "embedding_key";

/// Team sent on the wire when the binding names none.
const DEFAULT_TEAM: &str = "general";
/// Base URL of the OpenAI-compatible embeddings API when the binding names none.
const DEFAULT_EMBEDDING_BASE_URL: &str = "https://api.openai.com/v1";
/// The only embedding provider this backend speaks.
const OPENAI: &str = "openai";

/// Chunks returned when the query names no limit.
const DEFAULT_LIMIT: usize = 5;

/// Per-HTTP-call timeout override, in milliseconds.
const TIMEOUT_ENV: &str = "GREENTIC_KNOWLEDGE_INDEX_TIMEOUT_MS";
const DEFAULT_TIMEOUT_MS: u64 = 5_000;

/// The one HTTP client every [`ChronicleIndexKnowledge`] shares, built on the
/// first bound search. The graph lane mounts a fresh instance on every agent
/// turn, so building a client (TLS roots and all) per instance would put that
/// cost on every turn, bound or not.
static SHARED_CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();

/// The shared client, or why it could not be built. Never falls back to
/// `reqwest::Client::new()`: that can panic, and it drops the timeout.
fn shared_client() -> Result<reqwest::Client, String> {
    SHARED_CLIENT
        .get_or_init(|| build_client(timeout_from_env()))
        .clone()
}

fn build_client(timeout: Duration) -> Result<reqwest::Client, String> {
    reqwest::Client::builder()
        .timeout(timeout)
        .build()
        .map_err(|e| e.to_string())
}

/// Mount Chronicle-index knowledge retrieval, wrapping whatever backend is
/// already mounted.
///
/// `secret_tenant` is the tenant the host's own secrets are scoped by; `None`
/// uses the `TenantCtx` each `search_bound` call is handed.
#[must_use]
pub fn attach(
    base: AgentRuntime,
    secrets: Option<DynSecretsManager>,
    secret_tenant: Option<String>,
) -> AgentRuntime {
    let inner = base.knowledge_backend();
    base.with_knowledge(Arc::new(ChronicleIndexKnowledge::new(
        inner,
        secrets,
        secret_tenant,
    )))
}

/// What the graph lane needs to mount this backend on each agent turn,
/// captured once where its handler is built.
///
/// The graph lane runs each turn under a synthetic `TenantCtx` (`graph`), so
/// the tenant the host's secrets are scoped by has to be captured here rather
/// than read from the turn.
#[derive(Clone, Default)]
pub struct IndexMount {
    pub secrets: Option<DynSecretsManager>,
    pub secret_tenant: Option<String>,
}

impl IndexMount {
    /// [`attach`] with the captured secrets and tenant.
    #[must_use]
    pub fn attach(&self, base: AgentRuntime) -> AgentRuntime {
        attach(base, self.secrets.clone(), self.secret_tenant.clone())
    }
}

/// Retrieval from the Chronicle indexes named in the agent's binding.
pub struct ChronicleIndexKnowledge {
    /// The backend mounted before this one. Every binding that is not
    /// [`PROVIDER_ID`] — and every `ingest` — goes here.
    inner: Option<Arc<dyn Knowledge>>,
    secrets: Option<DynSecretsManager>,
    secret_tenant: Option<String>,
    /// `None` uses the process-wide [`shared_client`]; tests inject their own.
    http: Option<reqwest::Client>,
}

impl ChronicleIndexKnowledge {
    /// Does no I/O and no TLS setup: the HTTP client is the process-wide one,
    /// built on the first bound search.
    #[must_use]
    pub fn new(
        inner: Option<Arc<dyn Knowledge>>,
        secrets: Option<DynSecretsManager>,
        secret_tenant: Option<String>,
    ) -> Self {
        Self {
            inner,
            secrets,
            secret_tenant,
            http: None,
        }
    }

    /// [`Self::new`] with a caller-supplied client instead of the shared one,
    /// so a test can set its own timeout without racing the process-wide
    /// client's first initialisation.
    #[cfg(test)]
    pub(crate) fn with_client(
        inner: Option<Arc<dyn Knowledge>>,
        secrets: Option<DynSecretsManager>,
        secret_tenant: Option<String>,
        http: reqwest::Client,
    ) -> Self {
        Self {
            inner,
            secrets,
            secret_tenant,
            http: Some(http),
        }
    }

    fn http(&self) -> KnowledgeResult<reqwest::Client> {
        match &self.http {
            Some(http) => Ok(http.clone()),
            None => shared_client().map_err(|reason| {
                KnowledgeError::Backend(format!(
                    "knowledge index HTTP client could not be built: {reason}"
                ))
            }),
        }
    }

    async fn delegate_search(
        &self,
        tenant: &TenantCtx,
        query: KnowledgeQuery,
        binding: Option<&MemoryProviderRef>,
    ) -> KnowledgeResult<Vec<RetrievedChunk>> {
        match self.inner.as_ref() {
            Some(inner) => inner.search_bound(tenant, query, binding).await,
            None => Err(KnowledgeError::NotConfigured),
        }
    }

    /// Read one credential; a miss names the URIs tried, never a value.
    ///
    /// Team scope, then the tenant-default `_` scope — deliberately NO unit
    /// scope. The deployed stores (greentic-deployer's dev-store writer,
    /// greentic-start's reader) canonicalise the secret NAME for every
    /// category but `mcp`/`a2a` to `[a-z0-9_]`, so a `<key>.unit-<id>` name
    /// could never be written or found there; that is also why the key names
    /// use `_` rather than `-`.
    async fn read_key(
        secrets: &DynSecretsManager,
        tenant: &str,
        team: Option<&str>,
        key: &str,
    ) -> KnowledgeResult<String> {
        let bytes =
            read_secret_for_unit(secrets.as_ref(), SECRET_CATEGORY, tenant, team, None, key)
                .await
                .map_err(|miss| {
                    KnowledgeError::Backend(format!("knowledge index credential: {miss}"))
                })?;
        let value = String::from_utf8(bytes)
            .map_err(|_| {
                KnowledgeError::Backend(format!(
                    "knowledge index credential `{key}` is not valid UTF-8"
                ))
            })?
            .trim()
            .to_string();
        if value.is_empty() {
            return Err(KnowledgeError::Backend(format!(
                "knowledge index credential `{key}` is empty"
            )));
        }
        Ok(value)
    }
}

#[async_trait::async_trait]
impl Knowledge for ChronicleIndexKnowledge {
    /// The index is built by the designer's sync, not by this runtime, so
    /// there is nothing to write here; a wrapped backend still ingests.
    async fn ingest(
        &self,
        tenant: &TenantCtx,
        chunks: Vec<KnowledgeChunk>,
    ) -> KnowledgeResult<IngestOutcome> {
        match self.inner.as_ref() {
            Some(inner) => inner.ingest(tenant, chunks).await,
            None => Ok(IngestOutcome::default()),
        }
    }

    /// Without a binding there is no index to search.
    async fn search(
        &self,
        tenant: &TenantCtx,
        query: KnowledgeQuery,
    ) -> KnowledgeResult<Vec<RetrievedChunk>> {
        self.delegate_search(tenant, query, None).await
    }

    async fn search_bound(
        &self,
        tenant: &TenantCtx,
        query: KnowledgeQuery,
        binding: Option<&MemoryProviderRef>,
    ) -> KnowledgeResult<Vec<RetrievedChunk>> {
        let Some(bound) = binding.filter(|b| b.provider == PROVIDER_ID) else {
            return self.delegate_search(tenant, query, binding).await;
        };
        let index = IndexBinding::parse(bound)?;

        let secrets = self.secrets.as_ref().ok_or_else(|| {
            KnowledgeError::Backend(
                "no secrets manager is available to read the knowledge index credentials"
                    .to_string(),
            )
        })?;
        let secret_tenant = self
            .secret_tenant
            .as_deref()
            .unwrap_or_else(|| tenant.tenant.as_str());
        let team = index.team.as_deref();
        let index_key = Self::read_key(secrets, secret_tenant, team, INDEX_KEY).await?;
        let embedding_key = Self::read_key(secrets, secret_tenant, team, EMBEDDING_KEY).await?;

        let http = self.http()?;
        let vector = client::embed(&http, &index, &embedding_key, &query.query).await?;
        let limit = query.limit.unwrap_or(DEFAULT_LIMIT).max(1);
        let hits = client::search_all(
            &http,
            &index,
            &index_key,
            &query.query,
            &client::encode_vector(&vector),
            limit,
        )
        .await?;
        Ok(client::merge(hits, limit))
    }

    fn wrapped_backend(&self) -> Option<Arc<dyn Knowledge>> {
        self.inner.clone()
    }

    fn backend_id(&self) -> &'static str {
        BACKEND_ID
    }
}

/// What a [`PROVIDER_ID`] binding's params say, validated.
struct IndexBinding {
    endpoint: Url,
    /// The DESIGNER tenant slug, sent to the index server.
    tenant: String,
    team: Option<String>,
    index_ids: Vec<String>,
    embedding_model: String,
    embedding_base_url: Url,
}

impl IndexBinding {
    fn parse(binding: &MemoryProviderRef) -> KnowledgeResult<Self> {
        let key = |name: &str| format!("{PROVIDER_ID}.{name}");
        let read = |name: &str| -> Option<String> {
            let value = binding.params.get(&key(name))?.as_str()?.trim();
            (!value.is_empty()).then(|| value.to_string())
        };
        let malformed = |name: &str| {
            KnowledgeError::Backend(format!(
                "knowledge binding names `{PROVIDER_ID}` but its `{}` param is missing or invalid",
                key(name)
            ))
        };

        let endpoint = read("endpoint")
            .as_deref()
            .and_then(credential_destination)
            .ok_or_else(|| malformed("endpoint"))?;
        let embedding_base_url = match read("embedding_base_url") {
            Some(raw) => credential_destination(&raw),
            None => credential_destination(DEFAULT_EMBEDDING_BASE_URL),
        }
        .ok_or_else(|| malformed("embedding_base_url"))?;
        let tenant = read("tenant")
            .filter(|t| is_scope_slug(t))
            .ok_or_else(|| malformed("tenant"))?;
        let team = match read("team") {
            Some(team) if is_scope_slug(&team) => Some(team),
            Some(_) => return Err(malformed("team")),
            None => None,
        };
        let index_ids = binding
            .params
            .get(&key("index_ids"))
            .and_then(serde_json::Value::as_array)
            .and_then(|items| {
                items
                    .iter()
                    .map(|item| {
                        let id = item.as_str()?.trim();
                        (!id.is_empty()).then(|| id.to_string())
                    })
                    .collect::<Option<Vec<String>>>()
            })
            .filter(|ids| !ids.is_empty())
            .ok_or_else(|| malformed("index_ids"))?;
        let provider = read("embedding_provider").ok_or_else(|| malformed("embedding_provider"))?;
        if provider != OPENAI {
            return Err(KnowledgeError::Backend(format!(
                "unsupported embedding provider `{provider}` for the knowledge index (only \
                 openai-compatible is supported)"
            )));
        }
        let embedding_model =
            read("embedding_model").ok_or_else(|| malformed("embedding_model"))?;

        Ok(Self {
            endpoint,
            tenant,
            team,
            index_ids,
            embedding_model,
            embedding_base_url,
        })
    }
}

/// A URL a bearer credential may be sent to: absolute, with a host, and
/// `https` — or plain `http` only to a loopback host. The binding is pack
/// content, so it chooses where the index and embedding keys go; refusing
/// cleartext off-loopback keeps a key from crossing a network unencrypted.
fn credential_destination(raw: &str) -> Option<Url> {
    let url = Url::parse(raw).ok()?;
    let loopback = match url.host()? {
        Host::Domain(domain) => domain.eq_ignore_ascii_case("localhost"),
        Host::Ipv4(ip) => ip == std::net::Ipv4Addr::LOCALHOST,
        Host::Ipv6(ip) => ip == std::net::Ipv6Addr::LOCALHOST,
    };
    match url.scheme() {
        "https" => Some(url),
        "http" if loopback => Some(url),
        _ => None,
    }
}

/// `[A-Za-z0-9_-]{1,64}` — what a tenant or team slug sent as a header may be.
fn is_scope_slug(value: &str) -> bool {
    (1..=64).contains(&value.len())
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// `GREENTIC_KNOWLEDGE_INDEX_TIMEOUT_MS` when it is a positive integer, else
/// the default.
fn timeout_from_env() -> Duration {
    let ms = std::env::var(TIMEOUT_ENV)
        .ok()
        .and_then(|raw| raw.trim().parse::<u64>().ok())
        .filter(|ms| *ms > 0)
        .unwrap_or(DEFAULT_TIMEOUT_MS);
    Duration::from_millis(ms)
}

#[cfg(test)]
mod tests;