web-cortex-framework 2.5.0__tar.gz → 2.5.1__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.1}/Cargo.lock +2 -2
  2. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/Cargo.toml +1 -1
  3. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/PKG-INFO +7 -5
  4. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/README.md +6 -4
  5. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/app.rs +42 -5
  6. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/ledger.rs +5 -1
  7. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/lib.rs +4 -1
  8. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/manifest.rs +36 -1
  9. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/mcp.rs +44 -5
  10. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/server.rs +13 -1
  11. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/status.rs +35 -11
  12. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/ws.rs +37 -15
  13. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/tests/diagnostics.rs +68 -0
  14. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/pyproject.toml +1 -1
  15. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/__init__.py +1 -1
  16. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/cli.py +29 -4
  17. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/diagnostics.py +30 -7
  18. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/starters.py +2 -0
  19. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/LICENSE +0 -0
  20. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/Cargo.toml +0 -0
  21. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/agent/provider.rs +0 -0
  22. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/agent/registry.rs +0 -0
  23. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/agent/session.rs +0 -0
  24. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/agent/vision.rs +0 -0
  25. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/agent.rs +0 -0
  26. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/audit.rs +0 -0
  27. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/auth.rs +0 -0
  28. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/bridge.rs +0 -0
  29. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/context.rs +0 -0
  30. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/db.rs +0 -0
  31. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/devices.rs +0 -0
  32. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/errors.rs +0 -0
  33. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/files.rs +0 -0
  34. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/flow.rs +0 -0
  35. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/http.rs +0 -0
  36. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/middleware.rs +0 -0
  37. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/openapi.rs +0 -0
  38. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/router.rs +0 -0
  39. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/templates.rs +0 -0
  40. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-core/src/typegen.rs +0 -0
  41. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-py/Cargo.toml +0 -0
  42. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-py/src/behaviour.rs +0 -0
  43. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/crates/webcortex-py/src/lib.rs +0 -0
  44. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/_bridge.py +0 -0
  45. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/app.py +0 -0
  46. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/client.py +0 -0
  47. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/contextpack.py +0 -0
  48. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/errors.py +0 -0
  49. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/python/webcortex/media.py +0 -0
  50. {web_cortex_framework-2.5.0 → web_cortex_framework-2.5.1}/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.1"
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.1"
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.1"
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.1
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.1. 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.1. 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,
@@ -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,
@@ -1053,10 +1059,30 @@ impl App {
1053
1059
 
1054
1060
  let mut path_params = std::collections::BTreeMap::new();
1055
1061
  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));
1062
+ let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) else {
1063
+ continue;
1064
+ };
1065
+ let value = obj.get(name).filter(|v| !v.is_null()).map(json_to_path_string);
1066
+ match value {
1067
+ Some(v) if !v.is_empty() => {
1068
+ path_params.insert(name.to_string(), v);
1059
1069
  }
1070
+ // Without this, `/items/{id}` became `/items/` and the call
1071
+ // failed as "no route" (WC201), which sends a model looking
1072
+ // for a route that exists instead of the argument it left out.
1073
+ _ => {
1074
+ let res = WebCortexResponse::coded(
1075
+ 422,
1076
+ "WC206",
1077
+ format!("missing required argument {name:?} (a path parameter of {} {})", route.method, route.path),
1078
+ );
1079
+ return Err(format!(
1080
+ "tool {tool_name} failed with {}: {}",
1081
+ res.status,
1082
+ String::from_utf8_lossy(&res.body)
1083
+ ));
1084
+ }
1085
+ }
1060
1086
  }
1061
1087
 
1062
1088
  let concrete_path = substitute_path(&route.path, &path_params);
@@ -1128,7 +1154,18 @@ pub fn run_result_response(result: &RunResult) -> WebCortexResponse {
1128
1154
  _ => 200,
1129
1155
  };
1130
1156
  match serde_json::to_value(result) {
1131
- Ok(v) => WebCortexResponse::json(status, &v),
1157
+ Ok(v) => {
1158
+ let mut res = WebCortexResponse::json(status, &v);
1159
+ // A failed run is an error response like any other: the header
1160
+ // carries its code, so the request log and the status view record
1161
+ // the run's own code (WC304, …) rather than the generic one for 502.
1162
+ if status >= 400
1163
+ && let Some(code) = result.code.as_deref()
1164
+ {
1165
+ res.headers.push(("x-webcortex-error".into(), code.to_string()));
1166
+ }
1167
+ res
1168
+ }
1132
1169
  Err(e) => WebCortexResponse::coded(500, "WC001", e.to_string()),
1133
1170
  }
1134
1171
  }
@@ -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,7 +46,10 @@ 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
+ let ansi = std::io::IsTerminal::is_terminal(&std::io::stdout()) && std::env::var_os("NO_COLOR").is_none();
52
+ let _ = fmt().with_env_filter(filter).with_target(false).with_ansi(ansi).try_init();
50
53
  }
51
54
 
52
55
  #[cfg(test)]
@@ -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
+ }
@@ -125,7 +125,16 @@ async fn handle_one(app: &App, req: Value, caller: &Principal, request_id: &str)
125
125
  Ok(value) => json!({"jsonrpc": "2.0", "id": id, "result": value}),
126
126
  Err((code, message)) => {
127
127
  let wc = if code == -32601 { "WC212" } else { "WC205" };
128
- error_obj(id, code, message, wc)
128
+ let mut obj = error_obj(id, code, message, wc);
129
+ if code == -32601 {
130
+ // WC212's own hint lists control-plane GET paths, which is no
131
+ // help to an MCP client that sent an unknown method.
132
+ obj["error"]["data"]["hint"] = json!(
133
+ "This MCP server implements initialize, ping, tools/list, tools/call, \
134
+ resources/list and resources/read."
135
+ );
136
+ }
137
+ obj
129
138
  }
130
139
  })
131
140
  }
@@ -186,7 +195,7 @@ fn builtin_tools(app: &App) -> Vec<Value> {
186
195
  in flight and recent (steps, tokens, cost, outcome), budgets, e-stop, devices \
187
196
  and watchers. Pass section to get one part only.",
188
197
  "inputSchema": {"type": "object", "properties": {
189
- "section": {"type": "string", "enum": ["requests", "errors", "agents", "usage", "budgets", "estop", "devices"]}
198
+ "section": {"type": "string", "enum": STATUS_SECTIONS}
190
199
  }},
191
200
  "annotations": {"readOnlyHint": true, "idempotentHint": true, "destructiveHint": false,
192
201
  "openWorldHint": false, "requiresApproval": false, "actuator": false},
@@ -205,6 +214,18 @@ fn builtin_tools(app: &App) -> Vec<Value> {
205
214
  out
206
215
  }
207
216
 
217
+ /// The sections `webcortex_status` can return on their own.
218
+ const STATUS_SECTIONS: [&str; 7] = ["requests", "errors", "agents", "usage", "budgets", "estop", "devices"];
219
+
220
+ /// A built-in tool's error result with a hint of its own, shaped like [`tool_error`].
221
+ fn builtin_error(code: &str, message: String, hint: &str) -> Value {
222
+ json!({
223
+ "content": [{"type": "text", "text": format!("{message}\n\n[{code}] {hint}")}],
224
+ "structuredContent": {"error": {"code": code, "message": message, "hint": hint}},
225
+ "isError": true,
226
+ })
227
+ }
228
+
208
229
  /// A built-in tool call, or `None` when `name` is not one (or an app tool shadows it).
209
230
  fn call_builtin(app: &App, name: &str, args: &Value) -> Option<Value> {
210
231
  if app.route_for_tool(name).is_some() {
@@ -213,13 +234,31 @@ fn call_builtin(app: &App, name: &str, args: &Value) -> Option<Value> {
213
234
  let value = match name {
214
235
  STATUS_TOOL => {
215
236
  let all = app.status();
216
- match args.get("section").and_then(|s| s.as_str()) {
217
- Some(section) if all.get(section).is_some() => json!({ section: all[section] }),
218
- _ => all,
237
+ match args.get("section").and_then(|s| s.as_str()).filter(|s| !s.is_empty()) {
238
+ None => all,
239
+ Some(section) if STATUS_SECTIONS.contains(&section) && all.get(section).is_some() => {
240
+ json!({ section: all[section] })
241
+ }
242
+ // A typo used to return the whole document silently, so the
243
+ // caller could not tell its filter had been ignored.
244
+ Some(section) => {
245
+ return Some(builtin_error(
246
+ "WC206",
247
+ format!("unknown status section {section:?}"),
248
+ &format!("Pass one of {}, or omit section for everything.", STATUS_SECTIONS.join(", ")),
249
+ ));
250
+ }
219
251
  }
220
252
  }
221
253
  EXPLAIN_TOOL => {
222
254
  let code = args.get("code").and_then(|c| c.as_str()).unwrap_or("").trim().to_ascii_uppercase();
255
+ if code.is_empty() {
256
+ return Some(builtin_error(
257
+ "WC206",
258
+ "missing required argument \"code\"".into(),
259
+ "Pass the code to explain, e.g. {\"code\": \"WC402\"}; read webcortex://errors for the list.",
260
+ ));
261
+ }
223
262
  match crate::errors::lookup(&code) {
224
263
  Some(e) => json!({"code": e.code, "title": e.title, "category": e.category,
225
264
  "status": e.status, "hint": e.hint}),
@@ -168,6 +168,13 @@ async fn handle(app: Arc<App>, req: Request<Incoming>, client_ip: String) -> Res
168
168
  let method = req.method().as_str().to_string();
169
169
  let uri = req.uri().clone();
170
170
  let path = uri.path().to_string();
171
+ // An agent's WebSocket rides on its POST route, so its GET upgrade is
172
+ // counted against that route rather than as "(no route)".
173
+ let ws_upgrade = req
174
+ .headers()
175
+ .get(hyper::header::UPGRADE)
176
+ .and_then(|v| v.to_str().ok())
177
+ .is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
171
178
 
172
179
  // A caller's id is echoed and logged, so only a short, plain one is kept.
173
180
  let request_id = req
@@ -215,7 +222,12 @@ async fn handle(app: Arc<App>, req: Request<Incoming>, client_ip: String) -> Res
215
222
  let target = if path.starts_with(&app.manifest.server.control_prefix) {
216
223
  crate::status::Target::Control
217
224
  } else {
218
- match app.route_id_for(&method, &path) {
225
+ let id = app.route_id_for(&method, &path).or_else(|| {
226
+ (ws_upgrade && method == "GET")
227
+ .then(|| app.route_id_for("POST", &path))
228
+ .flatten()
229
+ });
230
+ match id {
219
231
  Some(id) => crate::status::Target::Route(id),
220
232
  None => crate::status::Target::Unmatched,
221
233
  }
@@ -31,7 +31,8 @@ pub fn unix_ms() -> u64 {
31
31
 
32
32
  /// Latency in power-of-two microsecond buckets: bucket `i` holds samples in
33
33
  /// `[2^(i-1), 2^i)` µs. Percentiles are reported as the bucket's upper bound,
34
- /// so they are never optimistic and within 2x of the truth.
34
+ /// so they are never optimistic and within 2x of the truth — capped at the
35
+ /// largest sample actually seen, so a percentile never exceeds `max_ms`.
35
36
  struct Histogram {
36
37
  buckets: [AtomicU64; BUCKETS],
37
38
  }
@@ -46,28 +47,33 @@ impl Histogram {
46
47
  self.buckets[i.min(BUCKETS - 1)].fetch_add(1, Relaxed);
47
48
  }
48
49
 
49
- fn percentile_ms(&self, counts: &[u64; BUCKETS], total: u64, p: f64) -> f64 {
50
+ fn percentile_ms(&self, counts: &[u64; BUCKETS], total: u64, p: f64, max_us: u64) -> f64 {
50
51
  if total == 0 {
51
52
  return 0.0;
52
53
  }
53
54
  let target = ((total as f64) * p).ceil().max(1.0) as u64;
54
55
  let mut seen = 0;
56
+ let mut upper = 1u64 << (BUCKETS - 1);
55
57
  for (i, c) in counts.iter().enumerate() {
56
58
  seen += c;
57
59
  if seen >= target {
58
- return (1u64 << i) as f64 / 1000.0;
60
+ upper = 1u64 << i;
61
+ break;
59
62
  }
60
63
  }
61
- (1u64 << (BUCKETS - 1)) as f64 / 1000.0
64
+ // A bucket's upper bound can lie above every sample in it; the true
65
+ // maximum is known exactly, and no percentile can exceed it.
66
+ round3(upper.min(max_us.max(1)) as f64 / 1000.0)
62
67
  }
63
68
 
64
- fn summary(&self) -> Value {
69
+ /// p50/p95/p99, none of them above `max_us`, the largest sample recorded.
70
+ fn summary(&self, max_us: u64) -> Value {
65
71
  let counts: [u64; BUCKETS] = std::array::from_fn(|i| self.buckets[i].load(Relaxed));
66
72
  let total: u64 = counts.iter().sum();
67
73
  json!({
68
- "p50_ms": self.percentile_ms(&counts, total, 0.50),
69
- "p95_ms": self.percentile_ms(&counts, total, 0.95),
70
- "p99_ms": self.percentile_ms(&counts, total, 0.99),
74
+ "p50_ms": self.percentile_ms(&counts, total, 0.50, max_us),
75
+ "p95_ms": self.percentile_ms(&counts, total, 0.95, max_us),
76
+ "p99_ms": self.percentile_ms(&counts, total, 0.99, max_us),
71
77
  })
72
78
  }
73
79
  }
@@ -143,6 +149,7 @@ impl Slot {
143
149
  return None;
144
150
  }
145
151
  let total = self.total_us.load(Relaxed);
152
+ let max_us = self.max_us.load(Relaxed);
146
153
  let mut v = json!({
147
154
  "route": &*self.label,
148
155
  "requests": count,
@@ -154,9 +161,9 @@ impl Slot {
154
161
  "5xx": self.by_class[4].load(Relaxed),
155
162
  },
156
163
  "mean_ms": round3(total as f64 / count as f64 / 1000.0),
157
- "max_ms": round3(self.max_us.load(Relaxed) as f64 / 1000.0),
164
+ "max_ms": round3(max_us as f64 / 1000.0),
158
165
  });
159
- if let (Value::Object(m), Value::Object(l)) = (&mut v, self.latency.summary()) {
166
+ if let (Value::Object(m), Value::Object(l)) = (&mut v, self.latency.summary(max_us)) {
160
167
  m.extend(l);
161
168
  }
162
169
  Some(v)
@@ -659,12 +666,29 @@ mod tests {
659
666
  h.record(100);
660
667
  }
661
668
  h.record(50_000);
662
- let s = h.summary();
669
+ let s = h.summary(50_000);
663
670
  assert_eq!(s["p50_ms"], 0.128);
664
671
  assert!(s["p99_ms"].as_f64().unwrap() <= 0.128);
665
672
  assert!(s["p99_ms"].as_f64().unwrap() >= 0.1);
666
673
  }
667
674
 
675
+ #[test]
676
+ fn no_percentile_exceeds_the_maximum() {
677
+ // 2.5.0 printed "p95 0.256ms max 0.162ms": the bucket's upper bound
678
+ // was reported even when every sample sat well below it.
679
+ let slot = Slot::new("GET /".into());
680
+ slot.record(200, 162);
681
+ slot.record(200, 19);
682
+ let v = slot.describe().unwrap();
683
+ let max = v["max_ms"].as_f64().unwrap();
684
+ assert_eq!(max, 0.162);
685
+ for p in ["p50_ms", "p95_ms", "p99_ms"] {
686
+ assert!(v[p].as_f64().unwrap() <= max, "{p} {} > max {max}", v[p]);
687
+ }
688
+ assert_eq!(v["p95_ms"], 0.162);
689
+ assert_eq!(v["p50_ms"], 0.032);
690
+ }
691
+
668
692
  #[test]
669
693
  fn truncation_respects_char_boundaries() {
670
694
  assert_eq!(truncate("abc", 5), "abc");
@@ -138,8 +138,15 @@ fn text(v: Value) -> Message {
138
138
  Message::Text(v.to_string().into())
139
139
  }
140
140
 
141
- fn error(message: impl Into<String>) -> Message {
142
- text(json!({"type": "error", "message": message.into()}))
141
+ /// An error message on an open socket: the same `code` and `hint` an HTTP
142
+ /// error body carries, so a device or agent client can branch on the code.
143
+ fn error(code: &str, message: impl Into<String>) -> Message {
144
+ text(json!({
145
+ "type": "error",
146
+ "message": message.into(),
147
+ "code": code,
148
+ "hint": crate::errors::hint(code),
149
+ }))
143
150
  }
144
151
 
145
152
  async fn ingest(app: Arc<App>, name: String, principal: Principal, mut ws: Socket) {
@@ -152,11 +159,11 @@ async fn ingest(app: Arc<App>, name: String, principal: Principal, mut ws: Socke
152
159
  // Dropping a frame that came too fast is the point of max_fps,
153
160
  // not news worth a message per frame.
154
161
  Ok(_) | Err(IngestError::TooFast) => None,
155
- Err(e) => Some(error(e.message())),
162
+ Err(e) => Some(error(e.code(), e.message())),
156
163
  },
157
164
  Ok(Message::Text(t)) => match serde_json::from_str::<Value>(t.as_str()) {
158
- Ok(v) => device.push_telemetry(v).err().map(|e| error(e.message())),
159
- Err(e) => Some(error(format!("telemetry must be JSON: {e}"))),
165
+ Ok(v) => device.push_telemetry(v).err().map(|e| error(e.code(), e.message())),
166
+ Err(e) => Some(error("WC505", format!("telemetry must be JSON: {e}"))),
160
167
  },
161
168
  Ok(Message::Close(_)) | Err(_) => break,
162
169
  Ok(_) => None,
@@ -241,8 +248,8 @@ async fn agent_session(app: Arc<App>, agent: String, principal: Principal, ws: S
241
248
  };
242
249
  let turn = match parse_turn(&raw, &principal) {
243
250
  Ok(t) => t,
244
- Err(e) => {
245
- if out.send(error(e)).await.is_err() {
251
+ Err((code, e)) => {
252
+ if out.send(error(code, e)).await.is_err() {
246
253
  break;
247
254
  }
248
255
  continue;
@@ -275,8 +282,8 @@ async fn agent_session(app: Arc<App>, agent: String, principal: Principal, ws: S
275
282
  }
276
283
  let reply = match outcome {
277
284
  Ok(Ok(result)) => text(json!({"type": "result", "result": result})),
278
- Ok(Err(e)) => error(e),
279
- Err(_) => error("the run exceeded agent_timeout_secs"),
285
+ Ok(Err(e)) => error(crate::errors::classify_run_error(&e), e),
286
+ Err(_) => error("WC203", "the run exceeded agent_timeout_secs"),
280
287
  };
281
288
  if out.send(reply).await.is_err() {
282
289
  break;
@@ -292,21 +299,22 @@ struct Turn {
292
299
  reset: bool,
293
300
  }
294
301
 
295
- fn parse_turn(raw: &str, principal: &Principal) -> Result<Turn, String> {
296
- let body: Value = serde_json::from_str(raw).map_err(|e| format!("send JSON: {e}"))?;
302
+ /// A turn, or the code and message of why it cannot be run.
303
+ fn parse_turn(raw: &str, principal: &Principal) -> Result<Turn, (&'static str, String)> {
304
+ let body: Value = serde_json::from_str(raw).map_err(|e| ("WC306", format!("send JSON: {e}")))?;
297
305
  let input = body
298
306
  .get("input")
299
307
  .and_then(|v| v.as_str())
300
- .ok_or("each message needs an 'input' string")?
308
+ .ok_or(("WC306", "each message needs an 'input' string".to_string()))?
301
309
  .to_string();
302
- let images = crate::agent::vision::input_images(body.get("images"))?;
310
+ let images = crate::agent::vision::input_images(body.get("images")).map_err(|e| ("WC313", e))?;
303
311
  let session_id = body
304
312
  .get("session_id")
305
313
  .and_then(|v| v.as_str())
306
314
  .filter(|s| !s.is_empty())
307
315
  .map(str::to_string);
308
316
  if session_id.is_some() && principal.root_is_anonymous() {
309
- return Err("sessions need an authenticated caller".into());
317
+ return Err(("WC607", "sessions need an authenticated caller".into()));
310
318
  }
311
319
  let reset = body.get("reset").and_then(|v| v.as_bool()).unwrap_or(false);
312
320
  Ok(Turn { input, images, session_id, reset })
@@ -327,12 +335,26 @@ mod tests {
327
335
  assert!(!is_upgrade(&h));
328
336
  }
329
337
 
338
+ #[test]
339
+ fn socket_errors_carry_a_code_and_its_hint() {
340
+ let anon = Principal::anonymous();
341
+ assert_eq!(parse_turn("not json", &anon).unwrap_err().0, "WC306");
342
+ assert_eq!(parse_turn(r#"{"inptu": 1}"#, &anon).unwrap_err().0, "WC306");
343
+ assert_eq!(parse_turn(r#"{"input": "x", "session_id": "s"}"#, &anon).unwrap_err().0, "WC607");
344
+ let Message::Text(t) = error("WC505", "telemetry must be JSON") else { panic!("text") };
345
+ let v: Value = serde_json::from_str(t.as_str()).unwrap();
346
+ assert_eq!(v["type"], "error");
347
+ assert_eq!(v["code"], "WC505");
348
+ assert_eq!(v["hint"], crate::errors::hint("WC505"));
349
+ assert_eq!(v["message"], "telemetry must be JSON");
350
+ }
351
+
330
352
  #[test]
331
353
  fn a_turn_needs_input_and_valid_images() {
332
354
  let anon = Principal::anonymous();
333
355
  assert!(parse_turn("{}", &anon).is_err());
334
356
  assert!(parse_turn("nope", &anon).is_err());
335
- assert!(parse_turn(r#"{"input": "hi", "session_id": "s"}"#, &anon).unwrap_err().contains("authenticated"));
357
+ assert!(parse_turn(r#"{"input": "hi", "session_id": "s"}"#, &anon).unwrap_err().1.contains("authenticated"));
336
358
  let t = parse_turn(r#"{"input": "hi"}"#, &anon).unwrap();
337
359
  assert_eq!(t.input, "hi");
338
360
  assert!(parse_turn(r#"{"input": "hi", "images": [{"url": "ftp://x"}]}"#, &anon).is_err());
@@ -161,3 +161,71 @@ async fn mcp_hides_the_status_view_from_a_caller_without_admin_once_auth_exists(
161
161
  let res = mcp::handle(&app, read, &reader).await.json_value();
162
162
  assert!(res["error"].is_object());
163
163
  }
164
+
165
+ #[tokio::test]
166
+ async fn a_failed_run_over_http_sends_its_own_code_in_the_header() {
167
+ // 2.5.0 sent no x-webcortex-error on a failed run's 502, so the request log
168
+ // and the status view recorded the generic WC300 beside the run's WC304.
169
+ let app = app().await;
170
+ let mut req = WebCortexRequest::synthetic("POST", "/agents/desk");
171
+ req.body = serde_json::to_vec(&json!({"input": "fail:anthropic 529: overloaded"})).unwrap().into();
172
+ let res = app.dispatch(req).await;
173
+ assert_eq!(res.status, 502);
174
+ assert_eq!(res.json_value()["code"], "WC304");
175
+ assert_eq!(res.error_code().as_deref(), Some("WC304"));
176
+
177
+ // A limit is an outcome, not an error: no header on its 200.
178
+ let mut req = WebCortexRequest::synthetic("POST", "/agents/tight");
179
+ req.body = serde_json::to_vec(&json!({"input": "tool:ping {}"})).unwrap().into();
180
+ let res = app.dispatch(req).await;
181
+ assert_eq!(res.status, 200);
182
+ assert!(!res.headers.iter().any(|(k, _)| k == "x-webcortex-error"));
183
+ }
184
+
185
+ #[tokio::test]
186
+ async fn a_tool_call_missing_a_path_argument_is_wc206_not_no_route() {
187
+ // 2.5.0 built "/items/" from {} and failed with WC201 "no route", which
188
+ // sends a model hunting for a route instead of the argument it omitted.
189
+ let manifest: Manifest = serde_json::from_value(json!({
190
+ "name": "args",
191
+ "routes": [
192
+ {"id": 0, "method": "GET", "path": "/items/{id}", "op": {"kind": "static", "body": {"ok": true}},
193
+ "tool": {"expose": true, "name": "get_item"}}
194
+ ]
195
+ }))
196
+ .expect("manifest");
197
+ let app = App::build_without_python(manifest).await.expect("app").into_arc();
198
+ for args in [json!({}), json!({"id": null}), json!({"id": ""})] {
199
+ let err = app.call_tool("get_item", &args, vec![]).await.unwrap_err();
200
+ assert!(err.contains("failed with 422"), "{err}");
201
+ assert_eq!(webcortex_core::errors::code_in(&err), Some("WC206"), "{err}");
202
+ assert!(err.contains("\\\"id\\\""), "names the argument: {err}");
203
+ }
204
+ assert_eq!(app.call_tool("get_item", &json!({"id": 7}), vec![]).await.unwrap(), json!({"ok": true}));
205
+
206
+ let who = Principal::anonymous();
207
+ let body = br#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_item","arguments":{}}}"#;
208
+ let res = mcp::handle(&app, body, &who).await.json_value();
209
+ assert_eq!(res["result"]["structuredContent"]["error"]["code"], "WC206");
210
+ }
211
+
212
+ #[tokio::test]
213
+ async fn mcp_builtins_refuse_a_bad_section_or_a_missing_code() {
214
+ let app = app().await;
215
+ let who = Principal::anonymous();
216
+ let call = |name: &str, args: Value| {
217
+ serde_json::to_vec(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
218
+ "params": {"name": name, "arguments": args}})).unwrap()
219
+ };
220
+ let res = mcp::handle(&app, &call(mcp::STATUS_TOOL, json!({"section": "bogus"})), &who).await.json_value();
221
+ assert_eq!(res["result"]["isError"], true);
222
+ assert_eq!(res["result"]["structuredContent"]["error"]["code"], "WC206");
223
+ assert!(res["result"]["structuredContent"]["error"]["hint"].as_str().unwrap().contains("requests"));
224
+
225
+ let res = mcp::handle(&app, &call(mcp::EXPLAIN_TOOL, json!({})), &who).await.json_value();
226
+ assert_eq!(res["result"]["structuredContent"]["error"]["code"], "WC206");
227
+
228
+ let res = mcp::handle(&app, br#"{"jsonrpc":"2.0","id":9,"method":"nosuch"}"#, &who).await.json_value();
229
+ assert_eq!(res["error"]["code"], -32601);
230
+ assert!(res["error"]["data"]["hint"].as_str().unwrap().contains("tools/call"));
231
+ }
@@ -7,7 +7,7 @@ build-backend = "maturin"
7
7
  # The split is for ergonomics, the same way djangorestframework imports as
8
8
  # `rest_framework`.
9
9
  name = "web-cortex-framework"
10
- version = "2.5.0"
10
+ version = "2.5.1"
11
11
  description = "A Rust-cored Python web framework where every route is also an agent tool."
12
12
  readme = "README.md"
13
13
  requires-python = ">=3.12"
@@ -25,7 +25,7 @@ def doctor(app: "WebCortex", *, online: bool = False, url: str | None = None,
25
25
  return app.doctor(online=online, url=url, key=key)
26
26
 
27
27
 
28
- __version__ = "2.5.0"
28
+ __version__ = "2.5.1"
29
29
 
30
30
  __all__ = [
31
31
  "WebCortex",
@@ -61,12 +61,17 @@ def _load_app(target: str) -> Any:
61
61
  inside = [str(Path(f.filename).resolve()).startswith(package) for f in frames]
62
62
  user = [f for f, mine in zip(frames, inside) if not mine]
63
63
  where = f" (at {user[-1].filename}:{user[-1].lineno})" if user else ""
64
+ if isinstance(e, SyntaxError) and e.filename:
65
+ # The traceback of a SyntaxError ends inside importlib; the error
66
+ # itself knows the file and line that failed to parse.
67
+ where = f" (at {e.filename}:{e.lineno})"
64
68
  detail = f"{type(e).__name__}: {e}{where}"
65
69
  # A ValueError raised by webcortex itself is a declaration it refused.
66
70
  declaration = isinstance(e, ValueError) and bool(inside) and inside[-1]
67
71
  code = "WC101" if declaration else "WC102"
68
72
  hint = ("A declaration in the app is invalid; the message names it and the location is the "
69
- "line that declared it.") if declaration else None
73
+ "line that declared it.") if declaration else (
74
+ f"Importing {path} raised. Run `python {path}` to see the full traceback.")
70
75
  raise CLIError(code, f"loading {target} failed: {detail}", hint) from None
71
76
 
72
77
  if not hasattr(module, attr):
@@ -119,7 +124,9 @@ def _banner(app: Any) -> None:
119
124
  security = app.security_report()
120
125
  gil = "free-threaded" if free_threaded() else "GIL-enabled"
121
126
 
122
- print(f" webcortex {app.version} · {app.name}")
127
+ from . import __version__
128
+
129
+ print(f" webcortex {__version__} · {app.name} {app.version}")
123
130
  print(f" python {sys.version.split()[0]} ({gil})")
124
131
  print(f" {report['routes']} routes, {report['native_routes']} served without touching Python")
125
132
 
@@ -314,6 +321,7 @@ def _cmd_new(args: argparse.Namespace) -> int:
314
321
  f"\nNext:\n"
315
322
  f" cd {target}\n"
316
323
  f" export WEBCORTEX_API_KEY=$(webcortex keygen)\n"
324
+ f" webcortex doctor # names anything else this starter needs\n"
317
325
  f" webcortex dev\n"
318
326
  )
319
327
  return 0
@@ -323,7 +331,13 @@ def main(argv: list[str] | None = None) -> int:
323
331
  parser = _parser()
324
332
  args = parser.parse_args(argv)
325
333
  try:
326
- return _run(parser, args)
334
+ try:
335
+ return _run(parser, args)
336
+ except ValueError as e:
337
+ # The core refusing the manifest, from any command that reads it.
338
+ if str(e).startswith("invalid application"):
339
+ raise CLIError("WC101", str(e)) from None
340
+ raise
327
341
  except CLIError as e:
328
342
  if getattr(args, "json", False) or args.command == "check":
329
343
  print(json.dumps(e.as_json(), indent=2))
@@ -494,10 +508,14 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
494
508
  app = _load_app(args.target)
495
509
 
496
510
  if args.command in ("dev", "run"):
511
+ # An explicit flag wins over WEBCORTEX_HOST/PORT, which the manifest
512
+ # (and every later command) reads; set both so they agree.
497
513
  if args.host:
498
514
  app.host = args.host
515
+ os.environ["WEBCORTEX_HOST"] = args.host
499
516
  if args.port:
500
517
  app.port = args.port
518
+ os.environ["WEBCORTEX_PORT"] = str(args.port)
501
519
  if args.workers:
502
520
  app.workers = args.workers
503
521
  if args.command == "dev":
@@ -506,7 +524,14 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
506
524
  _banner(app)
507
525
  except ValueError as e:
508
526
  raise CLIError("WC101", str(e)) from None
509
- app.run()
527
+ try:
528
+ app.run()
529
+ except RuntimeError as e:
530
+ msg = str(e)
531
+ if msg.startswith("bind") and any(t in msg for t in ("in use", "os error 48", "os error 98",
532
+ "os error 10048")):
533
+ raise CLIError("WC104", msg) from None
534
+ raise
510
535
  return 0
511
536
 
512
537
  if args.command == "halt":
@@ -52,7 +52,11 @@ def _get_json(url: str, key: str | None, timeout: float) -> tuple[int, Any]:
52
52
  req.add_header("x-api-key", key)
53
53
  try:
54
54
  with urllib.request.urlopen(req, timeout=timeout) as res:
55
- return res.status, json.loads(res.read() or b"null")
55
+ try:
56
+ return res.status, json.loads(res.read() or b"null")
57
+ except ValueError:
58
+ # Something answered, but not with JSON: not a WebCortex app.
59
+ return res.status, None
56
60
  except urllib.error.HTTPError as e:
57
61
  try:
58
62
  return e.code, json.loads(e.read() or b"null")
@@ -175,9 +179,14 @@ def doctor(app: Any, *, online: bool = False, url: str | None = None, key: str |
175
179
  if unpriced:
176
180
  add(_check("pricing", "ok",
177
181
  f"no app.pricing for {', '.join(unpriced)}: spend is counted, cost is reported as null"))
178
- if online:
179
- for base, models in endpoints.items():
180
- ok, detail = _probe(base, timeout)
182
+ if online and endpoints:
183
+ # Concurrently: each probe may wait out the whole timeout, and N
184
+ # unreachable providers should cost one timeout, not N.
185
+ from concurrent.futures import ThreadPoolExecutor
186
+
187
+ with ThreadPoolExecutor(max_workers=min(8, len(endpoints))) as pool:
188
+ results = list(pool.map(lambda b: _probe(b, timeout), endpoints))
189
+ for (base, models), (ok, detail) in zip(endpoints.items(), results):
181
190
  add(_check(f"online:{base}", "ok" if ok else "fail",
182
191
  f"{base} {detail} (for {', '.join(models)})", code=None if ok else "WC303"))
183
192
  elif endpoints:
@@ -264,8 +273,9 @@ def doctor(app: Any, *, online: bool = False, url: str | None = None, key: str |
264
273
  unbounded = [f"agent {a['name']}" for a in app._agents if not a.get("token_budget")]
265
274
  unbounded += [f"behaviour {b['name']}" for b in app._behaviours if not b.get("token_budget")]
266
275
  if unbounded:
276
+ # No code: WC402 means a budget was exhausted, and here there is none.
267
277
  add(_check("budgets", "warn", f"no token_budget on {', '.join(unbounded)}: only max_steps bounds a run",
268
- "token_budget=... caps a run's spend (and the whole request tree it starts).", code="WC402"))
278
+ "token_budget=... caps a run's spend (and the whole request tree it starts)."))
269
279
  elif app._agents or app._behaviours:
270
280
  add(_check("budgets", "ok", "every agent and behaviour has a token_budget"))
271
281
 
@@ -305,6 +315,13 @@ def doctor(app: Any, *, online: bool = False, url: str | None = None, key: str |
305
315
  elif in_use and not url:
306
316
  add(_check("port", "fail", f"{probe_host}:{port} is in use by something that is not {app.name}",
307
317
  code="WC104"))
318
+ elif code:
319
+ # Something answered, so "nothing answered" would send the reader
320
+ # looking for a stopped server instead of a wrong --url.
321
+ other = health.get("app") if isinstance(health, dict) else None
322
+ what = f"the WebCortex app {other!r}" if other else "something that is not a WebCortex app"
323
+ add(_check("running", "warn", f"{base} answered {code}, but it is {what}, not {app.name}",
324
+ "Check --url (or WEBCORTEX_HOST/WEBCORTEX_PORT) points at this app.", code="WC108"))
308
325
  else:
309
326
  add(_check("running", "warn", f"nothing answered at {base}", code="WC108"))
310
327
  else:
@@ -345,8 +362,14 @@ def fetch_status(app: Any = None, *, url: str | None = None, key: str | None = N
345
362
  status, body = _get_json(target, key, timeout)
346
363
  except (urllib.error.URLError, OSError) as e:
347
364
  raise StatusError("WC108", f"cannot reach {target}: {getattr(e, 'reason', e)}") from None
348
- if status != 200 or not isinstance(body, dict):
349
- err = (body or {}).get("error", {}) if isinstance(body, dict) else {}
365
+ err = body.get("error") if isinstance(body, dict) else None
366
+ if not isinstance(err, dict) and (status != 200 or not isinstance(body, dict) or "requests" not in body):
367
+ # Not a WebCortex error body and not a status document: whatever is
368
+ # listening there is not a WebCortex app (or not at this prefix).
369
+ raise StatusError("WC108", f"{target} answered {status}, but not with a WebCortex status document",
370
+ "Check --url (or WEBCORTEX_HOST/WEBCORTEX_PORT) points at the running WebCortex "
371
+ "app, without a path.")
372
+ if status != 200:
350
373
  code = err.get("code") or ("WC212" if status == 404 else "WC001")
351
374
  raise StatusError(code, f"{target} answered {status}: {err.get('message', body)}", err.get("hint"))
352
375
  return body
@@ -112,6 +112,7 @@ Built with [WebCortex](https://github.com/slimboi34/web_cortex_framework).
112
112
 
113
113
  ```bash
114
114
  export WEBCORTEX_API_KEY=$(webcortex keygen)
115
+ webcortex doctor # anything else to set first? other keys, model provider keys, the port
115
116
  webcortex dev
116
117
  ```
117
118
 
@@ -126,6 +127,7 @@ webcortex check # routes, tools, and the public attack surface
126
127
  webcortex security # what is reachable without a credential
127
128
  webcortex tools # the agent tool manifest
128
129
  webcortex typegen # generate client/api.ts
130
+ webcortex status # what the running app is doing (admin key)
129
131
  ```
130
132
  """
131
133