kcode-agent-runtime 0.2.0

Provider-neutral subagent loops over kcode-intelligence-router
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Provider-neutral subagent loops over `kcode-intelligence-router`.

#![deny(missing_docs)]
#![forbid(unsafe_code)]

use std::{future::Future, pin::Pin, time::Duration};

use anyhow::{Context, ensure};
use kcode_codex_runtime_v2::{
    AgentEvent, AgentRequest, DynamicTool, DynamicToolCall, ReasoningEffort, ToolResult,
};
use kcode_intelligence_router::{AgentProvider, Intelligence, ResolvedAgentModel, UsageReceipt};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use uuid::Uuid;

const DEFAULT_ROUND_LIMIT: u64 = 100;
const PROTOCOL_TOKEN_RESERVE: u64 = 4_096;
const INLINE_TOOL_RESULT_CHARACTERS: usize = 1_000;

/// A boxed asynchronous host operation.
pub type HostFuture<'a, T> = Pin<Box<dyn Future<Output = anyhow::Result<T>> + Send + 'a>>;

/// One application tool call requested by a subagent.
#[derive(Clone, Debug, PartialEq)]
pub struct ToolCall {
    /// Exact application tool name.
    pub name: String,
    /// Tool arguments.
    pub arguments: Value,
}

/// One complete, typed audit fact selected by the subagent runtime.
#[derive(Clone, Debug, PartialEq)]
pub enum AuditEvent {
    /// Immutable starting context and resolved provider capacity.
    Started {
        /// Parent operation that causally owns the subagent.
        parent_operation_id: Uuid,
        /// Caller-selected model identifier.
        model: String,
        /// Exact provider model.
        provider_model: String,
        /// Resolved provider transport.
        provider: AgentProvider,
        /// Total provider context window.
        context_window_tokens: u64,
        /// Maximum permitted input.
        max_input_tokens: u64,
        /// Ordered immutable starting context.
        context: Vec<String>,
        /// Focused subagent task.
        task: String,
        /// Opaque application metadata supplied at launch.
        host: Value,
    },
    /// Exact input identity submitted for one provider round.
    InferenceSubmitted {
        /// Parent operation that causally owns the subagent.
        parent_operation_id: Uuid,
        /// One-based subagent round.
        round: u64,
        /// SHA-256 hash of the exact provider input.
        manifest_hash: String,
        /// Runtime input estimate including protocol reserve.
        estimated_input_tokens: u64,
    },
    /// Application tool invocation requested by the provider.
    ToolCall {
        /// Parent operation that causally owns the subagent.
        parent_operation_id: Uuid,
        /// Exact application tool name.
        name: String,
        /// Exact tool arguments.
        arguments: Value,
    },
    /// Complete application tool result retained for audit.
    ToolResult {
        /// Parent operation that causally owns the subagent.
        parent_operation_id: Uuid,
        /// Exact application tool name.
        name: String,
        /// Whether execution itself succeeded.
        ok: bool,
        /// Whether the resulting context projection fit.
        projection_accepted: bool,
        /// Exact application result before provider compaction.
        result: String,
    },
    /// Canonical accounting for one completed or interrupted provider round.
    ProviderReceipt {
        /// Parent operation that causally owns the subagent.
        parent_operation_id: Uuid,
        /// One-based subagent round.
        round: u64,
        /// SHA-256 hash of the exact provider input.
        manifest_hash: String,
        /// Provider-native cumulative usage retained for exact audit detail.
        usage: Option<kcode_codex_runtime_v2::TokenUsage>,
        /// Canonical durable receipt written by the intelligence router.
        receipt: Box<UsageReceipt>,
    },
    /// Final non-empty subagent answer.
    Completed {
        /// Parent operation that causally owns the subagent.
        parent_operation_id: Uuid,
        /// Caller-selected model identifier.
        model: String,
        /// Terminal response returned to the application.
        response: String,
    },
}

/// One replaceable state section rendered into every later context slice.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StateUpdate {
    /// Stable state identity. A later update with this key replaces the prior text.
    pub key: String,
    /// Current rendered state, or `None` to remove it.
    pub text: Option<String>,
}

/// Result returned by the application after one tool or capture operation.
#[derive(Clone, Debug, PartialEq)]
pub struct ToolOutcome {
    /// Exact result retained for audit.
    pub text: String,
    /// Whether the operation succeeded.
    pub ok: bool,
    /// Replaceable state made current by the operation.
    pub state_updates: Vec<StateUpdate>,
    /// Opaque application token requesting a tool-free freeform output capture.
    pub capture: Option<Value>,
}

impl ToolOutcome {
    /// Constructs a simple successful result.
    pub fn success(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ok: true,
            state_updates: Vec::new(),
            capture: None,
        }
    }

    /// Constructs a simple failed result.
    pub fn failure(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            ok: false,
            state_updates: Vec::new(),
            capture: None,
        }
    }
}

/// Read-only capacity view supplied while a host evaluates a tool.
#[derive(Clone)]
pub struct ContextBudget {
    projection: Projection,
    max_input_tokens: u64,
}

impl ContextBudget {
    /// Current estimated input tokens, including protocol reserve.
    pub fn estimated_tokens(&self) -> u64 {
        self.projection.estimated_tokens()
    }

    /// Maximum permitted input tokens.
    pub fn max_input_tokens(&self) -> u64 {
        self.max_input_tokens
    }

    /// Returns whether replacing one projected state would fit.
    pub fn fits_state(&self, key: impl Into<String>, text: impl Into<String>) -> bool {
        let mut projection = self.projection.clone();
        projection.update_state(key.into(), Some(text.into()));
        projection.estimated_tokens() <= self.max_input_tokens
    }
}

/// Application-owned behavior invoked by the generic subagent loop.
pub trait Host: Send {
    /// Renders the retained invocation text before execution.
    fn render_tool_call(&mut self, call: &ToolCall) -> anyhow::Result<String>;

    /// Executes one application tool.
    fn execute_tool<'a>(
        &'a mut self,
        call: ToolCall,
        operation_id: Uuid,
        budget: ContextBudget,
    ) -> HostFuture<'a, ToolOutcome>;

    /// Completes an opaque freeform capture requested by a prior tool result.
    fn complete_capture<'a>(
        &'a mut self,
        capture: Value,
        contents: String,
        budget: ContextBudget,
    ) -> HostFuture<'a, ToolOutcome>;

    /// Records one durable audit event selected by the runtime.
    fn record(&mut self, event: AuditEvent) -> anyhow::Result<()>;
}

/// Inputs for one complete subagent run.
#[derive(Clone, Debug, PartialEq)]
pub struct RunRequest {
    /// Stable user identifier used for router accounting.
    pub user_id: String,
    /// Running parent operation whose cancellation propagates to each turn.
    pub parent_operation_id: Uuid,
    /// Exact requested model selector.
    pub model: String,
    /// Provider-neutral reasoning effort.
    pub reasoning_effort: String,
    /// Ordered immutable context sections.
    pub context: Vec<String>,
    /// Exact task presented after the context.
    pub task: String,
    /// Optional per-turn timeout.
    pub timeout: Option<Duration>,
    /// Additional application metadata included in the start audit event.
    pub start_metadata: Value,
}

/// Completed subagent output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunResult {
    /// Final non-empty assistant answer.
    pub answer: String,
    /// Model used for every turn.
    pub model: ResolvedAgentModel,
}

/// Cloneable provider-neutral subagent runtime.
#[derive(Clone)]
pub struct AgentRuntime {
    intelligence: Intelligence,
    round_limit: u64,
}

impl AgentRuntime {
    /// Constructs a runtime over the sole direct-model boundary.
    pub fn new(intelligence: Intelligence) -> Self {
        Self {
            intelligence,
            round_limit: DEFAULT_ROUND_LIMIT,
        }
    }

    /// Resolves a model without running an agent.
    pub async fn resolve_model(&self, requested: &str) -> anyhow::Result<ResolvedAgentModel> {
        self.intelligence
            .resolve_agent_model(requested)
            .await
            .map_err(anyhow::Error::new)
    }

    /// Runs one fresh-context subagent to a final non-empty answer.
    pub async fn run<H: Host>(
        &self,
        request: RunRequest,
        host: &mut H,
    ) -> anyhow::Result<RunResult> {
        let selected = self.resolve_model(&request.model).await?;
        let reasoning_effort = reasoning_effort(&request.reasoning_effort)?;
        let mut projection = Projection::new(request.context, request.task);
        ensure_capacity(&projection, selected.max_input_tokens)?;
        host.record(AuditEvent::Started {
            parent_operation_id: request.parent_operation_id,
            model: request.model.clone(),
            provider_model: selected.provider_model.clone(),
            provider: selected.provider,
            context_window_tokens: selected.context_window_tokens,
            max_input_tokens: selected.max_input_tokens,
            context: projection.context.clone(),
            task: projection.task.clone(),
            host: request.start_metadata.clone(),
        })?;
        let user = self
            .intelligence
            .for_user(request.user_id)
            .map_err(anyhow::Error::new)?;
        let mut deferred_capture: Option<Value> = None;

        for round in 0..self.round_limit {
            let capturing = deferred_capture.is_some();
            ensure_capacity(&projection, selected.max_input_tokens)?;
            let input = projection.render();
            let manifest_hash = hex::encode(Sha256::digest(input.as_bytes()));
            host.record(AuditEvent::InferenceSubmitted {
                parent_operation_id: request.parent_operation_id,
                round: round + 1,
                manifest_hash: manifest_hash.clone(),
                estimated_input_tokens: projection.estimated_tokens(),
            })?;
            let mut provider_request = AgentRequest::new(input, selected.requested_model.clone());
            provider_request.reasoning_effort = reasoning_effort;
            provider_request.ephemeral = true;
            provider_request.tools = if capturing {
                Vec::new()
            } else {
                vec![ktool_definition()]
            };
            if let Some(timeout) = request.timeout {
                provider_request.timeout = timeout;
            }
            let child_operation_id = Uuid::new_v4();
            let mut turn = match user
                .start_agent_turn(
                    child_operation_id,
                    Some(request.parent_operation_id),
                    provider_request,
                )
                .await
            {
                Ok(turn) => turn,
                Err(error) => {
                    if let Some(receipt) = error.receipt().cloned() {
                        host.record(AuditEvent::ProviderReceipt {
                            parent_operation_id: request.parent_operation_id,
                            round: round + 1,
                            manifest_hash,
                            usage: None,
                            receipt: Box::new(receipt),
                        })?;
                    }
                    return Err(anyhow::Error::new(error));
                }
            };
            let mut used_tool = false;
            let mut pending_capture: Option<Value> = None;
            let mut requires_rerender = false;
            let completed = loop {
                let event = match turn.next_event().await {
                    Ok(Some(event)) => event,
                    Ok(None) => {
                        let receipt = turn.finish_unavailable()?.clone();
                        host.record(AuditEvent::ProviderReceipt {
                            parent_operation_id: request.parent_operation_id,
                            round: round + 1,
                            manifest_hash: manifest_hash.clone(),
                            usage: None,
                            receipt: Box::new(receipt),
                        })?;
                        anyhow::bail!("subagent provider ended without a terminal turn event");
                    }
                    Err(error) => {
                        if let Some(receipt) = error.receipt().cloned() {
                            host.record(AuditEvent::ProviderReceipt {
                                parent_operation_id: request.parent_operation_id,
                                round: round + 1,
                                manifest_hash: manifest_hash.clone(),
                                usage: None,
                                receipt: Box::new(receipt),
                            })?;
                        }
                        return Err(anyhow::Error::new(error));
                    }
                };
                match event {
                    AgentEvent::ProviderInput(_) => {}
                    AgentEvent::UsageUpdated(_) => {}
                    AgentEvent::ToolCall(native) => {
                        used_tool = true;
                        if capturing {
                            respond_or_record(
                                &mut turn,
                                host,
                                request.parent_operation_id,
                                round + 1,
                                &manifest_hash,
                                &native.call_id,
                                ToolResult::failure(
                                    "No application tool is available while complete freeform output is being captured.",
                                ),
                            )
                            .await?;
                            continue;
                        }
                        if pending_capture.is_some() {
                            respond_or_record(
                                &mut turn,
                                host,
                                request.parent_operation_id,
                                round + 1,
                                &manifest_hash,
                                &native.call_id,
                                ToolResult::failure(
                                    "A freeform output capture is pending; no other tool can run first.",
                                ),
                            )
                            .await?;
                            continue;
                        }
                        if requires_rerender {
                            respond_or_record(
                                &mut turn,
                                host,
                                request.parent_operation_id,
                                round + 1,
                                &manifest_hash,
                                &native.call_id,
                                ToolResult::failure(
                                    "A state update is waiting to be re-rendered. End this slice before calling another tool.",
                                ),
                            )
                            .await?;
                            continue;
                        }
                        let call = match parse_ktool_call(&native) {
                            Ok(call) => call,
                            Err(error) => {
                                let text = format!("Invalid application tool call: {error}");
                                projection.push_history(format!("Ktool result:\n{text}"));
                                respond_or_record(
                                    &mut turn,
                                    host,
                                    request.parent_operation_id,
                                    round + 1,
                                    &manifest_hash,
                                    &native.call_id,
                                    ToolResult::failure(text),
                                )
                                .await?;
                                continue;
                            }
                        };
                        host.record(AuditEvent::ToolCall {
                            parent_operation_id: request.parent_operation_id,
                            name: call.name.clone(),
                            arguments: call.arguments.clone(),
                        })?;
                        projection.push_history(format!(
                            "Ktool call:\n{}",
                            host.render_tool_call(&call)?
                        ));
                        let budget = ContextBudget {
                            projection: projection.clone(),
                            max_input_tokens: selected.max_input_tokens,
                        };
                        let mut outcome = host
                            .execute_tool(call.clone(), child_operation_id, budget)
                            .await
                            .unwrap_or_else(|error| {
                                ToolOutcome::failure(format!("{} failed: {error}", call.name))
                            });
                        let exact_result = outcome.text.clone();
                        let initially_ok = outcome.ok;
                        let mut provider_result =
                            compact_tool_result(&outcome.text, &outcome.state_updates);
                        let mut candidate = projection.clone();
                        candidate.apply_updates(&outcome.state_updates);
                        candidate.push_history(format!("Ktool result:\n{provider_result}"));
                        let accepted = candidate.estimated_tokens() <= selected.max_input_tokens;
                        if accepted {
                            projection = candidate;
                            requires_rerender = !outcome.state_updates.is_empty();
                        } else {
                            outcome.ok = false;
                            outcome.capture = None;
                            provider_result = "The tool ran, but its result or updated state could not fit in the subagent context. Do not retry it; report the capacity failure to Kennedy.".into();
                            projection.push_history(format!("Ktool result:\n{provider_result}"));
                        }
                        host.record(AuditEvent::ToolResult {
                            parent_operation_id: request.parent_operation_id,
                            name: call.name.clone(),
                            ok: initially_ok,
                            projection_accepted: accepted,
                            result: exact_result,
                        })?;
                        pending_capture = outcome.capture.take();
                        respond_or_record(
                            &mut turn,
                            host,
                            request.parent_operation_id,
                            round + 1,
                            &manifest_hash,
                            &native.call_id,
                            if outcome.ok {
                                ToolResult::success(provider_result)
                            } else {
                                ToolResult::failure(provider_result)
                            },
                        )
                        .await?;
                    }
                    AgentEvent::Completed(completed) => break completed,
                }
            };
            let receipt = turn
                .receipt()
                .context("subagent provider completed without a usage receipt")?
                .clone();
            host.record(AuditEvent::ProviderReceipt {
                parent_operation_id: request.parent_operation_id,
                round: round + 1,
                manifest_hash: manifest_hash.clone(),
                usage: completed.usage.clone(),
                receipt: Box::new(receipt),
            })?;

            let capture = deferred_capture.take().or(pending_capture);
            if let Some(capture) = capture {
                if !capturing && completed.answer.is_empty() {
                    deferred_capture = Some(capture);
                    continue;
                }
                let budget = ContextBudget {
                    projection: projection.clone(),
                    max_input_tokens: selected.max_input_tokens,
                };
                let outcome = host
                    .complete_capture(capture, completed.answer, budget)
                    .await?;
                let mut candidate = projection.clone();
                candidate.apply_updates(&outcome.state_updates);
                candidate.push_history(format!("Ktool result:\n{}", outcome.text));
                ensure_capacity(&candidate, selected.max_input_tokens)?;
                projection = candidate;
                continue;
            }
            if requires_rerender {
                let draft = completed.answer.trim();
                if !draft.is_empty() {
                    projection.push_history(format!(
                        "Assistant draft produced before the state refresh:\n{draft}"
                    ));
                }
                continue;
            }
            let answer = completed.answer.trim().to_owned();
            if !answer.is_empty() {
                host.record(AuditEvent::Completed {
                    parent_operation_id: request.parent_operation_id,
                    model: request.model.clone(),
                    response: answer.clone(),
                })?;
                return Ok(RunResult {
                    answer,
                    model: selected,
                });
            }
            ensure!(
                used_tool,
                "subagent provider completed without a response or tool call"
            );
        }
        anyhow::bail!(
            "subagent exceeded the {}-round tool-loop safety limit",
            self.round_limit
        )
    }
}

async fn respond_or_record<H: Host>(
    turn: &mut kcode_intelligence_router::AgentTurn,
    host: &mut H,
    parent_operation_id: Uuid,
    round: u64,
    manifest_hash: &str,
    call_id: &str,
    result: ToolResult,
) -> anyhow::Result<()> {
    if let Err(error) = turn.respond(call_id, result).await {
        let receipt = turn.finish_unavailable()?.clone();
        host.record(AuditEvent::ProviderReceipt {
            parent_operation_id,
            round,
            manifest_hash: manifest_hash.into(),
            usage: None,
            receipt: Box::new(receipt),
        })?;
        return Err(anyhow::Error::new(error));
    }
    Ok(())
}

#[derive(Clone)]
struct Projection {
    context: Vec<String>,
    task: String,
    history: Vec<String>,
    states: Vec<ProjectedState>,
}

#[derive(Clone)]
struct ProjectedState {
    key: String,
    text: String,
}

impl Projection {
    fn new(context: Vec<String>, task: String) -> Self {
        Self {
            context,
            task,
            history: Vec::new(),
            states: Vec::new(),
        }
    }

    fn render(&self) -> String {
        self.context
            .iter()
            .map(String::as_str)
            .chain(std::iter::once(self.task.as_str()))
            .chain(self.history.iter().map(String::as_str))
            .chain(self.states.iter().map(|state| state.text.as_str()))
            .filter(|section| !section.is_empty())
            .collect::<Vec<_>>()
            .join("\n\n")
    }

    fn push_history(&mut self, text: impl Into<String>) {
        self.history.push(text.into());
    }

    fn update_state(&mut self, key: String, text: Option<String>) {
        self.states.retain(|state| state.key != key);
        if let Some(text) = text {
            self.states.push(ProjectedState { key, text });
        }
    }

    fn apply_updates(&mut self, updates: &[StateUpdate]) {
        for update in updates {
            self.update_state(update.key.clone(), update.text.clone());
        }
    }

    fn estimated_tokens(&self) -> u64 {
        (self.render().chars().count() as u64)
            .div_ceil(4)
            .saturating_add(PROTOCOL_TOKEN_RESERVE)
    }
}

fn compact_tool_result(text: &str, states: &[StateUpdate]) -> String {
    if states.is_empty() {
        return text.to_owned();
    }
    let result = if text.chars().count() <= INLINE_TOOL_RESULT_CHARACTERS {
        text
    } else {
        "Tool completed successfully."
    };
    format!(
        "{result}\n\nThe updated state will be rendered in the next fresh context slice; end this slice now."
    )
}

fn ensure_capacity(projection: &Projection, max_input_tokens: u64) -> anyhow::Result<()> {
    let estimated = projection.estimated_tokens();
    ensure!(
        estimated <= max_input_tokens,
        "subagent context requires approximately {estimated} input tokens, over the selected model's {max_input_tokens}-token input limit"
    );
    Ok(())
}

fn ktool_definition() -> DynamicTool {
    DynamicTool::new(
        "call_ktool",
        "Call one available Ktool by its exact name.",
        json!({
            "type": "object",
            "additionalProperties": false,
            "required": ["name", "arguments"],
            "properties": {
                "name": {"type": "string"},
                "arguments": {"type": "object"}
            }
        }),
    )
}

fn parse_ktool_call(call: &DynamicToolCall) -> anyhow::Result<ToolCall> {
    ensure!(call.tool == "call_ktool", "unknown provider tool");
    let arguments = call
        .arguments
        .as_object()
        .context("call_ktool arguments must be an object")?;
    ensure!(
        arguments
            .keys()
            .all(|key| matches!(key.as_str(), "name" | "arguments")),
        "call_ktool contains unknown arguments"
    );
    let name = arguments
        .get("name")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|name| !name.is_empty() && name.chars().count() <= 100)
        .context("call_ktool.name must be a non-empty bounded string")?
        .to_owned();
    let arguments = arguments
        .get("arguments")
        .filter(|value| value.is_object())
        .context("call_ktool.arguments must be an object")?
        .clone();
    Ok(ToolCall { name, arguments })
}

fn reasoning_effort(value: &str) -> anyhow::Result<ReasoningEffort> {
    Ok(match value {
        "none" => ReasoningEffort::None,
        "minimal" => ReasoningEffort::Minimal,
        "low" => ReasoningEffort::Low,
        "medium" => ReasoningEffort::Medium,
        "high" => ReasoningEffort::High,
        "xhigh" => ReasoningEffort::XHigh,
        "max" => ReasoningEffort::Max,
        _ => anyhow::bail!("unsupported reasoning effort {value:?}"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn projection_replaces_state_and_budget_accounts_for_reserve() {
        let mut projection = Projection::new(vec!["context".into()], "task".into());
        projection.update_state("file".into(), Some("old".into()));
        projection.update_state("file".into(), Some("new".into()));
        assert_eq!(projection.states.len(), 1);
        assert!(projection.render().contains("new"));
        assert!(!projection.render().contains("old"));
        assert!(projection.estimated_tokens() >= PROTOCOL_TOKEN_RESERVE);
    }

    #[test]
    fn state_changes_compact_large_tool_results() {
        let compacted = compact_tool_result(
            &"x".repeat(INLINE_TOOL_RESULT_CHARACTERS + 1),
            &[StateUpdate {
                key: "state".into(),
                text: Some("current".into()),
            }],
        );
        assert!(compacted.starts_with("Tool completed successfully."));
        assert!(compacted.contains("fresh context slice"));
    }

    #[test]
    fn native_tool_wrapper_is_strict() {
        let call = parse_ktool_call(&DynamicToolCall {
            call_id: "1".into(),
            tool: "call_ktool".into(),
            arguments: json!({"name": "Read", "arguments": {"id": 1}}),
        })
        .unwrap();
        assert_eq!(call.name, "Read");
        assert_eq!(call.arguments["id"], 1);
    }
}