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
//! Typed call/result pairing receipts for the LLM transcript sidecar.
//!
//! # Why the transcript needs them
//!
//! Reconstructing "which tool result answers which tool call" from the
//! recorded turns alone does not work on every channel.
//!
//! On the native channel the provider gives each call an id and the result
//! message carries it back, so the pair is visible. On the text channel there
//! is no such id: the model writes an inline `<tool_call>` block, and the
//! result is served back as an ordinary `role: "user"` echo with no identity
//! anywhere on it. A consumer left to pair those by position is guessing —
//! and that is precisely how a generic aggregate placeholder ends up looking
//! like a tool result.
//!
//! `provider_call_response.parsed_tool_calls` cannot stand in either. It is
//! written when the provider replies, before the loop parses the turn, and on
//! a text-channel run it re-parses the same text against its own counter. Its
//! synthetic `tc_N` ids are a parallel id space that no result ever answers.
//!
//! So the two moments that actually know the answer record it: dispatch knows
//! the id a call ran under, and injection knows the message index a result
//! landed at. Together they make the sidecar self-describing on every channel.
//!
//! # Observability-only
//!
//! Like `resolved_dispatch`, nothing recorded here re-enters request
//! construction. The model's next-turn payload is byte-identical with or
//! without these events.
use crate::orchestration::{TOOL_CALL_RECEIPT_VERSION, TOOL_RESULT_RECEIPT_VERSION};
use crate::value::VmValue;
use serde::Serialize;
const SESSION_MESSAGE_FACTS_KEY: &str = "_harn";
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum SessionMessageFacts {
Assistant {
tool_calls: Vec<serde_json::Value>,
},
ToolResult {
tool_call_id: String,
tool_name: String,
outcome: ToolResultOutcome,
/// Who authored this result. Omitted for the ordinary dispatch case, so
/// every existing message is byte-identical and a reader that does not
/// know the field behaves as it always did.
#[serde(skip_serializing_if = "ToolResultOrigin::is_dispatch")]
origin: ToolResultOrigin,
#[serde(skip_serializing_if = "Option::is_none")]
data: Option<serde_json::Value>,
},
}
#[derive(Serialize)]
#[serde(rename_all = "snake_case")]
enum ToolResultOutcome {
Ok,
Error,
}
/// Who produced a tool result.
///
/// A result the harness synthesized carries the ORIGINAL tool's name and call
/// id, because that is what pairs it to the orphaned `tool_use` block. Without
/// this field it is therefore indistinguishable from a real failed call of that
/// tool, and a completion authority reads the harness's own injected feedback
/// back as an observation of the workspace (harn#7757).
#[derive(Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ToolResultOrigin {
/// The tool ran and this is what it returned.
#[default]
Dispatch,
/// The harness wrote this to close an orphaned `tool_use` block. Its
/// content is injected harness feedback, not a tool observation.
HarnessRepair,
}
impl ToolResultOrigin {
fn is_dispatch(&self) -> bool {
matches!(self, Self::Dispatch)
}
}
fn attach_session_message_facts(message: VmValue, facts: &SessionMessageFacts) -> VmValue {
let Some(existing) = message.as_dict() else {
return message;
};
let mut enriched = existing.clone();
let encoded = serde_json::to_value(facts).expect("session message facts must serialize");
enriched.insert(
crate::value::intern_key(SESSION_MESSAGE_FACTS_KEY),
crate::stdlib::json_to_vm_value(&encoded),
);
VmValue::dict(enriched)
}
/// Attach provider-neutral parsed call facts to a durable assistant message.
/// The unified post-parse `tool_calls` list is authoritative; direct host
/// embeddings that supply only `native_tool_calls` retain those as a fallback.
/// Provider adapters strip `_harn` before egress, so transcript consumers read
/// one lifecycle shape without altering provider-visible history.
pub(crate) fn attach_assistant_facts(message: VmValue, llm_result: &VmValue) -> VmValue {
let tool_calls = ["tool_calls", "native_tool_calls"]
.iter()
.find_map(|key| {
llm_result
.as_dict()
.and_then(|result| result.get(*key))
.and_then(|value| match value {
VmValue::List(items) if !items.is_empty() => Some(
items
.iter()
.map(crate::llm::helpers::vm_value_to_json)
.collect::<Vec<_>>(),
),
_ => None,
})
})
.unwrap_or_default();
attach_session_message_facts(message, &SessionMessageFacts::Assistant { tool_calls })
}
/// Attach the dispatch-owned result identity and outcome to a durable result
/// message on every provider/tool-format channel.
pub(crate) fn attach_tool_result_facts(
message: VmValue,
tool_call_id: &str,
tool_name: &str,
ok: bool,
data: Option<&VmValue>,
origin: ToolResultOrigin,
) -> VmValue {
attach_session_message_facts(
message,
&SessionMessageFacts::ToolResult {
tool_call_id: tool_call_id.to_string(),
tool_name: tool_name.to_string(),
outcome: if ok {
ToolResultOutcome::Ok
} else {
ToolResultOutcome::Error
},
origin,
data: data.map(crate::llm::helpers::vm_value_to_json),
},
)
}
/// Record the calls a batch is about to dispatch, with the ids their results
/// will answer under.
///
/// Emitted before dispatch, so the receipts for one assistant turn appear in
/// the order the calls were requested even when the batch runs them
/// concurrently.
pub(crate) fn emit_tool_call_receipts(calls: &[VmValue]) {
let Some(session_id) = crate::agent_sessions::current_session_id() else {
return;
};
// The calls were parsed from the message just before the next slot, i.e.
// the assistant turn this batch answers.
let Some(next_index) = crate::agent_sessions::next_message_index(&session_id) else {
return;
};
let assistant_message_index = next_index.saturating_sub(1);
for call in calls {
let call = crate::llm::helpers::vm_value_to_json(call);
let mut fields = serde_json::Map::new();
fields.insert(
"schema_version".to_string(),
serde_json::json!(TOOL_CALL_RECEIPT_VERSION),
);
fields.insert("session_id".to_string(), serde_json::json!(session_id));
fields.insert(
"assistant_message_index".to_string(),
serde_json::json!(assistant_message_index),
);
fields.insert(
"call_id".to_string(),
serde_json::json!(string_field(&call, &["id", "tool_call_id"])),
);
fields.insert(
"tool_name".to_string(),
serde_json::json!(string_field(&call, &["name", "tool_name"])),
);
fields.insert(
"arguments".to_string(),
call.get("arguments")
.or_else(|| call.get("tool_args"))
.cloned()
.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new())),
);
crate::llm::append_observability_sidecar_entry("tool_call", fields);
}
}
/// Record which call the message just injected answers.
///
/// `message_index` is the index [`crate::agent_sessions::inject_message`]
/// returned, which binds the receipt to one exact message instead of to
/// whatever event happens to follow it.
pub(crate) fn emit_tool_result_receipt(
session_id: &str,
message_index: usize,
tool_call_id: &str,
tool_name: &str,
ok: bool,
tool_format: &str,
) {
let mut fields = serde_json::Map::new();
fields.insert(
"schema_version".to_string(),
serde_json::json!(TOOL_RESULT_RECEIPT_VERSION),
);
fields.insert("session_id".to_string(), serde_json::json!(session_id));
fields.insert(
"message_index".to_string(),
serde_json::json!(message_index),
);
fields.insert("call_id".to_string(), serde_json::json!(tool_call_id));
fields.insert("tool_name".to_string(), serde_json::json!(tool_name));
fields.insert("ok".to_string(), serde_json::json!(ok));
fields.insert("tool_format".to_string(), serde_json::json!(tool_format));
crate::llm::append_observability_sidecar_entry("tool_result", fields);
}
fn string_field(call: &serde_json::Value, keys: &[&str]) -> String {
keys.iter()
.find_map(|key| call.get(*key).and_then(serde_json::Value::as_str))
.unwrap_or_default()
.to_string()
}