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
//! Host implementation of `murmur:runtime/inference@0.3.0#run-inference`.
//!
//! A hook component that imports this interface can run exactly one LLM
//! completion through the capsule's already-configured inference driver. The
//! call goes through [`crate::runtime::invoke_tool_component`] — the same
//! instantiate/type-check/call body an ordinary agent-loop turn uses — so there
//! is no second HTTP client, no second credential path, and no duplicated
//! driver logic. See `wit/hook/inference.wit` for the contract.
use std::{path::PathBuf, sync::Arc, time::Instant};
use serde_json::Value;
use wasmtime::{
component::{Component, Linker},
Engine,
};
use crate::{
agent::{
build_driver_payload, count_tokens, parse_driver_usage, DriverUsage,
DEFAULT_MAX_OUTPUT_TOKENS,
},
bindings::{
hook::murmur::runtime::inference::{InferenceRequest, InferenceResponse},
host::murmur::tool::run::{Status, ToolInput},
},
network_policy::{NetworkAllowRule, ToolCapabilityGrant},
runtime::{invoke_tool_component, ToolA2aWiring, ToolInvokeEnv},
spend::{SpendMeter, SpendRefusal},
trace::InferenceOrigin,
types::CapabilityPolicy,
};
/// The versioned instance name the host provides `run-inference` under. Hook
/// components that do not import it simply ignore the registration.
pub(crate) const INFERENCE_IFACE_VERSIONED: &str = "murmur:runtime/inference@0.3.0";
/// One completed `run-inference` call, buffered for the agent loop to write
/// through the session's `TraceWriter`/`OtelEmitter`.
///
/// Written for **every** call, success or failure, so a hook that retries after
/// a failure produces two separate, truthful records rather than one relabelled
/// span.
#[derive(Debug, Clone)]
pub(crate) struct HookInferenceRecord {
/// Carried verbatim into `trace.jsonl` and the OTel `capsule.inference`
/// span, distinguishing this from an agent-loop turn.
pub(crate) origin: InferenceOrigin,
pub(crate) input_tokens: u64,
pub(crate) output_tokens: u64,
/// `"end_turn"` when the driver returned a usable completion, `"error"`
/// otherwise.
pub(crate) decision: String,
pub(crate) duration_ms: u64,
/// The provider's own counts, when the driver reported them. Recorded beside
/// `input_tokens`/`output_tokens` — which stay this runtime's tiktoken counts —
/// and never substituted for them. `None` for a failed call, which has no response
/// to read a `usage` block from.
pub(crate) usage: Option<DriverUsage>,
}
/// One `run-inference` call a spend ceiling refused before dispatch, buffered for the agent loop
/// to write as a `spend_ceiling_reached` trace line. No [`HookInferenceRecord`] accompanies it:
/// no call was made.
#[derive(Debug, Clone)]
pub(crate) struct SpendRefusalRecord {
/// `hook:<name>` of the hook whose call was refused.
pub(crate) origin: String,
pub(crate) refusal: SpendRefusal,
}
/// Everything the host needs to run one inference-driver call from inside a
/// hook's wasm call.
///
/// The fields are owned clones of `CapsuleStoreState`'s, not borrows: the agent
/// loop holds the capsule store `&mut` for the whole turn that dispatches hooks,
/// and a `Linker` closure registered once at hook-instantiation time has to
/// outlive any single call anyway.
pub(crate) struct HookInferenceCtx {
pub(crate) driver_name: String,
pub(crate) driver_component: Component,
/// The manifest's primary `inference.model` — what `model: none` resolves to.
pub(crate) model: String,
pub(crate) engine: Engine,
pub(crate) accessible_workdir: PathBuf,
/// The session's bookkeeping directory, where a credential failure writes `out/result.txt`.
pub(crate) workdir: PathBuf,
pub(crate) inference_env: Vec<(String, String)>,
pub(crate) capability_policy: CapabilityPolicy,
pub(crate) network_allow_rules: Vec<NetworkAllowRule>,
/// The driver artifact's own per-artifact narrowing, cloned from the capsule store's
/// grant map. `None` = the driver declared no `capabilities:` block, so the ceiling
/// applies. Carried here so a hook's `run-inference` runs the driver under exactly the
/// grant the agent loop's own turns do, rather than an unnarrowed copy of the ceiling.
pub(crate) driver_grant: Option<ToolCapabilityGrant>,
/// The session's inference gateway, so a hook's `run-inference` reaches the provider exactly
/// as the agent loop's own turns do.
pub(crate) inference_gateway: Option<Arc<crate::inference_gateway::InferenceGateway>>,
/// The session's spend account — the same one the agent loop admits its turns against — so a
/// hook's completion counts toward, and is refused by, the same ceilings.
pub(crate) spend: Arc<SpendMeter>,
/// Buffered trace records, drained by the agent loop after hook dispatch.
pub(crate) records: std::sync::Mutex<Vec<HookInferenceRecord>>,
/// Calls refused by a spend ceiling, drained beside [`Self::records`].
pub(crate) spend_refusals: std::sync::Mutex<Vec<SpendRefusalRecord>>,
}
impl HookInferenceCtx {
/// Run one completion. `Err` is the string handed straight back to the guest
/// as the `result`'s error case.
async fn run(
&self,
origin: &str,
request: InferenceRequest,
) -> Result<InferenceResponse, String> {
// `none` resolves to the manifest's primary model; `some(m)` is sent
// verbatim and, if the driver rejects it, surfaces as `Err` with no
// retry — a caller wanting fallback calls again with `none` itself.
let messages = wire_messages(&request);
let model = request.model.unwrap_or_else(|| self.model.clone());
// Hook completions keep the built-in default cap rather than the manifest's
// `inference.max_tokens`: that field is documented as the *agent turn* output cap, and a
// small value chosen for the agent loop would silently truncate a compaction summary.
let payload = build_driver_payload(
&model,
DEFAULT_MAX_OUTPUT_TOKENS,
&messages,
&[],
request.system_prompt.as_deref().unwrap_or(""),
None,
// A hook's `run-inference` shares no prompt prefix with the agent loop — its own
// system prompt, no tools — so there is no prefix for a routing hint to point at,
// and `HookInferenceCtx` carries no capsule name or version to build one from.
None,
);
let payload_json = serde_json::to_string(&payload)
.map_err(|e| format!("failed to encode driver payload: {e}"))?;
let input_tokens = u64::from(count_tokens(&payload_json));
// Refused before dispatch: the guest gets the refusal text as `err`, and the trace gets a
// refusal line rather than an `inference` record for a call that never happened.
let admission = match self
.spend
.admit(input_tokens, u64::from(DEFAULT_MAX_OUTPUT_TOKENS))
{
Ok(admission) => admission,
Err(refusal) => {
let text = refusal.to_string();
if let Ok(mut refusals) = self.spend_refusals.lock() {
refusals.push(SpendRefusalRecord {
origin: origin.to_string(),
refusal,
});
}
return Err(text);
}
};
let started = Instant::now();
let outcome = self.dispatch(payload_json).await;
let duration_ms = started.elapsed().as_millis() as u64;
let (output_tokens, usage, result) = match outcome {
Ok((raw, text, usage)) => {
// `input-tokens`/`output-tokens` on the WIT response are documented as the
// runtime's own tiktoken counts, so a driver-reported `usage` never lands
// there — it goes to the trace record below and nowhere else.
let output_tokens = u64::from(count_tokens(&raw));
admission.settle(input_tokens, output_tokens);
(
output_tokens,
usage,
Ok(InferenceResponse {
text,
// Echoed, not driver-confirmed — the response never
// names the model back.
model_used: model.clone(),
input_tokens,
output_tokens,
}),
)
}
Err(err) => {
drop(admission);
(0, None, Err(err))
}
};
self.record(HookInferenceRecord {
origin: InferenceOrigin {
source: origin.to_string(),
model,
},
input_tokens,
output_tokens,
decision: if result.is_ok() { "end_turn" } else { "error" }.to_string(),
duration_ms,
usage,
});
result
}
/// Dispatch the payload through the shared tool-invocation path and pull the
/// completion text and the optional `usage` block out of the driver's response.
/// Returns `(raw, text, usage)`.
async fn dispatch(
&self,
payload_json: String,
) -> Result<(String, String, Option<DriverUsage>), String> {
let result = invoke_tool_component(
ToolInvokeEnv {
engine: &self.engine,
accessible_workdir: &self.accessible_workdir,
inference_env: &self.inference_env,
capability_policy: &self.capability_policy,
network_allow_rules: &self.network_allow_rules,
artifact_grant: self.driver_grant.as_ref(),
inference_gateway: self.inference_gateway.as_ref(),
},
// A hook's completion is not part of the user-facing turn: it must
// not stream chunks into the SSE stream or ask the user for input.
ToolA2aWiring::silent(),
&self.driver_name,
&self.driver_component,
ToolInput {
data: Some(payload_json),
log_path: None,
},
)
.await
.map_err(|e| format!("inference driver '{}' failed: {e}", self.driver_name))?;
let raw = result
.data
.or(result.summary)
.ok_or_else(|| "inference driver returned no data".to_string())?;
if !matches!(result.status, Status::Passed) {
if let Some(message) = self.credential_failure() {
return Err(message);
}
return Err(format!("inference driver returned an error: {raw}"));
}
let response: Value = serde_json::from_str(&raw)
.map_err(|e| format!("failed to parse inference driver response: {e}"))?;
if response.get("stop_reason").and_then(Value::as_str) == Some("error") {
if let Some(message) = self.credential_failure() {
return Err(message);
}
let err = response
.get("error")
.and_then(Value::as_str)
.unwrap_or("driver returned error");
return Err(format!("inference driver returned an error: {err}"));
}
let text = response_text(&response);
let usage = parse_driver_usage(&response);
Ok((raw, text, usage))
}
/// A credential rejection the gateway recorded for this call, reported as `E-RUN-027` and
/// written to `out/result.txt` in place of the driver's error, or `None` when there is none.
fn credential_failure(&self) -> Option<String> {
let message = self
.inference_gateway
.as_ref()
.and_then(|gateway| gateway.credential())
.and_then(|credential| credential.report_rejection())?;
if let Err(err) = crate::agent::write_result(&self.workdir, &format!("error: {message}")) {
eprintln!("{err}");
}
Some(message)
}
fn record(&self, record: HookInferenceRecord) {
if let Ok(mut guard) = self.records.lock() {
guard.push(record);
}
}
/// Take every record buffered since the last drain.
pub(crate) fn drain_records(&self) -> Vec<HookInferenceRecord> {
self.records
.lock()
.map(|mut g| std::mem::take(&mut *g))
.unwrap_or_default()
}
/// Take every spend refusal buffered since the last drain.
pub(crate) fn drain_spend_refusals(&self) -> Vec<SpendRefusalRecord> {
self.spend_refusals
.lock()
.map(|mut g| std::mem::take(&mut *g))
.unwrap_or_default()
}
}
/// Convert a request's WIT `message` records into driver wire messages.
///
/// The WIT `message.content` is a plain `string`, but the driver deserializes
/// each message's `content` into a `Vec<MurmurContentBlock>` — a bare string
/// fails serde with `invalid type: string, expected a sequence`. Wrap each
/// message's content in a single text block, matching `build_driver_payload`
/// and what the agent loop already sends every driver. `role` is passed through
/// unchanged: `murmur-hook-compact` has already normalized roles to
/// `user`/`assistant` before calling `run-inference`.
fn wire_messages(request: &InferenceRequest) -> Vec<Value> {
request
.messages
.iter()
.map(|m| {
serde_json::json!({
"role": m.role,
"content": [{"type": "text", "text": m.content}],
})
})
.collect()
}
/// Concatenate the `text` blocks of a driver response's `content` array, in
/// order. Matches the wire format in `docs/murmur-inference-message-format.md`.
fn response_text(response: &Value) -> String {
response
.get("content")
.and_then(Value::as_array)
.map(|blocks| {
blocks
.iter()
.filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
.filter_map(|b| b.get("text").and_then(Value::as_str))
.collect::<Vec<_>>()
.join("")
})
.unwrap_or_default()
}
/// Register `murmur:runtime/inference@0.3.0#run-inference` on a hook linker.
///
/// `origin` is the `hook:<name>` tag attached to every trace record this hook's
/// calls produce. `ctx` is `None` when the capsule has no usable inference
/// driver: the import is still *defined* (so a hook that imports it links and
/// runs), it just always returns the same `err`.
pub(crate) fn add_inference_to_linker<T: 'static>(
linker: &mut Linker<T>,
origin: String,
ctx: Option<Arc<HookInferenceCtx>>,
) -> Result<(), String> {
let origin = Arc::new(origin);
linker
.instance(INFERENCE_IFACE_VERSIONED)
.map_err(|e| format!("failed to define {INFERENCE_IFACE_VERSIONED}: {e}"))?
.func_wrap_async(
"run-inference",
move |_store: wasmtime::StoreContextMut<'_, T>, (request,): (InferenceRequest,)| {
let ctx = ctx.clone();
let origin = Arc::clone(&origin);
let fut: Box<
dyn std::future::Future<
Output = wasmtime::Result<(Result<InferenceResponse, String>,)>,
> + Send,
> = Box::new(async move {
let result = match ctx {
Some(ctx) => ctx.run(&origin, request).await,
// Wording tracks RuntimeError::DriverNotConfigured.
None => Err("inference driver is not configured; add \
inference.driver.artifact to murmur.yaml"
.to_string()),
};
Ok((result,))
});
fut
},
)
.map_err(|e| {
format!("failed to register {INFERENCE_IFACE_VERSIONED}#run-inference: {e}")
})?;
Ok(())
}
#[cfg(test)]
pub(crate) mod test_support {
use wasmtime::component::Component;
/// A hand-authored `murmur:tool/run@0.1.0` component double standing in for
/// an inference driver: it ignores its input entirely and returns `response`
/// as the `tool-result.data` string with the given `status`.
///
/// Written in WAT rather than compiled from Rust because this crate has no
/// wasm32-wasip2 build step — the same reason `hooks.rs` hand-authors its
/// lifecycle doubles. `run`'s result exceeds one flat value, so the core
/// function returns an i32 pointer to a `tool-result` it lays out by hand;
/// the offsets below are the canonical ABI's (record align 4: `status` 0,
/// `summary` 4, `data` 16, `data-path` 28, `truncated` 40, `metadata` 44).
pub(crate) fn driver_double(
engine: &wasmtime::Engine,
status: u32,
response: &str,
) -> Component {
let len = response.len();
let escaped: String = response.bytes().map(|b| format!("\\{b:02x}")).collect();
let wat = format!(
r#"(component
(core module $m
(memory (export "memory") 1)
(global $bump (mut i32) (i32.const 1024))
(func (export "realloc") (param i32 i32 i32 i32) (result i32)
(local $p i32)
(local.set $p (i32.and (i32.add (global.get $bump) (i32.const 7)) (i32.const -8)))
(global.set $bump (i32.add (local.get $p) (i32.add (local.get 3) (i32.const 8))))
(local.get $p))
(func (export "run") (param i32 i32 i32 i32 i32 i32) (result i32)
(i32.store8 (i32.const 128) (i32.const {status}))
(i32.store (i32.const 132) (i32.const 0))
(i32.store (i32.const 144) (i32.const 1))
(i32.store (i32.const 148) (i32.const 4096))
(i32.store (i32.const 152) (i32.const {len}))
(i32.store (i32.const 156) (i32.const 0))
(i32.store8 (i32.const 168) (i32.const 0))
(i32.store (i32.const 172) (i32.const 0))
(i32.store (i32.const 176) (i32.const 0))
(i32.const 128))
(data (i32.const 4096) "{escaped}")
)
(core instance $i (instantiate $m))
(alias core export $i "memory" (core memory $mem))
(alias core export $i "realloc" (core func $realloc))
(type $status (enum "passed" "failed" "error"))
(type $tool-input (record
(field "data" (option string))
(field "log-path" (option string))))
(type $tool-result (record
(field "status" $status)
(field "summary" (option string))
(field "data" (option string))
(field "data-path" (option string))
(field "truncated" bool)
(field "metadata" (list (tuple string string)))))
(type $ft (func (param "input" $tool-input) (result $tool-result)))
(func $run (type $ft)
(canon lift (core func $i "run") (memory $mem) (realloc $realloc) string-encoding=utf8))
(instance $ti
(export "status" (type $status))
(export "tool-input" (type $tool-input))
(export "tool-result" (type $tool-result))
(export "run" (func $run)))
(export "murmur:tool/run@0.1.0" (instance $ti))
)"#
);
let bytes = wat::parse_str(&wat).expect("driver double WAT parses");
Component::new(engine, &bytes).expect("driver double compiles")
}
}
#[cfg(test)]
mod tests {
use super::{test_support::driver_double, *};
use crate::bindings::hook::murmur::hook::lifecycle::Message;
use tempfile::TempDir;
const CANNED: &str =
r#"{"stop_reason":"end_turn","content":[{"type":"text","text":"compacted summary"}]}"#;
fn engine() -> Engine {
let mut config = wasmtime::Config::new();
config.wasm_component_model(true);
config.epoch_interruption(true);
Engine::new(&config).expect("engine builds")
}
fn ctx(engine: &Engine, workdir: &std::path::Path, driver: Component) -> HookInferenceCtx {
ctx_with_spend(engine, workdir, driver, Arc::new(SpendMeter::unlimited()))
}
fn ctx_with_spend(
engine: &Engine,
workdir: &std::path::Path,
driver: Component,
spend: Arc<SpendMeter>,
) -> HookInferenceCtx {
HookInferenceCtx {
driver_name: "mock-driver".to_string(),
driver_component: driver,
model: "manifest-model".to_string(),
engine: engine.clone(),
accessible_workdir: workdir.to_path_buf(),
workdir: workdir.to_path_buf(),
inference_env: Vec::new(),
capability_policy: CapabilityPolicy::default(),
network_allow_rules: Vec::new(),
driver_grant: None,
inference_gateway: None,
spend,
records: std::sync::Mutex::new(Vec::new()),
spend_refusals: std::sync::Mutex::new(Vec::new()),
}
}
fn request(model: Option<&str>) -> InferenceRequest {
InferenceRequest {
messages: vec![Message {
role: "user".to_string(),
content: "summarize this".to_string(),
id: None,
source_id: None,
}],
system_prompt: None,
model: model.map(str::to_string),
}
}
/// Token count of the payload `run` must have built for `model` — recomputed
/// here from the *same* `build_driver_payload` the agent loop uses. Asserting
/// `input_tokens` against it proves the resolved model really went onto the
/// wire, not just into `model-used`.
fn expected_input_tokens(model: &str) -> u64 {
let messages = vec![
serde_json::json!({"role":"user","content":[{"type":"text","text":"summarize this"}]}),
];
let payload = build_driver_payload(
model,
DEFAULT_MAX_OUTPUT_TOKENS,
&messages,
&[],
"",
None,
None,
);
u64::from(count_tokens(&serde_json::to_string(&payload).unwrap()))
}
fn block_on<F: std::future::Future>(f: F) -> F::Output {
tokio::runtime::Runtime::new().unwrap().block_on(f)
}
/// `model: none` resolves to the manifest's primary `inference.model`, the
/// call goes through the shared driver-invocation path, and the response
/// carries the driver's text plus host-computed token counts.
#[test]
fn run_inference_model_none_resolves_to_manifest_model() {
let dir = TempDir::new().unwrap();
let engine = engine();
let ctx = ctx(&engine, dir.path(), driver_double(&engine, 0, CANNED));
let resp = block_on(ctx.run("hook:test", request(None)))
.expect("the driver double returns a well-formed completion");
assert_eq!(resp.text, "compacted summary");
assert_eq!(resp.model_used, "manifest-model");
assert_eq!(resp.input_tokens, expected_input_tokens("manifest-model"));
assert_eq!(resp.output_tokens, u64::from(count_tokens(CANNED)));
let records = ctx.drain_records();
assert_eq!(records.len(), 1, "exactly one trace record per call");
assert_eq!(records[0].origin.source, "hook:test");
assert_eq!(records[0].origin.model, "manifest-model");
assert_eq!(records[0].decision, "end_turn");
assert!(ctx.drain_records().is_empty(), "drain is destructive");
}
/// `model: some(m)` sends `m` instead of the manifest model. `input_tokens`
/// is recomputed from a payload built with the override (whose name is a
/// different token length from the manifest model's), so this fails if the
/// override only reached `model-used`.
#[test]
fn run_inference_model_some_overrides_the_sent_model() {
let dir = TempDir::new().unwrap();
let engine = engine();
let ctx = ctx(&engine, dir.path(), driver_double(&engine, 0, CANNED));
let resp = block_on(ctx.run(
"hook:test",
request(Some("override-model-with-longer-name")),
))
.expect("override model still completes against the double");
assert_eq!(resp.model_used, "override-model-with-longer-name");
assert_eq!(
resp.input_tokens,
expected_input_tokens("override-model-with-longer-name")
);
assert_ne!(
expected_input_tokens("override-model-with-longer-name"),
expected_input_tokens("manifest-model"),
"the two model names must tokenize differently for this test to discriminate"
);
assert_eq!(
ctx.drain_records()[0].origin.model,
"override-model-with-longer-name"
);
}
/// A driver-reported error surfaces as `Err` and is **not** retried with any
/// other model — exactly one dispatch, one trace record, tagged `error`.
#[test]
fn run_inference_driver_error_is_err_with_no_retry() {
let dir = TempDir::new().unwrap();
let engine = engine();
let driver = driver_double(
&engine,
0,
r#"{"stop_reason":"error","error":"unknown model: nope"}"#,
);
let ctx = ctx(&engine, dir.path(), driver);
let err = block_on(ctx.run("hook:test", request(Some("nope"))))
.expect_err("a driver-reported error must not be swallowed");
assert!(err.contains("unknown model: nope"), "got: {err}");
let records = ctx.drain_records();
assert_eq!(records.len(), 1, "one attempt, no implicit fallback retry");
assert_eq!(records[0].decision, "error");
assert_eq!(
records[0].origin.model, "nope",
"the failed record must name the model that was actually attempted"
);
}
/// Regression: the driver deserializes each message's `content` into a
/// `Vec<MurmurContentBlock>`, so the host must send it as a JSON array of
/// `{"type":"text","text":…}` blocks, never a bare string. Fails if
/// `wire_messages` ever emits `content` as a plain string again — the shape
/// that made LLM compaction fail against every driver.
#[test]
fn run_inference_message_content_is_a_sequence_of_text_blocks() {
let req = InferenceRequest {
messages: vec![
Message {
role: "user".to_string(),
content: "hello".to_string(),
id: None,
source_id: None,
},
Message {
role: "assistant".to_string(),
content: "hi there".to_string(),
id: None,
source_id: None,
},
],
system_prompt: None,
model: None,
};
let messages = wire_messages(&req);
assert_eq!(messages.len(), 2);
for (msg, (role, text)) in messages
.iter()
.zip([("user", "hello"), ("assistant", "hi there")])
{
assert_eq!(msg["role"], role);
let content = msg["content"]
.as_array()
.expect("content must be a sequence of blocks, not a bare string");
assert_eq!(content.len(), 1, "one text block per message");
assert_eq!(content[0]["type"], "text");
assert_eq!(content[0]["text"], text);
}
}
/// Invariant: `message.id` and `message.source-id` never reach the provider.
///
/// `wire_messages` names the two fields it forwards rather than serializing the
/// record, so a field added to the WIT `message` is inert on the wire until someone
/// deliberately forwards it. A uuid at the head of a cached prefix is volatile
/// content and would defeat provider prompt-prefix caching on every request.
#[test]
fn message_id_and_source_id_are_stripped_from_a_hooks_inference_request() {
let req = InferenceRequest {
messages: vec![Message {
role: "user".to_string(),
content: "hello".to_string(),
id: Some("msg_0198f1c2d3e44a5b8c9d0e1f2a3b4c5d".to_string()),
source_id: Some("corpus:abc".to_string()),
}],
system_prompt: None,
model: None,
};
let messages = wire_messages(&req);
assert_eq!(messages.len(), 1);
let keys: Vec<&String> = messages[0]
.as_object()
.expect("a wire message is a JSON object")
.keys()
.collect();
assert_eq!(keys, vec!["content", "role"]);
let payload = build_driver_payload("m", 8192, &messages, &[], "sys", None, None);
let serialized = serde_json::to_string(&payload).unwrap();
assert!(!serialized.contains("msg_0198f1c2d3e44a5b8c9d0e1f2a3b4c5d"));
assert!(!serialized.contains("corpus:abc"));
assert!(!serialized.contains("source_id"));
assert!(!serialized.contains("source-id"));
}
/// A spend ceiling refuses a hook's completion before dispatch — both a ceiling too small for
/// the call and a session already latched by an earlier refusal. The guest gets the refusal
/// text, no `inference` record is buffered, and one refusal record names the hook.
#[test]
fn run_inference_refused_by_spend_ceiling() {
let dir = TempDir::new().unwrap();
let engine = engine();
let latched = Arc::new(SpendMeter::new(Some(1_000_000), None));
assert!(latched.admit(2_000_000, 0).is_err(), "latches the session");
for (case, meter) in [
("too small", Arc::new(SpendMeter::new(Some(10), None))),
("latched", latched),
] {
// A driver double that, had it been invoked, would have buffered an `error` record:
// `run` records every dispatched call, success or failure.
let ctx = ctx_with_spend(
&engine,
dir.path(),
driver_double(&engine, 2, "the driver was invoked"),
Arc::clone(&meter),
);
let err = block_on(ctx.run("hook:compact", request(None)))
.expect_err("a refused call is an err");
assert!(
err.starts_with("spend ceiling reached: inference.max_session_tokens is"),
"{case}: {err}"
);
assert!(
err.contains("retrying will not get past it"),
"{case}: {err}"
);
assert!(!err.contains("the driver was invoked"), "{case}: {err}");
assert!(
ctx.drain_records().is_empty(),
"{case}: no inference record"
);
let refusals = ctx.drain_spend_refusals();
assert_eq!(refusals.len(), 1, "{case}");
assert_eq!(refusals[0].origin, "hook:compact", "{case}");
assert_eq!(
refusals[0].refusal.limit,
crate::spend::SpendLimit::Session,
"{case}"
);
assert_eq!(meter.used(), 0, "{case}: nothing was charged");
assert!(!meter.has_open_admission(), "{case}");
}
}
/// A non-`passed` tool status from the driver is also an `Err`.
#[test]
fn run_inference_failed_driver_status_is_err() {
let dir = TempDir::new().unwrap();
let engine = engine();
let ctx = ctx(&engine, dir.path(), driver_double(&engine, 2, "boom"));
let err =
block_on(ctx.run("hook:test", request(None))).expect_err("status: error must surface");
assert!(err.contains("boom"), "got: {err}");
assert_eq!(ctx.drain_records()[0].decision, "error");
}
}