1use serde::Serialize;
14
15use kian_core::model::SessionId;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct FrameInfo {
22 pub session: SessionId,
26 pub worker: String,
29 pub seq: u64,
32 pub epoch: Option<u64>,
35}
36
37impl FrameInfo {
38 pub fn new(session: SessionId) -> Self {
41 Self {
42 session,
43 worker: String::new(),
44 seq: 0,
45 epoch: None,
46 }
47 }
48}
49
50pub const EXEC_WORKER_KEY: &str = "exec_worker";
58
59fn binding_of_value(value: Option<&serde_json::Value>) -> Option<&str> {
60 match value {
61 Some(serde_json::Value::String(id)) if !id.is_empty() => Some(id.as_str()),
62 _ => None,
63 }
64}
65
66pub fn durable_worker_binding(
81 events: &[kian_core::events::Event],
82 session: &SessionId,
83) -> Option<String> {
84 let started = events.iter().find(|ev| {
85 ev.kind == kian_core::events::EventKind::ThreadStarted
86 && ev.bytes.get("worker").and_then(serde_json::Value::as_str)
87 == Some(session.0.to_string().as_str())
88 });
89 let payload = started.and_then(|ev| binding_of_value(ev.bytes.get(EXEC_WORKER_KEY)));
90 let wrapper = events
91 .iter()
92 .find(|ev| ev.kind == kian_core::events::EventKind::InputAdmitted)
93 .and_then(|ev| ev.bytes.get("content"))
94 .and_then(|content| binding_of_value(content.get(EXEC_WORKER_KEY)));
95 match (payload, wrapper) {
96 (Some(a), Some(b)) if a == b => Some(a.to_string()),
97 (Some(a), None) | (None, Some(a)) => Some(a.to_string()),
98 _ => None,
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum Origin {
107 Channel,
108 Api,
109}
110
111impl Origin {
112 pub fn as_str(self) -> &'static str {
113 match self {
114 Origin::Channel => "channel",
115 Origin::Api => "api",
116 }
117 }
118
119 pub fn parse(s: &str) -> Option<Self> {
120 match s {
121 "channel" => Some(Origin::Channel),
122 "api" => Some(Origin::Api),
123 _ => None,
124 }
125 }
126}
127
128impl Serialize for Origin {
129 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
130 serializer.serialize_str(self.as_str())
131 }
132}
133
134#[derive(Debug, Clone, Serialize)]
136pub struct AdmitTarget {
137 pub session: SessionId,
138 pub router: bool,
140}
141
142#[derive(Debug, Clone, Serialize)]
144pub struct AdmitInput {
145 pub role: String,
146 pub synthetic: bool,
148 pub content_preview: String,
150 pub content_bytes: u64,
152 pub content_sha256: String,
154 pub content_truncated: bool,
156 pub inline_view: bool,
158}
159
160#[derive(Debug, Clone, Serialize)]
163pub struct ChannelProvenance {
164 pub name: String,
165 pub event_id: String,
166 pub topic: Option<String>,
167}
168
169#[derive(Debug, Clone, Serialize)]
171pub struct AdmissionInfo {
172 pub policy: String,
173 pub spilled: bool,
174}
175
176#[derive(Debug, Clone, Serialize)]
180pub struct AdmitDraft {
181 pub origin: Origin,
182 pub targets: Vec<AdmitTarget>,
185 pub input: AdmitInput,
186 pub channel: Option<ChannelProvenance>,
188 pub admission: AdmissionInfo,
189 #[serde(skip)]
193 pub frames: Vec<FrameInfo>,
194}
195
196#[derive(Debug, Clone, Serialize)]
199pub struct AdmitReceiptView {
200 pub session: SessionId,
201 pub event_id: String,
202 pub seq: u64,
203 pub origin: Origin,
204 pub deduplicated: bool,
205 pub input: AdmitPostInput,
206 #[serde(skip)]
207 pub frame: Option<FrameInfo>,
208}
209
210#[derive(Debug, Clone, Serialize)]
212pub struct AdmitPostInput {
213 pub role: String,
214 pub content_bytes: u64,
215 pub spilled: bool,
216}
217
218#[derive(Debug, Clone, Serialize)]
221pub struct RequestMeta {
222 pub slot: String,
223 pub provider: String,
224 pub model: String,
225 pub iteration: u64,
226 pub request_bytes: u64,
227 pub request_sha256: String,
228 pub message_count: u64,
229 pub tool_names: Vec<String>,
231 pub tool_schema_sha256: String,
232 pub timing: String,
234 pub step_request_seq: u64,
235 #[serde(skip)]
236 pub frame: Option<FrameInfo>,
237}
238
239#[derive(Debug, Clone, Serialize)]
242pub struct TurnErrorAudit {
243 pub class: String,
244 pub action: String,
245}
246
247#[derive(Debug, Clone, Serialize)]
250pub struct ResponseView {
251 pub iteration: u64,
252 pub outcome: String,
255 pub tool_calls: u64,
256 pub text_bytes: u64,
257 pub reasoning_bytes: u64,
258 pub usage: serde_json::Value,
259 pub error: Option<TurnErrorAudit>,
260 pub timing: String,
262 #[serde(skip)]
263 pub frame: Option<FrameInfo>,
264}
265
266#[derive(Debug, Clone, Serialize)]
270pub struct PermissionView {
271 pub evaluated: String,
272 pub policy: String,
273 pub matched: String,
274 #[serde(skip_serializing_if = "Option::is_none")]
275 pub reason: Option<String>,
276}
277
278#[derive(Debug, Clone, Serialize)]
283pub struct ToolCallView {
284 pub call_id: String,
285 pub name: String,
286 pub iteration: u64,
287 pub arguments: serde_json::Value,
288 pub arguments_bytes: u64,
289 pub arguments_sha256: String,
290 pub arguments_truncated: bool,
291 pub permission: PermissionView,
292 pub surface: String,
294 #[serde(skip)]
295 pub frame: Option<FrameInfo>,
296}
297
298#[derive(Debug, Clone, Serialize)]
301pub struct RedactionReport {
302 pub kind: String,
303 pub name: String,
304 pub count: u64,
305}
306
307#[derive(Debug, Clone, Serialize)]
310pub struct ToolPostView {
311 pub call_id: String,
312 pub name: String,
313 pub is_error: bool,
314 pub output_bytes: u64,
315 pub output_sha256: String,
316 pub redactions: Vec<RedactionReport>,
317 #[serde(skip)]
318 pub frame: Option<FrameInfo>,
319}
320
321#[derive(Debug, Clone, Serialize)]
325pub struct RecoveryView {
326 pub error_class: String,
327 pub action: String,
329 pub iteration: u64,
330 #[serde(skip)]
331 pub frame: Option<FrameInfo>,
332}
333
334#[derive(Debug, Clone, Serialize)]
337pub struct SettleView {
338 pub reason: String,
339 pub turns: u64,
340 pub tool_calls: u64,
341 pub evidence: String,
344 pub vetoes_used: u64,
346 pub vetoes_remaining: u64,
347 pub episodes: u64,
348 #[serde(skip)]
349 pub frame: Option<FrameInfo>,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
356pub enum AdmitVerdict {
357 Next,
359 Stop { plugin: String, reason: String },
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
366pub enum ToolVerdict {
367 Allow,
369 Deny { plugin: String, reason: String },
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
377pub enum SettleVerdict {
378 Allow,
380 Deny { plugin: String, reason: String },
384 Override {
387 plugin: String,
388 reason: String,
389 vetoes_used: u64,
390 },
391 AdmitFailed {
396 plugin: String,
397 reason: String,
398 error: String,
399 vetoes_used: u64,
400 },
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 fn sid(s: &str) -> SessionId {
408 serde_json::from_str(&format!("\"{s}\"")).expect("valid uuid literal")
412 }
413
414 fn frame(session: &str) -> Option<FrameInfo> {
415 Some(FrameInfo {
416 session: sid(session),
417 worker: "node-zulu".to_string(),
418 seq: 41,
419 epoch: Some(7),
420 })
421 }
422
423 const SESSION_A: &str = "0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b";
424 const SESSION_B: &str = "1f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b";
425
426 fn compact<T: Serialize>(v: &T) -> String {
427 serde_json::to_string(v).expect("view serializes")
428 }
429
430 #[test]
431 fn payload_goldens_match_spec_3_2() {
432 let draft = AdmitDraft {
436 origin: Origin::Channel,
437 targets: vec![
438 AdmitTarget {
439 session: sid(SESSION_A),
440 router: false,
441 },
442 AdmitTarget {
443 session: sid(SESSION_B),
444 router: true,
445 },
446 ],
447 input: AdmitInput {
448 role: "user".to_string(),
449 synthetic: false,
450 content_preview: "please run the cleanup".to_string(),
451 content_bytes: 91234,
452 content_sha256: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
453 .to_string(),
454 content_truncated: true,
455 inline_view: false,
456 },
457 channel: Some(ChannelProvenance {
458 name: "lark".to_string(),
459 event_id: "evt_42".to_string(),
460 topic: None,
461 }),
462 admission: AdmissionInfo {
463 policy: "inline_cap_bytes=8192".to_string(),
464 spilled: true,
465 },
466 frames: vec![frame(SESSION_A).unwrap(), frame(SESSION_B).unwrap()],
467 };
468 assert_eq!(
469 compact(&draft),
470 concat!(
471 r#"{"origin":"channel","targets":[{"session":"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b","router":false},"#,
472 r#"{"session":"1f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b","router":true}],"#,
473 r#""input":{"role":"user","synthetic":false,"content_preview":"please run the cleanup","content_bytes":91234,"#,
474 r#""content_sha256":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
475 r#""content_truncated":true,"inline_view":false},"#,
476 r#""channel":{"name":"lark","event_id":"evt_42","topic":null},"#,
477 r#""admission":{"policy":"inline_cap_bytes=8192","spilled":true}}"#
478 ),
479 "the in-process frame identity must not ride the wire (K2)"
480 );
481
482 let receipt = AdmitReceiptView {
484 session: sid(SESSION_A),
485 event_id: format!("{SESSION_A}:41"),
486 seq: 41,
487 origin: Origin::Channel,
488 deduplicated: false,
489 input: AdmitPostInput {
490 role: "user".to_string(),
491 content_bytes: 91234,
492 spilled: true,
493 },
494 frame: frame(SESSION_A),
495 };
496 assert_eq!(
497 compact(&receipt),
498 concat!(
499 r#"{"session":"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b","event_id":"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b:41","#,
500 r#""seq":41,"origin":"channel","deduplicated":false,"#,
501 r#""input":{"role":"user","content_bytes":91234,"spilled":true}}"#
502 )
503 );
504
505 let request = RequestMeta {
507 slot: "main".to_string(),
508 provider: "openai-compat".to_string(),
509 model: "gpt-5".to_string(),
510 iteration: 2,
511 request_bytes: 48211,
512 request_sha256: "11b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
513 .to_string(),
514 message_count: 11,
515 tool_names: vec!["fs_read".to_string(), "fs_write".to_string()],
516 tool_schema_sha256: "22b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
517 .to_string(),
518 timing: "pre_send".to_string(),
519 step_request_seq: 57,
520 frame: frame(SESSION_A),
521 };
522 assert_eq!(
523 compact(&request),
524 concat!(
525 r#"{"slot":"main","provider":"openai-compat","model":"gpt-5","iteration":2,"#,
526 r#""request_bytes":48211,"request_sha256":"11b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
527 r#""message_count":11,"tool_names":["fs_read","fs_write"],"#,
528 r#""tool_schema_sha256":"22b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
529 r#""timing":"pre_send","step_request_seq":57}"#
530 )
531 );
532
533 let response = ResponseView {
535 iteration: 2,
536 outcome: "final_answer".to_string(),
537 tool_calls: 0,
538 text_bytes: 1422,
539 reasoning_bytes: 0,
540 usage: serde_json::json!({"input_tokens": 120, "output_tokens": 30}),
541 error: None,
542 timing: "settled".to_string(),
543 frame: frame(SESSION_A),
544 };
545 assert_eq!(
546 compact(&response),
547 concat!(
548 r#"{"iteration":2,"outcome":"final_answer","tool_calls":0,"text_bytes":1422,"#,
549 r#""reasoning_bytes":0,"usage":{"input_tokens":120,"output_tokens":30},"error":null,"#,
550 r#""timing":"settled"}"#
551 )
552 );
553
554 let call = ToolCallView {
556 call_id: "call_abc".to_string(),
557 name: "exec".to_string(),
558 iteration: 2,
559 arguments: serde_json::json!({"cmd": ["rm", "-rf", "/tmp/x"]}),
560 arguments_bytes: 38,
561 arguments_sha256: "33b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
562 .to_string(),
563 arguments_truncated: false,
564 permission: PermissionView {
565 evaluated: "allow".to_string(),
566 policy: "configured".to_string(),
567 matched: "rule[3]".to_string(),
568 reason: None,
569 },
570 surface: "react".to_string(),
571 frame: frame(SESSION_A),
572 };
573 assert_eq!(
574 compact(&call),
575 concat!(
576 r#"{"call_id":"call_abc","name":"exec","iteration":2,"arguments":{"cmd":["rm","-rf","/tmp/x"]},"#,
577 r#""arguments_bytes":38,"arguments_sha256":"33b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
578 r#""arguments_truncated":false,"#,
579 r#""permission":{"evaluated":"allow","policy":"configured","matched":"rule[3]"},"#,
580 r#""surface":"react"}"#
581 )
582 );
583
584 let post = ToolPostView {
586 call_id: "call_abc".to_string(),
587 name: "exec".to_string(),
588 is_error: false,
589 output_bytes: 812,
590 output_sha256: "44b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
591 .to_string(),
592 redactions: vec![RedactionReport {
593 kind: "env_line".to_string(),
594 name: "OPENAI_API_KEY".to_string(),
595 count: 1,
596 }],
597 frame: frame(SESSION_A),
598 };
599 assert_eq!(
600 compact(&post),
601 concat!(
602 r#"{"call_id":"call_abc","name":"exec","is_error":false,"output_bytes":812,"#,
603 r#""output_sha256":"44b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2","#,
604 r#""redactions":[{"kind":"env_line","name":"OPENAI_API_KEY","count":1}]}"#
605 )
606 );
607
608 let recovery = RecoveryView {
610 error_class: "rate_limited".to_string(),
611 action: "backoff_retry".to_string(),
612 iteration: 3,
613 frame: frame(SESSION_A),
614 };
615 assert_eq!(
616 compact(&recovery),
617 r#"{"error_class":"rate_limited","action":"backoff_retry","iteration":3}"#
618 );
619
620 let settle = SettleView {
622 reason: "completed".to_string(),
623 turns: 4,
624 tool_calls: 7,
625 evidence: "passed".to_string(),
626 vetoes_used: 0,
627 vetoes_remaining: 3,
628 episodes: 2,
629 frame: frame(SESSION_A),
630 };
631 assert_eq!(
632 compact(&settle),
633 concat!(
634 r#"{"reason":"completed","turns":4,"tool_calls":7,"evidence":"passed","#,
635 r#""vetoes_used":0,"vetoes_remaining":3,"episodes":2}"#
636 )
637 );
638 }
639}