trusty-common 0.70.2

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! The one way anything outside trusty-search calls the running daemon (#6285,
//! #7237).
//!
//! Why: this client lived in `trusty_mpm::daemon::search_rpc`, where only
//! `tm doctor` and the session manager could reach it. `search_index`'s
//! find-or-create sits BELOW trusty-mpm in the dependency graph, so it could
//! not use it and went on resolving `~/.trusty-search/http_addr` and POSTing
//! `http://127.0.0.1:7878/indexes` — a listener ADR-0032 retired, which is why
//! every fresh project logged `error sending request for url` and then
//! `NotConfirmed` at session launch (#7237). Moving the client down to
//! trusty-common is what makes one implementation serve both: trusty-mpm's
//! module is now a re-export of this one.
//!
//! What: [`crate::search_rpc::search_socket`] derives the path both ends
//! compute, [`crate::search_rpc::call_at`] writes one frame and reads one back,
//! and [`crate::search_rpc::call_blocking`] is that call from a synchronous
//! caller — it runs on a dedicated OS thread with its own current-thread
//! runtime, because `search_index`'s entry points are called from inside a
//! tokio runtime as often as not. [`crate::search_rpc::SearchRpcError`] carries the
//! daemon's own code, so a caller can tell "no such index" — the whole point of
//! the pinned-index probe (#5045) — and "that root already belongs to another
//! index" (#6864) from a transport failure.
//!
//! **The method names are literals here, and deliberately so.** trusty-common
//! has no Cargo edge on trusty-search (the edge runs the other way), so the
//! names cannot be imported; they are pinned by
//! `trusty_search::service::socket::METHODS`, which the daemon's own
//! `rpc_router_registers_every_documented_method` compares its router against.
//! A name that drifted answers `method_not_found`, which every caller here
//! reports as an unhealthy daemon.
//!
//! Test: `search_socket_honours_the_env_override`,
//! `search_socket_follows_trusty_data_dir_like_the_daemon`,
//! `search_socket_under_treats_empty_as_unset_and_refuses_relative`,
//! `call_at_reports_a_dead_socket_rather_than_hanging`,
//! `call_blocking_reports_a_dead_socket_rather_than_hanging`,
//! `call_blocking_round_trips_against_a_listening_daemon`,
//! `call_blocking_carries_the_daemons_own_error_code`,
//! `call_blocking_reports_a_panicking_handler_rather_than_hanging`.

use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, anyhow};
use serde_json::Value;

use crate::uds::send_framed_request;
use crate::uds::server::RpcResponse;

#[cfg(test)]
#[path = "search_rpc_tests.rs"]
mod tests;

/// Environment variable that pins the daemon's socket path explicitly.
///
/// Why: it replaces `TRUSTY_SEARCH_ADDR`, which named a listener there no
/// longer is one. The affordance it provided is still wanted — a test rig
/// points a probe at a daemon it started on a temp path — and the alternative,
/// `TRUSTY_DATA_DIR_OVERRIDE`, is process-global and would redirect every other
/// trusty-* client in the same process along with this one. Same shape as
/// [`crate::memory_rpc::TRUSTY_MEMORY_SOCKET_ENV`] and trusty-audit's
/// `TRUSTY_ANALYZE_SOCKET`.
pub const TRUSTY_SEARCH_SOCKET_ENV: &str = "TRUSTY_SEARCH_SOCKET";

/// The environment variable that isolates one trusty-search instance.
///
/// The daemon's `--data-dir` stamps it, and the daemon's lockfile, registry and
/// socket key off it; [`search_socket`] reads it so a client follows (#9214).
pub const TRUSTY_SEARCH_DATA_DIR_ENV: &str = "TRUSTY_DATA_DIR";

/// The app name trusty-search derives its socket path under.
///
/// Matches the daemon's own `daemon_socket_path("trusty-search")` call
/// (`trusty_search::service::socket::socket_path`), which is why caller and
/// daemon compute the same path with nothing published between them.
const SEARCH_APP_NAME: &str = "trusty-search";

/// Liveness, index count and the daemon's version.
pub const METHOD_HEALTH: &str = "search.health";

/// Every registered index — the `details` flag widens each entry.
pub const METHOD_INDEXES_LIST: &str = "search.indexes.list";

/// One index's stages, capabilities and footprint. Answers [`CODE_NOT_FOUND`]
/// for an id the daemon does not hold.
pub const METHOD_INDEX_STATUS: &str = "search.index.status";

/// `POST /indexes`' socket twin — register a new index, or re-join one that
/// already exists (#7237).
///
/// Params are a BARE `CreateIndexRequest`: `{id, root_path,
/// allow_sensitive_path, skip_vector}`, byte-for-byte the JSON the HTTP route
/// took. It is a registry-level write, so it does NOT take the
/// `{index_id, body}` envelope the index-scoped writes use — sending one would
/// be refused as `invalid_params`.
pub const METHOD_INDEX_CREATE: &str = "search.index.create";

/// `POST /indexes/{id}/reindex`' socket twin — queue a full reindex. The
/// trigger only; the walk itself is the daemon's.
///
/// Params are `{index_id}`, with an optional `body` the callers here never
/// send.
pub const METHOD_INDEX_REINDEX: &str = "search.index.reindex";

/// Deregister one index, and — with `delete_data: true` — destroy its on-disk
/// data directory.
///
/// The only destructive method named here. In trusty-mpm it is reachable
/// exclusively through `session_manager::index_delete_guard::DestructiveIndexDelete`,
/// which holds that crate's one copy of the `delete_data` opt-in (#4743).
pub const METHOD_INDEX_DELETE: &str = "search.index.delete";

/// One path's revision evidence (#10738, SPEC-OKF-01 §5.6 D1).
///
/// Params use the index-scoped write envelope, `{index_id, body: {path}}`. The
/// reply decodes as [`IndexFileStatus`]. An unknown index answers
/// [`CODE_NOT_FOUND`]; an unknown path answers `present: false`.
pub const METHOD_INDEX_FILE_STATUS: &str = "search.index.file.status";

/// An index's identity, as `search.index.status`, the `search.index.file.put`
/// reply and [`METHOD_INDEX_FILE_STATUS`] report it (#10738).
///
/// `instance_id` changes when the index ID is deleted and re-created;
/// `generation` rises when the stored contents may have lost chunks without a
/// per-path remove (a reset, a force reindex, a migration fault, a corpus that
/// failed to open). Two equal values mean the same stored contents lineage.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct IndexIdentity {
    /// Opaque, at least 128 random bits.
    pub instance_id: String,
    /// Starts at 1 for each `instance_id`.
    pub generation: u64,
}

/// The reply of [`METHOD_INDEX_FILE_STATUS`] (#10738).
///
/// `identity` is `None` when the daemon could not read its identity; a caller
/// must then treat the index as unreadable, never as matching.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct IndexFileStatus {
    /// The path as the caller sent it.
    pub path: String,
    /// True when the index holds chunks for the path.
    pub present: bool,
    /// Lowercase hex SHA-256 of the content the chunks came from; `None`
    /// when absent or unknown.
    pub content_sha256: Option<String>,
    /// How many chunks the index holds for the path.
    pub chunk_count: u64,
    /// The index identity at read time.
    pub identity: Option<IndexIdentity>,
}

/// Find or create the one index of a trusty-mpm project (#10531).
///
/// Params are `{project_key, name, root, profile?}`, a bare object like
/// [`METHOD_INDEX_CREATE`]. Idempotent: a repeat call for the same root
/// returns the same `index_id` and queues no reindex. A root that contains,
/// or sits inside, another index's root answers [`CODE_CONFLICT`] with
/// `data.overlapping_index_id`.
pub const METHOD_PROJECT_ENSURE: &str = "search.project.ensure";

/// The daemon's code for "the thing you asked about does not exist" (HTTP 404).
///
/// A second copy of `trusty_search::service::rpc::error::CODE_NOT_FOUND`, and
/// of `trusty_mpm::daemon::error::CODE_NOT_FOUND`, because trusty-common is
/// below both in the dependency graph and cannot import either.
/// `search_rpc_codes_match_the_daemon_error_table` in trusty-mpm is what keeps
/// this equal to the copy its own daemon serves.
pub const CODE_NOT_FOUND: i64 = -32004;

/// The daemon's code for "this write collides with a registration that already
/// exists" (HTTP 409) — see [`CODE_NOT_FOUND`] for why the number is duplicated.
///
/// The recoverable refusal #6864 is about: the requested id names another tree,
/// or this tree already belongs to another id.
pub const CODE_CONFLICT: i64 = -32009;

/// The daemon answered, and what it answered was an error.
///
/// Why a typed error rather than a formatted string: the pinned-index probe has
/// to tell "the daemon has no such index" from "the call failed" — a 404 is a
/// definite, actionable verdict and a transport failure is an absence of
/// information (#5045) — and the find-or-create has to tell a recoverable `409`
/// from an outright refusal (#6864). Carrying the code in the error keeps
/// [`call_at`]'s `Result<Value>` signature and makes only the callers that care
/// pay for it, via `anyhow::Error::downcast_ref`.
#[derive(Debug, thiserror::Error)]
#[error("{method} failed: {message} ({code})")]
pub struct SearchRpcError {
    /// The method that was called.
    pub method: String,
    /// The daemon's own JSON-RPC error code.
    pub code: i64,
    /// The daemon's own message.
    pub message: String,
    /// The JSON-RPC error's `data` member, when the daemon sent one (#6285).
    ///
    /// Why: an index-unavailable refusal carries `index_id`, `retryable`,
    /// `restore_via` and the rest of its HTTP body here; dropping it would
    /// leave a caller only the code.
    /// What: the daemon's `data` verbatim, `None` from a daemon that sent none.
    /// Test: `call_at_carries_the_daemons_error_data`.
    pub data: Option<Value>,
}

impl SearchRpcError {
    /// Did the daemon say the thing asked for does not exist?
    pub fn is_not_found(&self) -> bool {
        self.code == CODE_NOT_FOUND
    }

    /// Did the daemon refuse because the registry already holds this id, or
    /// this root, under other terms (#6864)?
    pub fn is_conflict(&self) -> bool {
        self.code == CODE_CONFLICT
    }
}

/// Resolve the socket the trusty-search daemon binds.
///
/// Why: a client must dial exactly the path the daemon binds, including a
/// daemon isolated with `TRUSTY_DATA_DIR` (#9214).
/// What: [`TRUSTY_SEARCH_SOCKET_ENV`] when set and non-blank; otherwise
/// [`search_socket_under`] over [`TRUSTY_SEARCH_DATA_DIR_ENV`].
///
/// # Errors
///
/// When the data directory cannot be resolved or created, or when
/// `TRUSTY_DATA_DIR` is relative — operator-fixable conditions, distinct from
/// "the daemon is not running", which this function cannot and does not report.
///
/// Test: `search_socket_honours_the_env_override`,
/// `search_socket_follows_trusty_data_dir_like_the_daemon`.
pub fn search_socket() -> Result<PathBuf> {
    if let Ok(raw) = std::env::var(TRUSTY_SEARCH_SOCKET_ENV) {
        let trimmed = raw.trim();
        if !trimmed.is_empty() {
            return Ok(PathBuf::from(trimmed));
        }
    }
    // #9214: honour TRUSTY_DATA_DIR as the daemon does, or an isolated daemon is unreachable.
    search_socket_under(std::env::var_os(TRUSTY_SEARCH_DATA_DIR_ENV).as_deref())
}

/// The socket trusty-search binds, with the instance override supplied rather
/// than read.
///
/// Why: the daemon (`trusty_search::service::socket::resolve_socket_path`) and
/// every client must apply one rule, or a client and a daemon sharing a custom
/// `TRUSTY_DATA_DIR` resolve two paths and never meet (#9214, #7801). The daemon
/// delegates here, so the rule exists once. Taking the value as a parameter
/// lets a test pin it without mutating process-global env.
/// What: `<override>/trusty-search.sock` when the override is present and
/// non-empty; otherwise the shared [`crate::daemon_socket_path`] derivation.
/// An empty value counts as unset, because joining onto `""` yields a relative
/// path that resolves against the caller's cwd.
///
/// # Errors
///
/// When the override is not absolute, when it cannot be created, or when the
/// shared data directory cannot be resolved.
///
/// Test: `search_socket_under_treats_empty_as_unset_and_refuses_relative`,
/// `search_socket_follows_trusty_data_dir_like_the_daemon`.
pub fn search_socket_under(data_dir_override: Option<&OsStr>) -> Result<PathBuf> {
    let Some(dir) = data_dir_override.filter(|d| !d.is_empty()) else {
        return crate::daemon_socket_path(SEARCH_APP_NAME);
    };
    let dir = PathBuf::from(dir);
    anyhow::ensure!(
        dir.is_absolute(),
        "{TRUSTY_SEARCH_DATA_DIR_ENV} must be an absolute path (got: {})",
        dir.display()
    );
    std::fs::create_dir_all(&dir).with_context(|| {
        format!(
            "create {TRUSTY_SEARCH_DATA_DIR_ENV} socket directory {}",
            dir.display()
        )
    })?;
    Ok(dir.join(format!("{SEARCH_APP_NAME}.sock")))
}

/// Call one method on the daemon at `socket` and return its `result`.
///
/// # Errors
///
/// When the socket cannot be dialled — which is what "the daemon is not
/// running" looks like — or when the daemon answers with a JSON-RPC error,
/// whose code and message are carried through in a [`SearchRpcError`] so the
/// caller reports the reason it was given rather than a generic failure.
///
/// Test: `call_at_reports_a_dead_socket_rather_than_hanging`.
pub async fn call_at(
    socket: &Path,
    method: &str,
    params: Value,
    timeout: Duration,
) -> Result<Value> {
    let request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": method,
        "params": params,
    });

    let response: RpcResponse = send_framed_request(socket, &request, timeout)
        .await
        .with_context(|| {
            format!(
                "call {method} on the trusty-search daemon at {}",
                socket.display()
            )
        })?;

    match (response.result, response.error) {
        (Some(result), _) => Ok(result),
        (None, Some(e)) => Err(anyhow::Error::new(SearchRpcError {
            method: method.to_string(),
            code: e.code,
            message: e.message,
            data: e.data,
        })),
        // The daemon's own contract is that exactly one of the two is present.
        (None, None) => Err(anyhow!(
            "{method} answered with neither a result nor an error"
        )),
    }
}

/// [`call_at`] from a synchronous caller, on a dedicated OS thread.
///
/// Why: `search_index`'s find-or-create is a blocking function called from
/// session launch and from tcode's task start, both of which are frequently
/// inside a tokio runtime — and `Runtime::block_on` inside a runtime worker
/// panics. Spawning the runtime on a freshly-created `std::thread` keeps it
/// entirely off the caller's async worker, which is the same arrangement the
/// `reqwest::blocking` client this replaced needed for the same reason.
/// What: builds a current-thread runtime on a joined thread and drives
/// [`call_at`] on it. A panicked worker is reported as an error rather than
/// re-raised, so a best-effort caller keeps its fail-closed shape.
///
/// A panic on the DAEMON's side takes the other route: the connection task dies
/// and this thread sees an unanswered call, which
/// `call_blocking_reports_a_panicking_handler_rather_than_hanging` pins. The
/// `join` arm below stays defensive — nothing this function drives panics on
/// its own thread — so it has no test of its own.
///
/// # Errors
///
/// Everything [`call_at`] reports, plus a failure to build the runtime and a
/// panicked worker thread.
///
/// Test: `call_blocking_round_trips_against_a_listening_daemon`,
/// `call_blocking_carries_the_daemons_own_error_code`,
/// `call_blocking_reports_a_dead_socket_rather_than_hanging`,
/// `call_blocking_reports_a_panicking_handler_rather_than_hanging`.
pub fn call_blocking(
    socket: &Path,
    method: &str,
    params: Value,
    timeout: Duration,
) -> Result<Value> {
    let socket = socket.to_path_buf();
    let owned_method = method.to_string();

    std::thread::spawn(move || {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .with_context(|| format!("build a runtime for {owned_method}"))?;
        runtime.block_on(call_at(&socket, &owned_method, params, timeout))
    })
    .join()
    .map_err(|_| anyhow!("the trusty-search {method} worker thread panicked"))?
}

/// The params of [`METHOD_PROJECT_ENSURE`] for one project (#10531).
///
/// Why: tm's register path and session launch both call it; one builder keeps
/// the two from spelling the wire shape twice.
/// What: `profile` is omitted from the object when `None`.
/// Test: `ensure_project_params_omit_an_absent_profile`.
#[must_use]
pub fn ensure_project_params(
    project_key: &str,
    name: &str,
    root: &Path,
    profile: Option<&str>,
) -> Value {
    let mut params = serde_json::json!({
        "project_key": project_key,
        "name": name,
        "root": root.to_string_lossy(),
    });
    if let Some(profile) = profile {
        params["profile"] = Value::String(profile.to_string());
    }
    params
}

/// [`call_blocking`] of [`METHOD_PROJECT_ENSURE`], answering the daemon's body.
///
/// Why: session launch is synchronous and often inside a runtime, like the
/// other find-or-create callers here.
/// Test: `ensure_project_blocking_sends_the_wire_shape`.
///
/// # Errors
///
/// Everything [`call_blocking`] reports; a refusal is a [`SearchRpcError`].
pub fn ensure_project_blocking(
    socket: &Path,
    project_key: &str,
    name: &str,
    root: &Path,
    profile: Option<&str>,
    timeout: Duration,
) -> Result<Value> {
    call_blocking(
        socket,
        METHOD_PROJECT_ENSURE,
        ensure_project_params(project_key, name, root, profile),
        timeout,
    )
}