web-cortex-framework 2.5.0__tar.gz → 2.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/Cargo.lock +2 -2
  2. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/Cargo.toml +1 -1
  3. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/PKG-INFO +7 -5
  4. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/README.md +6 -4
  5. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/agent.rs +33 -3
  6. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/app.rs +81 -9
  7. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/devices.rs +64 -7
  8. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/errors.rs +4 -1
  9. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/ledger.rs +5 -1
  10. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/lib.rs +22 -1
  11. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/manifest.rs +36 -1
  12. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/mcp.rs +44 -5
  13. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/server.rs +66 -18
  14. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/status.rs +110 -11
  15. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/ws.rs +58 -17
  16. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/tests/diagnostics.rs +68 -0
  17. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/pyproject.toml +1 -1
  18. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/__init__.py +1 -1
  19. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/cli.py +29 -4
  20. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/client.py +14 -2
  21. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/diagnostics.py +32 -8
  22. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/errors.py +1 -1
  23. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/starters.py +2 -0
  24. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/LICENSE +0 -0
  25. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/Cargo.toml +0 -0
  26. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/agent/provider.rs +0 -0
  27. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/agent/registry.rs +0 -0
  28. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/agent/session.rs +0 -0
  29. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/agent/vision.rs +0 -0
  30. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/audit.rs +0 -0
  31. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/auth.rs +0 -0
  32. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/bridge.rs +0 -0
  33. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/context.rs +0 -0
  34. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/db.rs +0 -0
  35. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/files.rs +0 -0
  36. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/flow.rs +0 -0
  37. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/http.rs +0 -0
  38. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/middleware.rs +0 -0
  39. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/openapi.rs +0 -0
  40. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/router.rs +0 -0
  41. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/templates.rs +0 -0
  42. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-core/src/typegen.rs +0 -0
  43. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-py/Cargo.toml +0 -0
  44. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-py/src/behaviour.rs +0 -0
  45. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/crates/webcortex-py/src/lib.rs +0 -0
  46. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/_bridge.py +0 -0
  47. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/app.py +0 -0
  48. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/contextpack.py +0 -0
  49. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/media.py +0 -0
  50. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.2}/python/webcortex/schema.py +0 -0
@@ -2662,7 +2662,7 @@ dependencies = [
2662
2662
 
2663
2663
  [[package]]
2664
2664
  name = "webcortex-core"
2665
- version = "2.5.0"
2665
+ version = "2.5.2"
2666
2666
  dependencies = [
2667
2667
  "base64 0.23.1",
2668
2668
  "bytes",
@@ -2690,7 +2690,7 @@ dependencies = [
2690
2690
 
2691
2691
  [[package]]
2692
2692
  name = "webcortex-py"
2693
- version = "2.5.0"
2693
+ version = "2.5.2"
2694
2694
  dependencies = [
2695
2695
  "bytes",
2696
2696
  "futures",
@@ -3,7 +3,7 @@ members = ["crates/webcortex-core", "crates/webcortex-py"]
3
3
  resolver = "3"
4
4
 
5
5
  [workspace.package]
6
- version = "2.5.0"
6
+ version = "2.5.2"
7
7
  edition = "2024"
8
8
  license = "Apache-2.0"
9
9
  rust-version = "1.88"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: web-cortex-framework
3
- Version: 2.5.0
3
+ Version: 2.5.2
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -115,11 +115,13 @@ prints the lot in a form a coding model can extend.
115
115
  ## Start here
116
116
 
117
117
  ```bash
118
- uv venv --python 3.13 && uv pip install web-cortex-framework
118
+ uv venv --python 3.13 && source .venv/bin/activate # puts `webcortex` on PATH
119
+ uv pip install web-cortex-framework
119
120
 
120
- webcortex new myapp # --template api | fullstack | agent | behaviour | orchestration
121
+ webcortex new myapp # --template api | fullstack | agent | behaviour | orchestration | robotics | hub
121
122
  cd myapp
122
123
  export WEBCORTEX_API_KEY=$(webcortex keygen)
124
+ webcortex doctor # anything else to set first: other keys, model provider keys
123
125
  webcortex dev
124
126
  ```
125
127
 
@@ -136,7 +138,7 @@ interpreter at request time*. In practice that is most of a CRUD API and all of
136
138
  an orchestration.
137
139
 
138
140
  ```
139
- $ webcortex check
141
+ $ webcortex dev # the boot banner
140
142
  19 routes, 17 served without touching Python
141
143
  ```
142
144
 
@@ -525,7 +527,7 @@ tested, the known limits, and what v2 added to the surface.
525
527
 
526
528
  ## Status
527
529
 
528
- v2.5.0. Working and tested: the manifest IR, router, native ops (static /
530
+ v2.5.2. Working and tested: the manifest IR, router, native ops (static /
529
531
  query / proxy / page / files / flow), the free-threaded Python bridge,
530
532
  authentication and scopes, rate limiting, CORS, security headers, graceful
531
533
  shutdown, Behaviours with concurrent leaves, the agent runtime with handoffs,
@@ -87,11 +87,13 @@ prints the lot in a form a coding model can extend.
87
87
  ## Start here
88
88
 
89
89
  ```bash
90
- uv venv --python 3.13 && uv pip install web-cortex-framework
90
+ uv venv --python 3.13 && source .venv/bin/activate # puts `webcortex` on PATH
91
+ uv pip install web-cortex-framework
91
92
 
92
- webcortex new myapp # --template api | fullstack | agent | behaviour | orchestration
93
+ webcortex new myapp # --template api | fullstack | agent | behaviour | orchestration | robotics | hub
93
94
  cd myapp
94
95
  export WEBCORTEX_API_KEY=$(webcortex keygen)
96
+ webcortex doctor # anything else to set first: other keys, model provider keys
95
97
  webcortex dev
96
98
  ```
97
99
 
@@ -108,7 +110,7 @@ interpreter at request time*. In practice that is most of a CRUD API and all of
108
110
  an orchestration.
109
111
 
110
112
  ```
111
- $ webcortex check
113
+ $ webcortex dev # the boot banner
112
114
  19 routes, 17 served without touching Python
113
115
  ```
114
116
 
@@ -497,7 +499,7 @@ tested, the known limits, and what v2 added to the surface.
497
499
 
498
500
  ## Status
499
501
 
500
- v2.5.0. Working and tested: the manifest IR, router, native ops (static /
502
+ v2.5.2. Working and tested: the manifest IR, router, native ops (static /
501
503
  query / proxy / page / files / flow), the free-threaded Python bridge,
502
504
  authentication and scopes, rate limiting, CORS, security headers, graceful
503
505
  shutdown, Behaviours with concurrent leaves, the agent runtime with handoffs,
@@ -510,6 +510,9 @@ impl AgentRuntime {
510
510
  let SuspendedRun { state: mut st, calls, gated, mut results, approval_id, .. } = suspended;
511
511
  let call = &calls[gated];
512
512
  app.recorder().run_started(&st.run_id, &st.def.name, &st.caller.id, st.depth);
513
+ // The approved call runs before `drive` does; dropped there, the run
514
+ // is cancelled just the same.
515
+ let mut guard = CancelGuard { app, run_id: Some(st.run_id.clone()) };
513
516
 
514
517
  if approve {
515
518
  self.audit.record(AuditEvent::approval_decided(
@@ -539,17 +542,29 @@ impl AgentRuntime {
539
542
  results.push(tool_result(&call.id, &json!({"error": msg}), true));
540
543
  }
541
544
 
542
- match self.execute_calls(app, &mut st, &calls, gated + 1, results).await {
545
+ let result = match self.execute_calls(app, &mut st, &calls, gated + 1, results).await {
543
546
  CallsOutcome::Done(results) => {
544
547
  st.conversation.messages.push(Message { role: "user".into(), content: Value::Array(results) });
545
548
  self.drive(app, st).await
546
549
  }
547
550
  CallsOutcome::Suspended { gated, results } => self.suspend(app, st, calls, gated, results),
548
- }
551
+ };
552
+ guard.run_id = None;
553
+ result
549
554
  }
550
555
 
551
556
  /// The main loop. Everything mutable lives in `st`.
552
- async fn drive(&self, app: &App, mut st: RunState) -> RunResult {
557
+ async fn drive(&self, app: &App, st: RunState) -> RunResult {
558
+ // The future driving a run is dropped when its request times out or
559
+ // its client goes away; the run then never reaches `finish`. The
560
+ // guard takes it out of the status view's in-flight list either way.
561
+ let mut guard = CancelGuard { app, run_id: Some(st.run_id.clone()) };
562
+ let result = self.drive_steps(app, st).await;
563
+ guard.run_id = None;
564
+ result
565
+ }
566
+
567
+ async fn drive_steps(&self, app: &App, mut st: RunState) -> RunResult {
553
568
  let max_steps = st.entry.max_steps.unwrap_or(12);
554
569
 
555
570
  loop {
@@ -1169,6 +1184,21 @@ fn outcome_code(status: RunStatus, steps: &[Step]) -> Option<&'static str> {
1169
1184
  }
1170
1185
  }
1171
1186
 
1187
+ /// Reports a run as cancelled if it is dropped before `drive` returns.
1188
+ struct CancelGuard<'a> {
1189
+ app: &'a App,
1190
+ run_id: Option<String>,
1191
+ }
1192
+
1193
+ impl Drop for CancelGuard<'_> {
1194
+ fn drop(&mut self) {
1195
+ if let Some(run_id) = self.run_id.take() {
1196
+ tracing::info!(run_id = %run_id, "agent run cancelled before it finished (timeout or client gone)");
1197
+ self.app.recorder().run_cancelled(&run_id);
1198
+ }
1199
+ }
1200
+ }
1201
+
1172
1202
  /// Hand a finished run to the live status view.
1173
1203
  fn record_finished(app: &App, r: &RunResult, cost_usd: Option<f64>) {
1174
1204
  let status = serde_json::to_value(r.status).ok();
@@ -195,8 +195,14 @@ impl App {
195
195
  approvals: Mutex::new(HashMap::new()),
196
196
  self_ref: std::sync::OnceLock::new(),
197
197
  halt: Mutex::new(manifest_start_halted.then(|| {
198
+ // The boot time, not 0: a reader computing "halted for" from
199
+ // since_unix would otherwise see fifty years.
200
+ let since = std::time::SystemTime::now()
201
+ .duration_since(std::time::UNIX_EPOCH)
202
+ .map(|d| d.as_secs())
203
+ .unwrap_or(0);
198
204
  serde_json::json!({"reason": "started halted; release to enable actuators",
199
- "by": "boot", "since_unix": 0})
205
+ "by": "boot", "since_unix": since})
200
206
  })),
201
207
  devices,
202
208
  recorder,
@@ -327,7 +333,7 @@ impl App {
327
333
  /// same scopes as the route it is mounted on.
328
334
  pub fn authorize(&self, method: &str, path: &str, principal: &Principal) -> Result<&Route, WebCortexResponse> {
329
335
  let matched = self.router.find(method, path).map_err(|e| match e {
330
- MatchError::NotFound => WebCortexResponse::coded(404, "WC201", format!("no route for {method} {path}")),
336
+ MatchError::NotFound => self.no_route(method, path),
331
337
  MatchError::MethodNotAllowed => WebCortexResponse::coded(405, "WC202", format!("{method} not allowed on {path}")),
332
338
  })?;
333
339
  let route = self
@@ -440,12 +446,47 @@ impl App {
440
446
  all
441
447
  }
442
448
 
449
+ /// The 404 for a path no route matches. Under a device prefix, naming a
450
+ /// device that was never declared, it is WC501 "unknown device" rather
451
+ /// than WC201, whose hint sends the reader looking for a route.
452
+ fn no_route(&self, method: &str, path: &str) -> WebCortexResponse {
453
+ if let Some(name) = self.undeclared_device_in(path) {
454
+ return WebCortexResponse::coded(
455
+ 404,
456
+ "WC501",
457
+ format!("no device named {name:?} (no route for {method} {path})"),
458
+ );
459
+ }
460
+ WebCortexResponse::coded(404, "WC201", format!("no route for {method} {path}"))
461
+ }
462
+
463
+ /// The device segment of `path`, when `path` sits under the prefix of a
464
+ /// declared device's routes and names a device that does not exist.
465
+ fn undeclared_device_in<'p>(&self, path: &'p str) -> Option<&'p str> {
466
+ if self.devices().is_empty() {
467
+ return None;
468
+ }
469
+ for route in &self.manifest.routes {
470
+ let Op::Device { device, .. } = &route.op else { continue };
471
+ let Some(at) = route.path.find(&format!("/{device}/")) else { continue };
472
+ let prefix = &route.path[..at];
473
+ if prefix.is_empty() {
474
+ continue;
475
+ }
476
+ let Some(rest) = path.strip_prefix(prefix).and_then(|r| r.strip_prefix('/')) else { continue };
477
+ let Some((name, _)) = rest.split_once('/') else { continue };
478
+ if !name.is_empty() && name.len() <= 64 && self.devices().get(name).is_none() {
479
+ return Some(name);
480
+ }
481
+ return None;
482
+ }
483
+ None
484
+ }
485
+
443
486
  pub async fn dispatch(&self, mut req: WebCortexRequest) -> WebCortexResponse {
444
487
  let matched = match self.router.find(&req.method, &req.path) {
445
488
  Ok(m) => m,
446
- Err(MatchError::NotFound) => {
447
- return WebCortexResponse::coded(404, "WC201", format!("no route for {} {}", req.method, req.path));
448
- }
489
+ Err(MatchError::NotFound) => return self.no_route(&req.method, &req.path),
449
490
  Err(MatchError::MethodNotAllowed) => {
450
491
  let allowed = self.router.allowed_methods(&req.path).join(", ");
451
492
  let mut res = WebCortexResponse::coded(
@@ -1053,10 +1094,30 @@ impl App {
1053
1094
 
1054
1095
  let mut path_params = std::collections::BTreeMap::new();
1055
1096
  for seg in route.path.split('/') {
1056
- if let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}'))
1057
- && let Some(v) = obj.get(name) {
1058
- path_params.insert(name.to_string(), json_to_path_string(v));
1097
+ let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) else {
1098
+ continue;
1099
+ };
1100
+ let value = obj.get(name).filter(|v| !v.is_null()).map(json_to_path_string);
1101
+ match value {
1102
+ Some(v) if !v.is_empty() => {
1103
+ path_params.insert(name.to_string(), v);
1104
+ }
1105
+ // Without this, `/items/{id}` became `/items/` and the call
1106
+ // failed as "no route" (WC201), which sends a model looking
1107
+ // for a route that exists instead of the argument it left out.
1108
+ _ => {
1109
+ let res = WebCortexResponse::coded(
1110
+ 422,
1111
+ "WC206",
1112
+ format!("missing required argument {name:?} (a path parameter of {} {})", route.method, route.path),
1113
+ );
1114
+ return Err(format!(
1115
+ "tool {tool_name} failed with {}: {}",
1116
+ res.status,
1117
+ String::from_utf8_lossy(&res.body)
1118
+ ));
1059
1119
  }
1120
+ }
1060
1121
  }
1061
1122
 
1062
1123
  let concrete_path = substitute_path(&route.path, &path_params);
@@ -1128,7 +1189,18 @@ pub fn run_result_response(result: &RunResult) -> WebCortexResponse {
1128
1189
  _ => 200,
1129
1190
  };
1130
1191
  match serde_json::to_value(result) {
1131
- Ok(v) => WebCortexResponse::json(status, &v),
1192
+ Ok(v) => {
1193
+ let mut res = WebCortexResponse::json(status, &v);
1194
+ // A failed run is an error response like any other: the header
1195
+ // carries its code, so the request log and the status view record
1196
+ // the run's own code (WC304, …) rather than the generic one for 502.
1197
+ if status >= 400
1198
+ && let Some(code) = result.code.as_deref()
1199
+ {
1200
+ res.headers.push(("x-webcortex-error".into(), code.to_string()));
1201
+ }
1202
+ res
1203
+ }
1132
1204
  Err(e) => WebCortexResponse::coded(500, "WC001", e.to_string()),
1133
1205
  }
1134
1206
  }
@@ -36,6 +36,8 @@ pub const MAX_TELEMETRY_BYTES: usize = 64 * 1024;
36
36
  const KEEP_INSIGHTS: usize = 32;
37
37
  /// Events buffered per subscriber before a slow one starts missing them.
38
38
  const CHANNEL_CAPACITY: usize = 64;
39
+ /// Arrival times kept for the frame rate, whatever `keep` is.
40
+ const RATE_WINDOW: usize = 32;
39
41
 
40
42
  pub fn now_ms() -> u64 {
41
43
  std::time::SystemTime::now()
@@ -124,12 +126,18 @@ pub fn sniff(data: &[u8]) -> Option<&'static str> {
124
126
  pub struct Device {
125
127
  pub def: DeviceDef,
126
128
  frames: Mutex<VecDeque<Arc<Frame>>>,
129
+ /// When the newest frames arrived, for `recent_fps`. Separate from the
130
+ /// ring, which may hold a single frame (`keep=1`) and so no interval.
131
+ arrivals: Mutex<VecDeque<u64>>,
127
132
  telemetry: Mutex<Option<(u64, Arc<Value>)>>,
128
133
  insights: Mutex<VecDeque<Value>>,
129
134
  seq: AtomicU64,
130
135
  last_ingest: Mutex<Option<Instant>>,
131
136
  frames_in: AtomicU64,
132
137
  frames_dropped: AtomicU64,
138
+ /// Frames refused as invalid (not an image, empty, over max_frame_bytes,
139
+ /// sent to a sensor). Over a WebSocket these are otherwise invisible.
140
+ frames_rejected: AtomicU64,
133
141
  tx: broadcast::Sender<Event>,
134
142
  }
135
143
 
@@ -139,12 +147,14 @@ impl Device {
139
147
  Self {
140
148
  def,
141
149
  frames: Mutex::new(VecDeque::new()),
150
+ arrivals: Mutex::new(VecDeque::new()),
142
151
  telemetry: Mutex::new(None),
143
152
  insights: Mutex::new(VecDeque::new()),
144
153
  seq: AtomicU64::new(0),
145
154
  last_ingest: Mutex::new(None),
146
155
  frames_in: AtomicU64::new(0),
147
156
  frames_dropped: AtomicU64::new(0),
157
+ frames_rejected: AtomicU64::new(0),
148
158
  tx,
149
159
  }
150
160
  }
@@ -152,6 +162,14 @@ impl Device {
152
162
  /// Accept one encoded frame. The type is sniffed from the bytes; the
153
163
  /// declared content type is only a fallback for the error message.
154
164
  pub fn push_frame(&self, data: Bytes) -> Result<u64, IngestError> {
165
+ let result = self.accept_frame(data);
166
+ if matches!(result, Err(IngestError::Invalid(_))) {
167
+ self.frames_rejected.fetch_add(1, Ordering::Relaxed);
168
+ }
169
+ result
170
+ }
171
+
172
+ fn accept_frame(&self, data: Bytes) -> Result<u64, IngestError> {
155
173
  if self.def.kind == DeviceKind::Sensor {
156
174
  return Err(IngestError::Invalid(format!(
157
175
  "{:?} is a sensor; send telemetry, not frames",
@@ -172,7 +190,9 @@ impl Device {
172
190
  IngestError::Invalid("frame is not a PNG, JPEG, GIF or WebP image".into())
173
191
  })?;
174
192
  {
175
- let interval = Duration::from_secs_f64(1.0 / self.def.max_fps);
193
+ // try_: a vanishingly small max_fps overflows a Duration, and the
194
+ // panic took the request (or the device's socket) down with it.
195
+ let interval = Duration::try_from_secs_f64(1.0 / self.def.max_fps).unwrap_or(Duration::MAX);
176
196
  let mut last = self.last_ingest.lock().unwrap_or_else(|p| p.into_inner());
177
197
  if last.is_some_and(|t| t.elapsed() < interval) {
178
198
  self.frames_dropped.fetch_add(1, Ordering::Relaxed);
@@ -186,6 +206,13 @@ impl Device {
186
206
  fn store(&self, media_type: &'static str, data: Bytes) -> u64 {
187
207
  let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
188
208
  let frame = Arc::new(Frame { seq, media_type, data, at_ms: now_ms() });
209
+ {
210
+ let mut arrivals = self.arrivals.lock().unwrap_or_else(|p| p.into_inner());
211
+ arrivals.push_back(frame.at_ms);
212
+ while arrivals.len() > RATE_WINDOW {
213
+ arrivals.pop_front();
214
+ }
215
+ }
189
216
  {
190
217
  let mut frames = self.frames.lock().unwrap_or_else(|p| p.into_inner());
191
218
  frames.push_back(frame.clone());
@@ -240,15 +267,15 @@ impl Device {
240
267
  self.tx.subscribe()
241
268
  }
242
269
 
243
- /// Frames per second over the frames still held in the ring, or 0 when
244
- /// fewer than two are held or the newest is over ten seconds old.
270
+ /// Frames per second over the last few arrivals, or 0 when fewer than two
271
+ /// have arrived or the newest is over ten seconds old.
245
272
  pub fn recent_fps(&self) -> f64 {
246
- let frames = self.frames.lock().unwrap_or_else(|p| p.into_inner());
247
- let (Some(first), Some(last)) = (frames.front(), frames.back()) else { return 0.0 };
248
- if frames.len() < 2 || now_ms().saturating_sub(last.at_ms) > 10_000 || last.at_ms <= first.at_ms {
273
+ let arrivals = self.arrivals.lock().unwrap_or_else(|p| p.into_inner());
274
+ let (Some(&first), Some(&last)) = (arrivals.front(), arrivals.back()) else { return 0.0 };
275
+ if arrivals.len() < 2 || now_ms().saturating_sub(last) > 10_000 || last <= first {
249
276
  return 0.0;
250
277
  }
251
- let fps = (frames.len() - 1) as f64 * 1000.0 / (last.at_ms - first.at_ms) as f64;
278
+ let fps = (arrivals.len() - 1) as f64 * 1000.0 / (last - first) as f64;
252
279
  (fps * 100.0).round() / 100.0
253
280
  }
254
281
 
@@ -262,6 +289,7 @@ impl Device {
262
289
  "telemetry_at_ms": self.telemetry().map(|(at, _)| at),
263
290
  "frames_in": self.frames_in.load(Ordering::Relaxed),
264
291
  "frames_dropped": self.frames_dropped.load(Ordering::Relaxed),
292
+ "frames_rejected": self.frames_rejected.load(Ordering::Relaxed),
265
293
  "subscribers": self.tx.receiver_count(),
266
294
  "insights": self.insights.lock().unwrap_or_else(|p| p.into_inner()).len(),
267
295
  "max_fps": self.def.max_fps,
@@ -314,6 +342,7 @@ impl DeviceHub {
314
342
  "max_fps": d.def.max_fps,
315
343
  "frames_in": d.frames_in.load(Ordering::Relaxed),
316
344
  "frames_dropped": d.frames_dropped.load(Ordering::Relaxed),
345
+ "frames_rejected": d.frames_rejected.load(Ordering::Relaxed),
317
346
  "last_frame_age_ms": latest.map(|f| now.saturating_sub(f.at_ms)),
318
347
  "last_telemetry_age_ms": d.telemetry().map(|(at, _)| now.saturating_sub(at)),
319
348
  "subscribers": d.tx.receiver_count(),
@@ -723,6 +752,34 @@ mod tests {
723
752
  assert!(d.push_telemetry(big).is_err());
724
753
  }
725
754
 
755
+ #[test]
756
+ fn the_frame_rate_is_measured_even_when_only_one_frame_is_kept() {
757
+ // 2.5.1 measured fps over the ring, so a keep=1 camera always read 0.
758
+ let d = Device::new(def(1000.0, 1));
759
+ for _ in 0..5 {
760
+ d.push_frame(Bytes::from_static(PNG)).unwrap();
761
+ std::thread::sleep(Duration::from_millis(20));
762
+ }
763
+ let fps = d.recent_fps();
764
+ assert!(fps > 10.0 && fps < 60.0, "fps {fps}");
765
+ }
766
+
767
+ #[test]
768
+ fn a_tiny_max_fps_drops_frames_instead_of_panicking() {
769
+ let d = Device::new(def(1e-300, 2));
770
+ d.push_frame(Bytes::from_static(PNG)).unwrap();
771
+ assert_eq!(d.push_frame(Bytes::from_static(PNG)), Err(IngestError::TooFast));
772
+ }
773
+
774
+ #[test]
775
+ fn rejected_frames_are_counted() {
776
+ let d = Device::new(def(1000.0, 2));
777
+ assert!(d.push_frame(Bytes::from_static(b"nope")).is_err());
778
+ assert!(d.push_frame(Bytes::new()).is_err());
779
+ assert_eq!(d.describe()["frames_rejected"], 2);
780
+ assert_eq!(d.describe()["frames_in"], 0);
781
+ }
782
+
726
783
  #[test]
727
784
  fn a_sensor_takes_telemetry_not_frames() {
728
785
  let mut s = def(10.0, 4);
@@ -108,6 +108,8 @@ pub static CATALOGUE: &[ErrorInfo] = &[
108
108
  "The request conflicts with the current state of the resource; re-read it and retry."),
109
109
  e!("WC215", "http", Some(503), "Unavailable",
110
110
  "A subsystem this route needs is not running in this process (for example the agent runtime). Check the server log at boot."),
111
+ e!("WC216", "http", Some(408), "Request body too slow",
112
+ "The client announced a body but did not finish sending it within request_timeout (agent_timeout on agent, behaviour and flow routes). Send the whole body promptly, or raise the limit on WebCortex(...)."),
111
113
 
112
114
  // ---- WC3xx agents and providers -------------------------------------
113
115
  e!("WC300", "agent", Some(502), "Agent run failed",
@@ -167,7 +169,7 @@ pub static CATALOGUE: &[ErrorInfo] = &[
167
169
  e!("WC504", "devices", Some(429), "Frame faster than max_fps",
168
170
  "The device is sending faster than its max_fps; the frame was dropped. Slow the sender or raise max_fps."),
169
171
  e!("WC505", "devices", Some(422), "Invalid frame or telemetry",
170
- "The frame is not a PNG/JPEG/GIF/WebP, is over max_frame_bytes, or the telemetry is not a JSON body."),
172
+ "The frame is not a PNG/JPEG/GIF/WebP, is over max_frame_bytes, or the telemetry is not a JSON body (a body that is not JSON at all is answered 400; the rest 422)."),
171
173
  e!("WC506", "devices", Some(502), "Camera unreachable",
172
174
  "A pulled IP camera did not answer with a snapshot. Check its URL, its bearer_env, and that it is reachable from the server."),
173
175
 
@@ -208,6 +210,7 @@ pub fn code_for_status(status: u16) -> &'static str {
208
210
  403 => "WC602",
209
211
  404 => "WC207",
210
212
  405 => "WC202",
213
+ 408 => "WC216",
211
214
  409 => "WC214",
212
215
  413 => "WC204",
213
216
  422 => "WC206",
@@ -155,10 +155,12 @@ impl Ledger {
155
155
  }
156
156
  }
157
157
 
158
+ // `+ 0.0`: an empty f64 sum is -0.0, which serialises as "-0.0".
158
159
  let priced_cost: f64 = entries
159
160
  .iter()
160
161
  .filter_map(|(k, t)| price_for(&k.model).map(|p| t.cost_usd(&p)))
161
- .sum();
162
+ .sum::<f64>()
163
+ + 0.0;
162
164
 
163
165
  serde_json::json!({
164
166
  "since_unix": self.started_unix,
@@ -196,6 +198,8 @@ mod tests {
196
198
  assert_eq!(snap["by_caller"]["agent:a"]["cache_read_tokens"], 3);
197
199
  assert!(snap["estimated_cost_usd"].is_null(), "unpriced must not be reported as free");
198
200
  assert_eq!(snap["unpriced_models"].as_array().unwrap().len(), 2);
201
+ // 2.5.0 reported "priced_cost_usd": -0.0 when nothing was priced.
202
+ assert_eq!(serde_json::to_string(&snap["priced_cost_usd"]).unwrap(), "0.0");
199
203
  }
200
204
 
201
205
  #[test]
@@ -46,11 +46,32 @@ pub fn init_tracing(default_level: &str) {
46
46
  use tracing_subscriber::{EnvFilter, fmt};
47
47
  let filter = EnvFilter::try_from_env("WEBCORTEX_LOG")
48
48
  .unwrap_or_else(|_| EnvFilter::new(default_level));
49
- let _ = fmt().with_env_filter(filter).with_target(false).try_init();
49
+ // Colour only on a terminal: redirected to a file or a platform's log
50
+ // collector, escape codes are noise around every field. NO_COLOR is honoured
51
+ // when set to anything but the empty string, as no-color.org specifies.
52
+ let ansi = use_colour(
53
+ std::io::IsTerminal::is_terminal(&std::io::stdout()),
54
+ std::env::var_os("NO_COLOR").as_deref(),
55
+ );
56
+ let _ = fmt().with_env_filter(filter).with_target(false).with_ansi(ansi).try_init();
57
+ }
58
+
59
+ fn use_colour(terminal: bool, no_color: Option<&std::ffi::OsStr>) -> bool {
60
+ terminal && no_color.is_none_or(|v| v.is_empty())
50
61
  }
51
62
 
52
63
  #[cfg(test)]
53
64
  mod tests {
65
+ #[test]
66
+ fn colour_only_on_a_terminal_without_no_color() {
67
+ use std::ffi::OsStr;
68
+ assert!(super::use_colour(true, None));
69
+ assert!(!super::use_colour(false, None));
70
+ assert!(!super::use_colour(true, Some(OsStr::new("1"))));
71
+ // no-color.org: an empty NO_COLOR does not disable colour.
72
+ assert!(super::use_colour(true, Some(OsStr::new(""))));
73
+ }
74
+
54
75
  use super::*;
55
76
  use manifest::derive_tool_name;
56
77
 
@@ -1377,11 +1377,25 @@ fn agent_names_all(m: &Manifest) -> std::collections::HashSet<&str> {
1377
1377
 
1378
1378
  /// Closest match by edit distance, for "did you mean" hints on typos.
1379
1379
  fn nearest(needle: &str, haystack: &std::collections::HashSet<String>) -> Option<String> {
1380
+ // A handler's function name (`move`) is the usual mistake for its derived
1381
+ // tool name (`create_arm_move`): prefer a name containing the needle as
1382
+ // whole `_`-separated words over one that is merely a few edits away.
1383
+ let words = |c: &str| {
1384
+ let needle = needle.trim_matches('_');
1385
+ !needle.is_empty()
1386
+ && c != needle
1387
+ && (c.starts_with(&format!("{needle}_"))
1388
+ || c.ends_with(&format!("_{needle}"))
1389
+ || c.contains(&format!("_{needle}_")))
1390
+ };
1391
+ if let Some(c) = haystack.iter().filter(|c| words(c)).min_by_key(|c| (c.len(), c.as_str())) {
1392
+ return Some(c.clone());
1393
+ }
1380
1394
  haystack
1381
1395
  .iter()
1382
1396
  .map(|c| (edit_distance(needle, c), c))
1383
1397
  .filter(|(d, _)| *d <= 3)
1384
- .min_by_key(|(d, _)| *d)
1398
+ .min_by_key(|(d, c)| (*d, c.as_str()))
1385
1399
  .map(|(_, c)| c.clone())
1386
1400
  }
1387
1401
 
@@ -1430,3 +1444,24 @@ pub fn derive_tool_name(method: &str, path: &str) -> String {
1430
1444
  }
1431
1445
  parts.join("_")
1432
1446
  }
1447
+
1448
+ #[cfg(test)]
1449
+ mod tests {
1450
+ use super::nearest;
1451
+
1452
+ fn set(names: &[&str]) -> std::collections::HashSet<String> {
1453
+ names.iter().map(|s| s.to_string()).collect()
1454
+ }
1455
+
1456
+ #[test]
1457
+ fn a_handler_name_suggests_its_derived_tool_name() {
1458
+ // 2.5.0 suggested the agent "mover" for tools=["move"], one edit away,
1459
+ // when the route's tool was create_arm_move.
1460
+ let tools = set(&["mover", "create_arm_move", "list_things", "get_typed_by_n"]);
1461
+ assert_eq!(nearest("move", &tools).as_deref(), Some("create_arm_move"));
1462
+ assert_eq!(nearest("typed", &tools).as_deref(), Some("get_typed_by_n"));
1463
+ // A typo still finds its near neighbour.
1464
+ assert_eq!(nearest("list_thing", &tools).as_deref(), Some("list_things"));
1465
+ assert_eq!(nearest("zzzzzzzzzz", &tools), None);
1466
+ }
1467
+ }