laser_wire/headers.rs
1// Header conventions. Format framing rides `agdx.*`, and index values ride the
2// `agdx.idx.` namespace as small scalars. The reserved keys are deliberately SHORT
3// and their values TYPED (u8 content-type code, u32 schema id, bool inline
4// flag): these headers ride every message, so at millions of messages the
5// key+value bytes are real bandwidth. The byte layout also matches the
6// planned native Iggy reserved-block carve (`schema_id: u32, content_type:
7// u8`), so the eventual migration is a dispatch-key swap.
8
9/// Header key: the wire codec tag (`u8` code, see
10/// [`ContentType::code`](crate::content::ContentType::code)).
11pub const CONTENT_TYPE: &str = "agdx.ct";
12/// Header key carrying the `u32` writer-schema id (typed header value) for a
13/// schema-first codec (Avro, Protobuf). The LaserData Cloud resolves it against
14/// its schema registry to decode the body. A bridge that lives in LaserData Cloud
15/// until Iggy gains native schema dispatch.
16pub const SCHEMA_ID: &str = "agdx.sid";
17/// Header key carrying the 32-byte logical schema fingerprint for an Arrow IPC stream.
18pub const LOGICAL_SCHEMA_FINGERPRINT: &str = "agdx.sfp";
19/// Prefix marking an indexed-field header (`agdx.idx.<name>`).
20pub const IDX_PREFIX: &str = "agdx.idx.";
21/// Header key: per-record inline-payload override (`bool` typed value).
22/// Stamped so the projector keeps a copy of the opaque payload bytes inline
23/// with the materialized row. Absent means the index row carries only indexed
24/// scalars and metadata while Iggy keeps the original body in the log.
25pub const INLINE_PAYLOAD: &str = "agdx.inline";
26/// Header key: which projection a record routes to. Opaque string by design
27/// (a name + version like `"reading.v1"`), deliberately distinct from `agdx.sid`,
28/// which selects a codec's writer schema rather than a materialization rule.
29pub const PROJECTION_REF: &str = "agdx.ref";
30/// Header key for the generic request/reply correlation id. Short on purpose
31/// (it rides every request/reply pair) and independent of any agentic header
32/// so the generic substrate works without provenance.
33pub const CORRELATION_ID: &str = "agdx.corr";
34
35// Well-known projected field names (the `agdx.idx.*` value after the prefix).
36/// Reserved indexed-field name for the event type.
37pub const FIELD_MESSAGE_TYPE: &str = "message_type";
38/// Reserved indexed-field name for the timestamp (epoch micros).
39pub const FIELD_TS: &str = "ts";
40/// Default field/pointer for the embedding vector.
41pub const VECTOR_FIELD: &str = "embedding";
42/// Result-row header key carrying a tumbling window's lower edge (epoch
43/// micros) when an aggregate query sets a window. Byte-identical to the
44/// LaserData Cloud's `window_start` column.
45pub const WINDOW_START: &str = "window_start";
46
47// On-wire header caps (Iggy-level, not provenance-specific).
48/// Soft cap on total header bytes per record.
49pub const HEADER_SOFT_CAP: usize = 1024;
50/// Per-header wire overhead counted toward the soft cap (key length, value
51/// kind, value length), so the cap reflects on-wire size.
52pub const HEADER_FRAMING_BYTES: usize = 9;
53/// Maximum bytes in a single header value (Iggy serializes the length as u8).
54pub const HEADER_VALUE_MAX: usize = 255;
55
56// The provenance dictionary. OTel `gen_ai.*` keys stay spec-exact (verified
57// against the gen-ai semconv registry) so traces correlate across tooling.
58// Custom keys are deliberately short because they ride every agentic message.
59/// Header key: conversation id (OTel `gen_ai.conversation.id`).
60pub const CONVERSATION_ID: &str = "gen_ai.conversation.id";
61/// The projected-column name a deployment materializes the
62/// [`CONVERSATION_ID`] header under, so every projection row is filterable by
63/// the conversation that produced it without a producer stamping an index
64/// header. The stable short field name the query surface's conversation lens
65/// and the graph/KV conversation columns all agree on.
66pub const CONVERSATION_FIELD: &str = "conversation_id";
67/// Header key: the producing agent's id.
68pub const AGENT_ID: &str = "gen_ai.agent.id";
69/// Header key: model requested for this call.
70pub const REQUEST_MODEL: &str = "gen_ai.request.model";
71/// Header key: model that answered this call.
72pub const RESPONSE_MODEL: &str = "gen_ai.response.model";
73/// Header key: provider that served this call.
74pub const PROVIDER_NAME: &str = "gen_ai.provider.name";
75/// Header key: LLM input/prompt tokens.
76pub const USAGE_INPUT_TOKENS: &str = "gen_ai.usage.input_tokens";
77/// Header key: LLM output/completion tokens.
78pub const USAGE_OUTPUT_TOKENS: &str = "gen_ai.usage.output_tokens";
79/// Header key: the message this one is a reply to.
80pub const CAUSAL_PARENT: &str = "agdx.cause";
81/// Header key: the conversation this was spawned from.
82pub const PARENT_CONVERSATION_ID: &str = "agdx.parent_conv";
83/// Header key: the root of the conversation tree.
84pub const ROOT_CONVERSATION_ID: &str = "agdx.root_conv";
85/// Header key: the agent this message is addressed to.
86pub const TARGET_AGENT_ID: &str = "agdx.to";
87/// Header key: reserved alias for an on-behalf-of subject. Signed delegation
88/// uses the envelope metadata key `on_behalf_of`.
89pub const DELEGATED_BY: &str = "agdx.on_behalf_of";
90/// Header key: dedup / reply-correlation key.
91pub const IDEMPOTENCY_KEY: &str = "agdx.idem";
92/// Header key: drop-dead time (epoch micros).
93pub const DEADLINE: &str = "agdx.deadline";
94/// Header key: LLM call cost in USD.
95pub const COST_USD: &str = "agdx.cost";
96/// Header key: the strictly-monotonic per-task fence the producer held (`u64`).
97/// A consumer rejects a log-resident effect whose fence is below the highest it
98/// has accepted for the task, so a stale-holder replay cannot re-fire.
99pub const FENCE: &str = "agdx.fence";
100/// Header key: the agent envelope's wire version (`u32` typed value).
101/// Rides outside the CBOR body so projections, a viewer, and rolling-upgrade
102/// consumers pick the decoder (and filter per version) without decoding the body.
103pub const AGENT_VERSION: &str = "agdx.av";
104
105// Memory scope. Carried as headers so the fold keys the read view on the scope,
106// not the topic, and one shared topic still resolves every context.
107/// Header key: the logical memory namespace the read view materializes under.
108pub const MEMORY_NAMESPACE: &str = "agdx.mem.ns";
109/// Header key: the user scope layer. Unscoped recall widens across it.
110pub const MEMORY_USER: &str = "agdx.mem.user";
111/// Header key: the app scope layer. Unscoped recall widens across it.
112pub const MEMORY_APP: &str = "agdx.mem.app";
113
114/// One typed user-header value as a record carries it.
115#[derive(Clone, Debug, PartialEq)]
116pub enum HeaderField {
117 Text(String),
118 Uint8(u8),
119 Uint32(u32),
120 Uint64(u64),
121 Float64(f64),
122}
123
124/// Who a record is addressed to. Broadcast rides `agdx.to` as the literal `*`
125/// and is never read as an agent id.
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub enum Addressee {
128 Agent(crate::agent::AgentId),
129 Broadcast,
130}
131
132impl Addressee {
133 /// The `agdx.to` text.
134 pub fn as_str(&self) -> &str {
135 match self {
136 Self::Agent(agent) => agent.as_str(),
137 Self::Broadcast => BROADCAST,
138 }
139 }
140
141 /// Read an `agdx.to` value. `*` is broadcast, anything else must be an
142 /// agent id.
143 pub fn parse(text: &str) -> Result<Self, crate::error::InvalidError> {
144 if text == BROADCAST {
145 return Ok(Self::Broadcast);
146 }
147 text.parse()
148 .map(Self::Agent)
149 .map_err(|_| crate::error::InvalidError::new("agdx.to is not an agent id or `*`"))
150 }
151}
152
153/// The `agdx.to` value that addresses every agent.
154pub const BROADCAST: &str = "*";
155
156/// The routing and provenance headers of one record. Envelope records carry
157/// the envelope version and content type. Generic records do not. Ids ride as
158/// canonical strings and numbers ride typed.
159#[derive(Clone, Debug, PartialEq)]
160pub struct RecordHeaders {
161 pub envelope: Option<(u32, crate::content::ContentType)>,
162 pub conversation: crate::agent::ConversationId,
163 pub parent: Option<crate::agent::ConversationId>,
164 pub root: Option<crate::agent::ConversationId>,
165 pub agent: Option<crate::agent::AgentId>,
166 pub addressee: Option<Addressee>,
167 pub causal_parent: Option<String>,
168 pub idempotency_key: Option<String>,
169 pub correlation: Option<String>,
170 pub fence: Option<u64>,
171 pub deadline_micros: Option<u64>,
172 pub input_tokens: Option<u64>,
173 pub output_tokens: Option<u64>,
174 pub cost_usd: Option<f64>,
175}
176
177impl RecordHeaders {
178 /// Headers of a generic record in `conversation`.
179 pub fn new(conversation: crate::agent::ConversationId) -> Self {
180 Self {
181 envelope: None,
182 conversation,
183 parent: None,
184 root: None,
185 agent: None,
186 addressee: None,
187 causal_parent: None,
188 idempotency_key: None,
189 correlation: None,
190 fence: None,
191 deadline_micros: None,
192 input_tokens: None,
193 output_tokens: None,
194 cost_usd: None,
195 }
196 }
197
198 /// Headers of an envelope record: version, content type, conversation,
199 /// ancestry, author, and addressee. A record without a target is
200 /// addressed to every agent when `broadcast` is set, as every record on a
201 /// shared session topic must be.
202 pub fn for_envelope(
203 envelope: &crate::agent::AgentEnvelope,
204 content_type: crate::content::ContentType,
205 broadcast: bool,
206 ) -> Self {
207 let mut headers = Self::new(envelope.conversation);
208 headers.envelope = Some((crate::codes::AGENT_OP_VERSION, content_type));
209 headers.parent = envelope.parent;
210 headers.root = envelope.root;
211 headers.agent = Some(envelope.source.clone());
212 headers.addressee = match &envelope.target {
213 Some(target) => Some(Addressee::Agent(target.clone())),
214 None if broadcast => Some(Addressee::Broadcast),
215 None => None,
216 };
217 headers
218 }
219
220 /// The header block, sorted by key.
221 pub fn encode(&self) -> Vec<(&'static str, HeaderField)> {
222 let text = |value: &dyn std::fmt::Display| HeaderField::Text(value.to_string());
223 let mut block = Vec::new();
224 if let Some((version, content_type)) = self.envelope {
225 block.push((AGENT_VERSION, HeaderField::Uint32(version)));
226 block.push((CONTENT_TYPE, HeaderField::Uint8(content_type.code())));
227 }
228 block.push((CONVERSATION_ID, text(&self.conversation)));
229 let optional: [(&'static str, Option<HeaderField>); 12] = [
230 (PARENT_CONVERSATION_ID, self.parent.map(|id| text(&id))),
231 (ROOT_CONVERSATION_ID, self.root.map(|id| text(&id))),
232 (
233 AGENT_ID,
234 self.agent
235 .as_ref()
236 .map(|agent| HeaderField::Text(agent.as_str().to_owned())),
237 ),
238 (
239 TARGET_AGENT_ID,
240 self.addressee
241 .as_ref()
242 .map(|to| HeaderField::Text(to.as_str().to_owned())),
243 ),
244 (
245 CAUSAL_PARENT,
246 self.causal_parent.clone().map(HeaderField::Text),
247 ),
248 (
249 IDEMPOTENCY_KEY,
250 self.idempotency_key.clone().map(HeaderField::Text),
251 ),
252 (
253 CORRELATION_ID,
254 self.correlation.clone().map(HeaderField::Text),
255 ),
256 (FENCE, self.fence.map(HeaderField::Uint64)),
257 (DEADLINE, self.deadline_micros.map(HeaderField::Uint64)),
258 (
259 USAGE_INPUT_TOKENS,
260 self.input_tokens.map(HeaderField::Uint64),
261 ),
262 (
263 USAGE_OUTPUT_TOKENS,
264 self.output_tokens.map(HeaderField::Uint64),
265 ),
266 (COST_USD, self.cost_usd.map(HeaderField::Float64)),
267 ];
268 block.extend(
269 optional
270 .into_iter()
271 .filter_map(|(key, value)| value.map(|value| (key, value))),
272 );
273 block.sort_by(|left, right| left.0.cmp(right.0));
274 block
275 }
276}