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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
//! Provider-neutral agent 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, TokenUsage, 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 shared by every provider call in one primary session run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionRunRequest {
/// Stable user identifier used for router accounting.
pub user_id: String,
/// Top-level operation whose cancellation propagates to every provider call.
pub operation_id: Uuid,
/// Number of provider rounds already durably used by a restored session.
pub rounds_used: u64,
/// Maximum cumulative provider rounds permitted for the logical turn.
pub round_limit: u64,
}
/// Exact provider input prepared by the application for one primary round.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PreparedRound {
/// Complete provider-visible context.
pub input: String,
/// Exact requested model identifier.
pub model: String,
/// Provider-neutral reasoning effort.
pub reasoning_effort: String,
/// Session-specific explanation attached to the single application-tool bridge.
pub tool_description: String,
/// Optional complete provider-turn timeout.
pub timeout: Option<Duration>,
}
/// Result of preparing the next primary round.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RoundPreparation {
/// Run the prepared provider round.
Run(PreparedRound),
/// Finish without starting another provider round.
Complete(Option<String>),
}
/// One durable provider-protocol fact emitted by the primary runtime.
#[derive(Clone, Debug, PartialEq)]
pub enum SessionEvent {
/// Exact input identity submitted for one provider round.
InferenceSubmitted {
/// Cumulative one-based provider round.
round: u64,
/// SHA-256 hash of the exact provider input.
manifest_hash: String,
/// Exact requested model identifier.
model: String,
},
/// Exact provider transport input retained for diagnostics.
ProviderInput {
/// Cumulative one-based provider round.
round: u64,
/// Exact provider input record.
input: String,
},
/// Cumulative live usage reported during the provider round.
UsageUpdated {
/// Cumulative one-based provider round.
round: u64,
/// Provider-native cumulative usage.
usage: TokenUsage,
},
/// Canonical receipt and final usage for a completed or interrupted call.
ProviderReceipt {
/// Cumulative one-based provider round.
round: u64,
/// Final provider-native usage when available.
usage: Option<TokenUsage>,
/// Canonical durable receipt written by the intelligence router.
receipt: Box<UsageReceipt>,
},
}
/// Complete application handling of one primary-session tool call.
#[derive(Clone, Debug, PartialEq)]
pub struct SessionToolOutcome {
/// Exact result returned through the provider's native tool protocol.
pub text: String,
/// Whether tool execution succeeded.
pub ok: bool,
/// Opaque token requesting tool-free freeform output capture.
pub capture: Option<Value>,
/// Whether the logical session must stop after this tool response.
pub stop: bool,
/// Whether the logical session should finish after this provider round.
pub finish_after_round: bool,
/// Whether this tool already emitted the session's externally visible response.
pub emitted_response: bool,
}
impl SessionToolOutcome {
/// Constructs a simple successful tool result.
pub fn success(text: impl Into<String>) -> Self {
Self {
text: text.into(),
ok: true,
capture: None,
stop: false,
finish_after_round: false,
emitted_response: false,
}
}
/// Constructs a simple failed tool result.
pub fn failure(text: impl Into<String>) -> Self {
Self {
text: text.into(),
ok: false,
capture: None,
stop: false,
finish_after_round: false,
emitted_response: false,
}
}
}
/// Provider completion summarized for the application-owned session policy.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RoundCompletion {
/// Terminal assistant text, which may be empty after tool use.
pub answer: String,
/// Whether the provider called at least one application tool.
pub used_tool: bool,
/// Whether a successful tool requested session completion after this round.
pub finish_requested: bool,
/// Whether a tool already emitted the externally visible response.
pub emitted_response: bool,
}
/// Application decision after completing a semantic primary-session transition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SessionControl {
/// Prepare another fresh provider round.
Continue,
/// Finish the logical turn with the optional externally visible answer.
Complete(Option<String>),
}
/// Application-owned semantics invoked by the primary agent runtime.
pub trait SessionHost: Send {
/// Prepares the complete context and runtime selection for one provider round.
fn prepare_round<'a>(&'a mut self, round: u64) -> HostFuture<'a, RoundPreparation>;
/// Records one provider-protocol fact and durably checkpoints its effects.
fn record<'a>(&'a mut self, event: SessionEvent) -> HostFuture<'a, ()>;
/// Executes and durably projects one parsed or invalid application tool call.
fn execute_tool<'a>(
&'a mut self,
call: anyhow::Result<ToolCall>,
provider_operation_id: Uuid,
) -> HostFuture<'a, SessionToolOutcome>;
/// Completes an opaque freeform capture requested by a prior tool result.
fn complete_capture<'a>(
&'a mut self,
capture: Value,
contents: String,
) -> HostFuture<'a, SessionControl>;
/// Applies the terminal provider answer and decides whether another round is needed.
fn complete_round<'a>(
&'a mut self,
completion: RoundCompletion,
) -> HostFuture<'a, SessionControl>;
}
/// Error returned when a restored primary turn exhausts its cumulative round budget.
#[derive(Debug)]
pub struct SessionRoundLimitError {
limit: u64,
}
impl std::fmt::Display for SessionRoundLimitError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"agent exceeded the {}-round tool-loop safety limit",
self.limit
)
}
}
impl std::error::Error for SessionRoundLimitError {}
/// Returns whether an error is the primary runtime's round-limit signal.
pub fn is_session_round_limit(error: &anyhow::Error) -> bool {
error.downcast_ref::<SessionRoundLimitError>().is_some()
}
/// 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 primary logical turn across fresh provider rounds until the host completes it.
pub async fn run_session<H: SessionHost>(
&self,
request: SessionRunRequest,
host: &mut H,
) -> anyhow::Result<Option<String>> {
ensure!(
request.round_limit > 0,
"session round limit must be positive"
);
ensure!(
request.rounds_used <= request.round_limit,
"restored session round count exceeds its safety limit"
);
let user = self
.intelligence
.for_user(request.user_id)
.map_err(anyhow::Error::new)?;
for round_index in request.rounds_used..request.round_limit {
let round = round_index + 1;
let prepared = match host.prepare_round(round).await? {
RoundPreparation::Run(prepared) => prepared,
RoundPreparation::Complete(answer) => return Ok(answer),
};
let manifest_hash = hex::encode(Sha256::digest(prepared.input.as_bytes()));
host.record(SessionEvent::InferenceSubmitted {
round,
manifest_hash: manifest_hash.clone(),
model: prepared.model.clone(),
})
.await?;
let mut provider_request = AgentRequest::new(prepared.input, prepared.model);
provider_request.reasoning_effort = reasoning_effort(&prepared.reasoning_effort)?;
provider_request.previous_thread_id = None;
provider_request.tools = vec![ktool_definition(&prepared.tool_description)];
if let Some(timeout) = prepared.timeout {
provider_request.timeout = timeout;
}
let mut turn = match user
.start_agent_turn(request.operation_id, None, provider_request)
.await
{
Ok(turn) => turn,
Err(error) => {
if let Some(receipt) = error.receipt().cloned() {
host.record(SessionEvent::ProviderReceipt {
round,
usage: None,
receipt: Box::new(receipt),
})
.await?;
}
return Err(anyhow::Error::new(error));
}
};
let mut used_tool = false;
let mut finish_requested = false;
let mut emitted_response = false;
let mut pending_capture: Option<Value> = None;
let completed = loop {
let event = match turn.next_event().await {
Ok(Some(event)) => event,
Ok(None) => {
let receipt = turn.finish_unavailable()?.clone();
host.record(SessionEvent::ProviderReceipt {
round,
usage: None,
receipt: Box::new(receipt),
})
.await?;
anyhow::bail!("provider ended without a terminal turn event");
}
Err(error) => {
if let Some(receipt) = error.receipt().cloned() {
host.record(SessionEvent::ProviderReceipt {
round,
usage: None,
receipt: Box::new(receipt),
})
.await?;
}
return Err(anyhow::Error::new(error));
}
};
match event {
AgentEvent::ProviderInput(input) => {
host.record(SessionEvent::ProviderInput { round, input })
.await?;
}
AgentEvent::UsageUpdated(usage) => {
host.record(SessionEvent::UsageUpdated { round, usage })
.await?;
}
AgentEvent::ToolCall(native) => {
used_tool = true;
let call = parse_ktool_call(&native)
.map_err(|error| anyhow::anyhow!("Invalid Ktool call: {error}"));
let mut outcome = host.execute_tool(call, request.operation_id).await?;
finish_requested |= outcome.ok && outcome.finish_after_round;
emitted_response |= outcome.ok && outcome.emitted_response;
pending_capture = outcome.capture.take();
let stop = outcome.stop;
respond_session_or_record(
&mut turn,
host,
round,
&native.call_id,
if outcome.ok {
ToolResult::success(outcome.text)
} else {
ToolResult::failure(outcome.text)
},
)
.await?;
if stop {
return Ok(None);
}
}
AgentEvent::Completed(completed) => break completed,
}
};
let receipt = turn
.receipt()
.context("provider completed without a usage receipt")?
.clone();
host.record(SessionEvent::ProviderReceipt {
round,
usage: completed.usage.clone(),
receipt: Box::new(receipt),
})
.await?;
let control = if let Some(capture) = pending_capture {
host.complete_capture(capture, completed.answer).await?
} else {
host.complete_round(RoundCompletion {
answer: completed.answer,
used_tool,
finish_requested,
emitted_response,
})
.await?
};
match control {
SessionControl::Continue => {}
SessionControl::Complete(answer) => return Ok(answer),
}
}
Err(SessionRoundLimitError {
limit: request.round_limit,
}
.into())
}
/// 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(
"Call one available Ktool by its exact name.",
)]
};
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(())
}
async fn respond_session_or_record<H: SessionHost>(
turn: &mut kcode_intelligence_router::AgentTurn,
host: &mut H,
round: u64,
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(SessionEvent::ProviderReceipt {
round,
usage: None,
receipt: Box::new(receipt),
})
.await?;
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(description: &str) -> DynamicTool {
DynamicTool::new(
"call_ktool",
description,
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);
}
}