roboticus-api 0.11.3

HTTP routes, WebSocket, auth, rate limiting, and dashboard for the Roboticus agent runtime
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
//! Truthfulness guards: ExecutionTruth, ModelIdentityTruth, CurrentEventsTruth,
//! LiteraryQuoteRetry, PersonalityIntegrity.

use crate::api::routes::agent::guard_registry::{Guard, GuardContext, GuardId, GuardVerdict};
use crate::api::routes::agent::intent_registry::Intent;

// ── 2. ExecutionTruthGuard ───────────────────────────────────────────────

pub(in crate::api::routes::agent) struct ExecutionTruthGuard;

impl Guard for ExecutionTruthGuard {
    fn id(&self) -> GuardId {
        GuardId::ExecutionTruth
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::Execution)
            || ctx.has_intent(Intent::TaskManagement)
            || ctx.has_intent(Intent::Delegation)
            || ctx.has_intent(Intent::Cron)
            || ctx.has_intent(Intent::FileDistribution)
            || ctx.has_intent(Intent::FolderScan)
            || ctx.has_intent(Intent::WalletAddressScan)
            || ctx.has_intent(Intent::ImageCountScan)
            || ctx.has_intent(Intent::MarkdownCountScan)
            || ctx.has_intent(Intent::ObsidianInsights)
            || ctx.has_intent(Intent::EmailTriage)
    }

    fn evaluate(&self, content: &str, ctx: &GuardContext) -> GuardVerdict {
        // Delegation claim verification — only fire when the semantic classifier
        // confirms the response is making a FALSE_COMPLETION claim (score > 0.7).
        // Recommendations, opinions, and analysis about delegation are NOT false
        // claims and must pass through.
        if ctx.has_intent(Intent::Delegation)
            && !ctx.tool_results.iter().any(|(name, output)| {
                let is_delegate_tool = super::behavioral::DELEGATION_TOOLS.contains(name.as_str());
                let succeeded = !output.to_ascii_lowercase().starts_with("error:");
                is_delegate_tool && succeeded
            })
        {
            let false_completion_score = ctx
                .semantic_guard_scores
                .get("FALSE_COMPLETION")
                .map(|(score, _)| *score)
                .unwrap_or(0.0);

            if false_completion_score > 0.7 {
                tracing::warn!(
                    false_completion_score,
                    "guard[ExecutionTruth]: blocked unverified delegation claim"
                );
                return GuardVerdict::Rewritten(format!(
                    "{}: by your command, execution truth is strict. I did not execute a delegated \
                     subagent task for that request. I can only claim delegated results when a \
                     subagent tool call actually runs.",
                    ctx.agent_name
                ));
            }
        }

        // Cron claim verification — uses CRON_TOOLS constant set and checks
        // for false completion claims via sentence-level heuristic.
        if ctx.has_intent(Intent::Cron) {
            let cron_tool_ran = ctx.tool_results.iter().any(|(name, output)| {
                super::behavioral::CRON_TOOLS.contains(name.as_str())
                    || name.to_ascii_lowercase().contains("cron")
                        && !output.to_ascii_lowercase().starts_with("error:")
            });
            if !cron_tool_ran {
                // Detect false completion claims via semantic classification.
                // The FALSE_COMPLETION bank captures when the model claims to
                // have completed an action that no tool execution supports.
                let false_completion_score = ctx
                    .semantic_guard_scores
                    .get("FALSE_COMPLETION")
                    .map(|(score, _trust)| *score)
                    .unwrap_or(0.0);
                if false_completion_score > 0.7 {
                    tracing::warn!(
                        "guard[ExecutionTruth]: blocked unverified cron completion claim"
                    );
                    return GuardVerdict::RetryRequested {
                        reason: "You claimed a cron job was scheduled but no cron tool was \
                                 executed. Actually schedule the cron job using the available \
                                 scheduling tools, then report the result."
                            .into(),
                    };
                }
            }
        }

        // Runtime execution prompt verification.
        let runtime_execution = ctx.has_intent(Intent::Execution)
            || ctx.has_intent(Intent::FileDistribution)
            || ctx.has_intent(Intent::FolderScan)
            || ctx.has_intent(Intent::WalletAddressScan)
            || ctx.has_intent(Intent::ImageCountScan)
            || ctx.has_intent(Intent::ObsidianInsights)
            || ctx.has_intent(Intent::EmailTriage);

        if !runtime_execution {
            return GuardVerdict::Pass;
        }

        // FIX (was L314 bug)
        if !ctx.tool_results.is_empty() {
            if denies_local_runtime_capability(content, ctx) {
                tracing::warn!(
                    "guard[ExecutionTruth]: rewriting — capability denial despite tool execution"
                );
                let tool_summary: Vec<String> = ctx
                    .tool_results
                    .iter()
                    .map(|(name, output)| {
                        let truncated: String = output.chars().take(500).collect();
                        format!("Tool `{name}` returned:\n{truncated}")
                    })
                    .collect();
                return GuardVerdict::Rewritten(format!(
                    "Here are the results:\n\n{}",
                    tool_summary.join("\n\n")
                ));
            }
            return GuardVerdict::Pass;
        }

        // No tools ran — check for false execution claims.
        let lower = content.to_ascii_lowercase();
        if lower.contains("encountered an error reaching all llm providers") {
            return GuardVerdict::Pass;
        }

        if looks_like_unexecuted_claim(content)
            || lower.contains("tool successfully executed")
            || lower.contains("the `")
            || lower.starts_with('{')
        {
            tracing::warn!("guard[ExecutionTruth]: retrying — narrated tool use without execution");
            return GuardVerdict::RetryRequested {
                reason: "You described executing a tool or producing results without actually \
                         calling any tool. Do not narrate what a tool would do — actually invoke \
                         the tool (e.g., call `bash` with the appropriate command) and report \
                         the real output."
                    .into(),
            };
        }

        if denies_local_runtime_capability(content, ctx) {
            tracing::warn!("guard[ExecutionTruth]: retrying — false capability denial");
            return GuardVerdict::RetryRequested {
                reason: "You claimed you cannot access local files or execute commands, but you \
                         have tool access. Call the `bash` tool with the appropriate command to \
                         fulfill the user's request. Do not claim inability when tools are \
                         available."
                    .into(),
            };
        }

        GuardVerdict::Pass
    }
}

fn looks_like_unexecuted_claim(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    lower.contains("\"tool_call\"")
        || lower.contains("you can use the following")
        || lower.contains("you can run")
        || lower.contains("would use the following")
        || lower.contains("crontab entry")
        || lower.contains("unable to directly execute")
}

fn denies_local_runtime_capability(response: &str, ctx: &GuardContext<'_>) -> bool {
    if ctx
        .semantic_guard_scores
        .contains_key(roboticus_llm::intent_exemplars::CAT_CAPABILITY_DENIAL)
    {
        return true;
    }
    let lower = response.to_ascii_lowercase();
    (lower.contains("can't access your files")
        || lower.contains("cannot access your files")
        || lower.contains("can't access your local files")
        || lower.contains("cannot access your local files")
        || lower.contains("can't access your folders")
        || lower.contains("cannot access your folders")
        || lower.contains("can't browse your files")
        || lower.contains("cannot browse your files")
        || lower.contains("can't write directly to your local filesystem")
        || lower.contains("cannot write directly to your local filesystem")
        || lower.contains("i'm not able to directly access")
        || lower.contains("i am not able to directly access"))
        && (lower.contains("folder")
            || lower.contains("filesystem")
            || lower.contains("device")
            || lower.contains("local"))
}

// ── 5. ModelIdentityTruthGuard ───────────────────────────────────────────

pub(in crate::api::routes::agent) struct ModelIdentityTruthGuard;

impl Guard for ModelIdentityTruthGuard {
    fn id(&self) -> GuardId {
        GuardId::ModelIdentityTruth
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::ModelIdentity)
    }

    fn evaluate(&self, content: &str, ctx: &GuardContext) -> GuardVerdict {
        // If the response is short and primarily about identity, replace it
        // with the canonical identity statement.
        let is_primarily_identity = content.len() < 200 && content.lines().count() <= 3;

        if is_primarily_identity {
            tracing::warn!(
                model = ctx.resolved_model,
                "guard[ModelIdentityTruth]: emitting canonical model identity"
            );
            return GuardVerdict::Rewritten(format!(
                "{} reporting in. I am currently running on {}.",
                ctx.agent_name, ctx.resolved_model
            ));
        }

        // For longer responses that happen to mention a model name,
        // strip the model name reference but keep the substantive content.
        // The model name is in ctx.resolved_model (e.g. "moonshot/kimi-k2-turbo-preview").
        let model = ctx.resolved_model;
        let model_short = model.split('/').next_back().unwrap_or(model);
        let cleaned = content
            .replace(model, &format!("{}'s current model", ctx.agent_name))
            .replace(model_short, &format!("{}'s model", ctx.agent_name));
        if cleaned != content {
            tracing::info!(
                model = ctx.resolved_model,
                "guard[ModelIdentityTruth]: redacted model name from substantive response"
            );
            return GuardVerdict::Rewritten(cleaned);
        }

        GuardVerdict::Pass
    }
}

// ── 5b. CurrentEventsTruthGuard ──────────────────────────────────────────

pub(in crate::api::routes::agent) struct CurrentEventsTruthGuard;

impl Guard for CurrentEventsTruthGuard {
    fn id(&self) -> GuardId {
        GuardId::CurrentEventsTruth
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::CurrentEvents)
    }

    fn evaluate(&self, content: &str, _ctx: &GuardContext) -> GuardVerdict {
        if !looks_like_stale_knowledge_disclaimer(content) {
            return GuardVerdict::Pass;
        }
        tracing::warn!("guard[CurrentEventsTruth]: blocked stale-knowledge disclaimer");
        GuardVerdict::Rewritten(
            "Acknowledged. I cannot provide a current-events sitrep from stale memory. I will \
             run live retrieval/delegation and return an up-to-date report with the current date."
                .into(),
        )
    }
}

fn looks_like_stale_knowledge_disclaimer(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    lower.contains("as of my last update")
        || lower.contains("as of my last training")
        || lower.contains("i cannot provide real-time updates")
        || lower.contains("i can't provide real-time updates")
        || lower.contains("i cannot provide real-time geopolitical analysis")
        || lower.contains("i can't provide real-time geopolitical analysis")
        || lower.contains("do not include live news feeds")
        || lower.contains("does not include live news feeds")
        || lower.contains("no live news feeds")
        || lower.contains("specialized geopolitical subagents")
        || lower.contains("as of early 2023")
        || lower.contains("as of 2023")
}

// ── 6. LiteraryQuoteRetryGuard ───────────────────────────────────────────

pub(in crate::api::routes::agent) struct LiteraryQuoteRetryGuard;

impl Guard for LiteraryQuoteRetryGuard {
    fn id(&self) -> GuardId {
        GuardId::LiteraryQuoteRetry
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::LiteraryQuoteContext)
    }

    fn evaluate(&self, content: &str, _ctx: &GuardContext) -> GuardVerdict {
        if is_overbroad_sensitive_conflict_refusal(content) {
            tracing::warn!(
                "guard[LiteraryQuoteRetry]: overbroad refusal detected; requesting retry"
            );
            GuardVerdict::RetryRequested {
                reason: "overbroad sensitive-topic refusal for literary quote request".into(),
            }
        } else {
            GuardVerdict::Pass
        }
    }
}

fn is_overbroad_sensitive_conflict_refusal(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    const MARKERS: &[&str] = &[
        "i cannot provide quotes related to ongoing conflicts",
        "i can't provide quotes related to ongoing conflicts",
        "i cannot provide quotes",
        "sensitive geopolitical situations",
        "helpful and harmless",
        "avoiding engagement with potentially harmful or biased content",
        "if you have other requests that do not involve sensitive topics",
    ];
    MARKERS.iter().any(|m| lower.contains(m))
}

// ── 7. PersonalityIntegrityGuard ─────────────────────────────────────────

pub(in crate::api::routes::agent) struct PersonalityIntegrityGuard;

impl Guard for PersonalityIntegrityGuard {
    fn id(&self) -> GuardId {
        GuardId::PersonalityIntegrity
    }

    fn is_relevant(&self, _ctx: &GuardContext) -> bool {
        true
    }

    fn evaluate(&self, content: &str, ctx: &GuardContext) -> GuardVerdict {
        if !contains_foreign_identity_boilerplate(content) {
            return GuardVerdict::Pass;
        }
        tracing::warn!("guard[PersonalityIntegrity]: stripped foreign identity boilerplate");
        let cleaned = filter_foreign_identity_sentences(content);
        if !cleaned.is_empty() {
            return GuardVerdict::Rewritten(cleaned);
        }

        let lower_prompt = ctx.user_prompt.to_ascii_lowercase();
        let asks_release_summary = lower_prompt.contains("release")
            || lower_prompt.contains("changelog")
            || lower_prompt.contains("linkedin")
            || lower_prompt.contains("x.com")
            || lower_prompt.contains("twitter")
            || lower_prompt.contains("v0.9.5")
            || lower_prompt.contains("0.9.5");
        if asks_release_summary {
            return GuardVerdict::Rewritten(
                "I need concrete Roboticus 0.9.5 context to summarize accurately. I can pull \
                 from changelog/roadmap memory if available, or you can provide release notes \
                 and I'll format them for operator, LinkedIn, and X."
                    .into(),
            );
        }
        if ctx.has_intent(Intent::ModelIdentity) {
            return GuardVerdict::Rewritten(format!(
                "I am {} and I am currently running on {}.",
                ctx.agent_name, ctx.resolved_model
            ));
        }
        GuardVerdict::Rewritten(format!(
            "I'm {}. I'll continue in my configured voice and avoid foreign boilerplate.",
            ctx.agent_name
        ))
    }
}

const FOREIGN_IDENTITY_MARKERS: &[&str] = &[
    "as an ai developed by microsoft",
    "as an ai developed by",
    "as an ai language model",
    "as an ai text-based interface",
    "as an ai, i can't",
    "as an ai, i cannot",
    "as an ai i can't",
    "as an ai i cannot",
    "as a language model",
    "i am claude",
    "i'm claude",
    "i am chatgpt",
    "i'm chatgpt",
];

fn contains_foreign_identity_boilerplate(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    FOREIGN_IDENTITY_MARKERS.iter().any(|m| lower.contains(m))
}

fn filter_foreign_identity_sentences(response: &str) -> String {
    let mut out = String::new();
    for chunk in response.split_inclusive(['\n', '.', '!', '?']) {
        let lower = chunk.to_ascii_lowercase();
        if FOREIGN_IDENTITY_MARKERS.iter().any(|m| lower.contains(m)) {
            continue;
        }
        out.push_str(chunk);
    }
    out.trim().to_string()
}