Repository navigation
Expand file tree
/
Copy pathruntime_http.rs
More file actions
607 lines (586 loc) · 22.2 KB
/
Copy pathruntime_http.rs
File metadata and controls
607 lines (586 loc) · 22.2 KB
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
use crate::action_audit::{ActionAudit, ActionAuditRecord};
use crate::json_error;
use crate::tool_request_trace::{
estimate_json_bytes, new_trace_id, scope_active_trace, ToolRequestLifecycle,
};
use crate::tool_runtime::kernel::{
ToolCallContext, ToolCallErrorStatus, ToolCallRequest as KernelToolCallRequest, ToolTransport,
};
use crate::tool_runtime::model_ergonomics_telemetry::ModelErgonomicsCompletion;
use crate::tool_runtime::sessions::TOOL_CALL_RECORDING_SESSION_ID_FIELD;
use crate::tool_runtime::{
ListToolsOptions, ToolCall, ToolRuntime, TOOL_CALL_PARAMS_FIELD, TOOL_CALL_TOOL_FIELD,
};
use salvo::prelude::*;
use serde_json::{json, Value};
use std::sync::Arc;
mod projects;
pub use projects::projects_resolve_or_register;
fn runtime(depot: &Depot) -> Option<Arc<ToolRuntime>> {
depot.obtain::<Arc<ToolRuntime>>().ok().cloned()
}
/// Pull the [`ToolRuntime`] out of the depot, or render a 500 "Tool runtime
/// not configured" error and return `None` so the handler can bail early.
///
/// Every GPT-Actions / MCP handler opens with the same guard; this collapses
/// the seven-line `let Some(runtime) = runtime(depot) else { render; return }`
/// block into `let Some(runtime) = require_runtime(depot, res) else { return };`.
pub(crate) fn require_runtime(depot: &Depot, res: &mut Response) -> Option<Arc<ToolRuntime>> {
match runtime(depot) {
Some(runtime) => Some(runtime),
None => {
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
res.render(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"Tool runtime not configured",
));
None
}
}
}
/// Parse a JSON request body as `T`, or render a 400 "Invalid JSON" error and
/// return `None` so the handler can bail early.
///
/// Mirrors the inline `match req.parse_json().await { Ok(b) => b, Err(e) => {
/// render; return } }` block repeated across every handler. The error message
/// format is byte-identical to the previous inline form.
pub(crate) async fn parse_json_body<T>(req: &mut Request, res: &mut Response) -> Option<T>
where
T: serde::de::DeserializeOwned,
{
match req.parse_json().await {
Ok(body) => Some(body),
Err(e) => {
res.status_code(StatusCode::BAD_REQUEST);
res.render(json_error(
StatusCode::BAD_REQUEST,
format!("Invalid JSON: {}", e),
));
None
}
}
}
/// Parse an optional JSON request body while distinguishing a truly absent body
/// from malformed non-empty JSON. Empty/whitespace bodies and explicit `null`
/// preserve legacy no-argument behavior; malformed bodies fail closed with 400
/// instead of silently widening a targeted inventory request.
pub(crate) async fn parse_optional_json_body(
req: &mut Request,
res: &mut Response,
) -> Option<Value> {
let payload = match req.payload().await {
Ok(payload) => payload,
Err(e) => {
res.status_code(StatusCode::BAD_REQUEST);
res.render(json_error(
StatusCode::BAD_REQUEST,
format!("Failed to read request body: {}", e),
));
return None;
}
};
if payload.is_empty() || payload.iter().all(|byte| byte.is_ascii_whitespace()) {
return Some(Value::Object(Default::default()));
}
match serde_json::from_slice::<Value>(payload) {
Ok(Value::Null) => Some(Value::Object(Default::default())),
Ok(body) => Some(body),
Err(e) => {
res.status_code(StatusCode::BAD_REQUEST);
res.render(json_error(
StatusCode::BAD_REQUEST,
format!("Invalid JSON: {}", e),
));
None
}
}
}
fn render_result(
res: &mut Response,
audit: &ActionAudit,
operation: &str,
project: Option<String>,
result: crate::tool_runtime::ToolResult,
) {
let status = if result.success {
StatusCode::OK
} else {
StatusCode::BAD_REQUEST
};
res.status_code(status);
let mut event = ActionAuditRecord::new(operation.to_string(), result.success, status)
.error(result.error.clone())
.summary(json!({
"output": result.output.clone(),
}));
event.project = project;
audit.record(event);
res.render(Json(result));
}
/// Return the durable ActionAudit projection for one tool result.
///
/// Privacy-sensitive computer observation tools use the same bounded
/// metadata-only projection as the Workflow Session ledger, so screenshots and
/// complete window lists never enter ActionAudit.
fn action_audit_output_for_tool(tool: &str, output: &Value) -> Value {
crate::tool_runtime::audit_safe_result_for_tool(tool, output)
}
/// Audit and return the canonical tool result.
fn prepare_action_tools_call_response(
audit: &ActionAudit,
tool: &str,
project: Option<String>,
result: crate::tool_runtime::ToolResult,
model_ergonomics: Option<&ModelErgonomicsCompletion>,
canonical_audit_output: Option<Value>,
correlation: &crate::tool_runtime::ToolCallCorrelation,
) -> (StatusCode, crate::tool_runtime::ToolResult) {
let status = if result.success {
StatusCode::OK
} else {
StatusCode::BAD_REQUEST
};
let audit_output = canonical_audit_output
.unwrap_or_else(|| action_audit_output_for_tool(tool, &result.output));
let response = result;
let mut summary = json!({"output": audit_output});
if let Some(telemetry) = model_ergonomics
.and_then(|completion| completion.record_for_tool_result(&response))
.and_then(|record| serde_json::to_value(record).ok())
{
summary["model_ergonomics"] = telemetry;
}
if let Some(composition) = correlation.code_mode_composition_audit_summary() {
summary["code_mode_composition"] = composition;
}
if let Some(expectation) = &correlation.failure_expectation_result {
summary["failure_expectation_result"] = json!(expectation);
}
if let Some(job_trace) = correlation.job_audit_summary() {
summary["job_trace"] = job_trace;
}
let mut event = ActionAuditRecord::new(tool.to_string(), response.success, status)
.error(response.error.clone())
.summary(summary);
if response.success {
if let Some(ids) =
crate::tool_runtime::job_audit::action_audit_job_ids(Some(tool), &response.output)
{
event = event.ids(ids);
}
}
event.project = project;
audit.record(event);
(status, response)
}
fn record_action_tools_call_pre_result_failure(
audit: &ActionAudit,
tool: &str,
status: StatusCode,
model_ergonomics: Option<&ModelErgonomicsCompletion>,
error_kind: &'static str,
) {
let mut summary = json!({});
if let Some(telemetry) = model_ergonomics
.map(|completion| completion.record_for_pre_result_failure(error_kind))
.and_then(|record| serde_json::to_value(record).ok())
{
summary["model_ergonomics"] = telemetry;
}
audit.record(ActionAuditRecord::new(tool.to_string(), false, status).summary(summary));
}
#[handler]
pub async fn tools_list(req: &mut Request, depot: &mut Depot, res: &mut Response) {
let Some(runtime) = require_runtime(depot, res) else {
return;
};
let body = match req.payload().await {
Ok(body) => body,
Err(e) => {
res.status_code(StatusCode::BAD_REQUEST);
res.render(json_error(
StatusCode::BAD_REQUEST,
format!("Failed to read request body: {}", e),
));
return;
}
};
let options = if body.is_empty() || body.iter().all(|b| b.is_ascii_whitespace()) {
ListToolsOptions::default()
} else {
match serde_json::from_slice::<ListToolsOptions>(body) {
Ok(options) => options,
Err(e) => {
res.status_code(StatusCode::BAD_REQUEST);
res.render(json_error(
StatusCode::BAD_REQUEST,
format!("Invalid listRuntimeTools request: {}", e),
));
return;
}
}
};
let mut payload = runtime.list_tools_payload(options);
payload["success"] = json!(true);
res.render(Json(payload));
}
#[handler]
pub async fn tools_call(req: &mut Request, depot: &mut Depot, res: &mut Response) {
let mut guard =
ToolRequestLifecycle::new("api", new_trace_id(), "-", "POST /api/tools/call", None);
guard.received();
let audit = ActionAudit::start(req, depot, "/api/tools/call", "callTool");
let Some(runtime) = runtime(depot) else {
guard.parsed("error_runtime_missing");
let body = serde_json::json!({
"status": StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
"error": "Tool runtime not configured",
});
guard.capture_payload("final_response", &body);
let estimated = estimate_json_bytes(&body);
guard.response_serialized(500, estimated, Some(false), None, "error_runtime_missing");
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
res.render(Json(body));
guard.handler_returned(500, estimated, Some(false), None, "error_runtime_missing");
return;
};
// Parse the body as a raw JSON value so we can enforce the explicit
// tool/params envelope and emit field-aware errors that include the tool
// name. We never echo the raw body back, so tokens/headers/env never leak
// through error messages.
let body: Value = match req.parse_json().await {
Ok(body) => body,
Err(e) => {
guard.parsed("parse_error");
let body = serde_json::json!({
"status": StatusCode::BAD_REQUEST.as_u16(),
"error": format!("Invalid JSON: {}", e),
});
guard.capture_payload("final_response", &body);
let estimated = estimate_json_bytes(&body);
guard.response_serialized(400, estimated, Some(false), None, "parse_error");
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(400, estimated, Some(false), None, "parse_error");
return;
}
};
if let Some(tool) = body.get("tool").and_then(Value::as_str) {
guard.capture_request_diagnostic(tool, body.get("params").unwrap_or(&body));
}
let (tool, params) = match extract_tool_call(&body) {
Ok(pair) => pair,
Err(msg) => {
guard.capture_payload_lazy("raw_request_body", || tool_call_trace_raw_body(&body));
// Params-level failure: not yet in ToolRuntime.
guard.parsed("invalid_tool_call");
let body = serde_json::json!({
"status": StatusCode::BAD_REQUEST.as_u16(),
"error": msg,
});
guard.capture_payload("final_response", &body);
let estimated = estimate_json_bytes(&body);
guard.response_serialized(400, estimated, Some(false), None, "invalid_tool_call");
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(400, estimated, Some(false), None, "invalid_tool_call");
return;
}
};
guard.set_tool_name(Some(tool.clone()));
guard.capture_payload_lazy("raw_request_body", || tool_call_trace_raw_body(&body));
let window = crate::client_window::api_window(req, res);
guard.set_client_window(Some(&window));
guard.parsed("ok");
guard.capture_payload_lazy("effective_arguments", || {
tool_call_trace_effective_arguments(&tool, ¶ms)
});
// dispatch_started only after argument extraction succeeds and immediately
// before ToolRuntime dispatch.
guard.dispatch_started();
let session_id = extract_recording_session_id(&body);
let auth = depot.obtain::<crate::auth::AuthContext>().ok().cloned();
let active_trace_id = guard.active_trace_id();
let outcome = scope_active_trace(
active_trace_id,
runtime.call_tool_with_context(
KernelToolCallRequest {
tool_name: tool.clone(),
arguments: params,
},
ToolCallContext {
transport: ToolTransport::Api,
session_id: session_id.as_deref(),
auth: auth.as_ref(),
window: Some(&window),
record_oauth_scope_denials: true,
host_file_import_trust: crate::tool_runtime::kernel::HostFileImportTrust::Untrusted,
},
),
)
.await;
let model_ergonomics = outcome.model_ergonomics;
match outcome.error_status {
Some(ToolCallErrorStatus::InsufficientScope {
required_scope,
description,
}) => {
guard.dispatch_failed("insufficient_scope");
record_action_tools_call_pre_result_failure(
&audit,
&tool,
StatusCode::FORBIDDEN,
model_ergonomics.as_ref(),
"insufficient_scope",
);
guard.dispatch_finished(false, Some(false), "insufficient_scope");
let response_body = crate::auth::scope_forbidden_body(
auth.as_ref(),
required_scope,
description.clone(),
);
guard.capture_payload("final_response", &response_body);
let estimated = estimate_json_bytes(&response_body);
guard.response_serialized(
403,
estimated,
Some(false),
Some(false),
"insufficient_scope",
);
crate::auth::render_scope_forbidden(res, auth.as_ref(), required_scope, description);
guard.handler_returned(
403,
estimated,
Some(false),
Some(false),
"insufficient_scope",
);
}
Some(ToolCallErrorStatus::InvalidArguments { message }) => {
guard.dispatch_failed("invalid_arguments");
record_action_tools_call_pre_result_failure(
&audit,
&tool,
StatusCode::BAD_REQUEST,
model_ergonomics.as_ref(),
"invalid_arguments",
);
guard.dispatch_finished(false, Some(false), "invalid_arguments");
let body = serde_json::json!({
"status": StatusCode::BAD_REQUEST.as_u16(),
"error": message,
});
guard.capture_payload("final_response", &body);
let estimated = estimate_json_bytes(&body);
guard.response_serialized(
400,
estimated,
Some(false),
Some(false),
"invalid_arguments",
);
res.status_code(StatusCode::BAD_REQUEST);
res.render(Json(body));
guard.handler_returned(
400,
estimated,
Some(false),
Some(false),
"invalid_arguments",
);
}
None => {
let result = outcome
.result
.expect("tool kernel outcome without error must include result");
debug_assert_eq!(outcome.success, result.success);
let tool_success = result.success;
// HTTP/API protocol success tracks the rendered status (200 vs 400).
let protocol_success = tool_success;
if tool_success {
guard.dispatch_finished(true, Some(true), "success");
} else {
guard.dispatch_finished(true, Some(false), "tool_error");
}
// Audit the tool-specific durable projection; optionally compact only the HTTP response body.
// Trace size reflects what ChatGPT receives (post-compact when on).
let (status, response) = prepare_action_tools_call_response(
&audit,
&tool,
outcome.project,
result,
model_ergonomics.as_ref(),
outcome.canonical_audit_output,
&outcome.correlation,
);
let response_value = guard
.enabled()
.then(|| serde_json::to_value(&response).ok())
.flatten();
if let Some(value) = response_value.as_ref() {
guard.capture_payload("final_response", value);
}
let estimated = response_value.as_ref().and_then(estimate_json_bytes);
let category = if tool_success { "ok" } else { "tool_error" };
guard.response_serialized(
status.as_u16(),
estimated,
Some(protocol_success),
Some(tool_success),
category,
);
res.status_code(status);
res.render(Json(response));
guard.handler_returned(
status.as_u16(),
estimated,
Some(protocol_success),
Some(tool_success),
category,
);
}
}
}
fn tool_call_trace_raw_body(body: &Value) -> Value {
let Some(object) = body.as_object() else {
return body.clone();
};
if object.get(TOOL_CALL_TOOL_FIELD).and_then(Value::as_str)
!= Some(crate::plugin_gateway::PLUGIN_TOOL_NAME)
{
return body.clone();
}
let plugin_arguments = object
.get(TOOL_CALL_PARAMS_FIELD)
.filter(|value| value.is_object())
.cloned()
.unwrap_or_else(|| {
let mut flattened = serde_json::Map::new();
for (key, value) in object {
if key == TOOL_CALL_TOOL_FIELD
|| key == TOOL_CALL_PARAMS_FIELD
|| key == TOOL_CALL_RECORDING_SESSION_ID_FIELD
{
continue;
}
flattened.insert(key.clone(), value.clone());
}
Value::Object(flattened)
});
json!({
"tool": crate::plugin_gateway::PLUGIN_TOOL_NAME,
"arguments": crate::plugin_gateway::audit_arguments(&plugin_arguments),
"recording_session_id_present": object
.get(TOOL_CALL_RECORDING_SESSION_ID_FIELD)
.is_some(),
})
}
fn tool_call_trace_effective_arguments(tool: &str, params: &Value) -> Value {
if tool == crate::plugin_gateway::PLUGIN_TOOL_NAME {
crate::plugin_gateway::audit_arguments(params)
} else {
params.clone()
}
}
/// Extract `(tool, params)` from the generic REST `/api/tools/call` body.
///
/// Accepted shapes:
/// - `{"tool":"list_tools"}`
/// - `{"tool":"list_tools","params":null}`
/// - `{"tool":"read_workspace_changes","params":{"project":"agent:c:p"}}`
/// - `{"tool":"get_git_status","params":{"project":"agent:c:p"},"recording_session_id":"wc_sess_..."}`
///
/// `params` is the only tool-argument container. Top-level
/// `recording_session_id` remains request metadata and is not injected into
/// tool arguments. Unknown top-level fields fail with migration guidance. The
/// retired `arguments` wrapper is rejected explicitly. Returns a human-readable
/// error string (never including the raw body) when the body is invalid.
fn extract_tool_call(body: &Value) -> Result<(String, Value), String> {
let obj = body
.as_object()
.ok_or_else(|| "request body must be a JSON object".to_string())?;
let tool = match obj.get(TOOL_CALL_TOOL_FIELD) {
Some(v) => match v.as_str() {
Some(s) if !s.is_empty() => s.to_string(),
_ => {
return Err(format!(
"field '{TOOL_CALL_TOOL_FIELD}' must be a non-empty string"
));
}
},
None => {
return Err(format!("missing required field '{TOOL_CALL_TOOL_FIELD}'"));
}
};
if obj.contains_key("arguments") {
return Err(
"field 'arguments' is no longer supported; move tool arguments under 'params'"
.to_string(),
);
}
let mut unexpected = obj
.keys()
.filter(|key| {
key.as_str() != TOOL_CALL_TOOL_FIELD
&& key.as_str() != TOOL_CALL_PARAMS_FIELD
&& key.as_str() != TOOL_CALL_RECORDING_SESSION_ID_FIELD
})
.cloned()
.collect::<Vec<_>>();
unexpected.sort();
if !unexpected.is_empty() {
let fields = unexpected
.iter()
.map(|field| format!("'{field}'"))
.collect::<Vec<_>>()
.join(", ");
return Err(format!(
"unexpected top-level field(s) {fields}; move tool arguments under 'params'"
));
}
let params = obj
.get(TOOL_CALL_PARAMS_FIELD)
.cloned()
.unwrap_or(Value::Null);
Ok((tool, params))
}
fn extract_recording_session_id(body: &Value) -> Option<String> {
body.as_object()
.and_then(|obj| obj.get(TOOL_CALL_RECORDING_SESSION_ID_FIELD))
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
#[handler]
pub async fn runtime_status(req: &mut Request, depot: &mut Depot, res: &mut Response) {
let audit = ActionAudit::start(req, depot, "/api/runtime/status", "getRuntimeStatus");
let Some(runtime) = require_runtime(depot, res) else {
return;
};
// Body remains optional for compatibility. Non-empty malformed JSON must
// fail closed instead of silently widening a focused request to fleet-wide.
let Some(arguments) = parse_optional_json_body(req, res).await else {
return;
};
let call = match ToolCall::from_tool_name("get_runtime_status", arguments) {
Ok(call) => call,
Err(error) => {
render_result(
res,
&audit,
"get_runtime_status",
None,
crate::tool_runtime::ToolResult::err(error),
);
return;
}
};
let auth = depot.obtain::<crate::auth::AuthContext>().ok().cloned();
let result = runtime.dispatch_with_auth(call, auth.as_ref()).await;
render_result(res, &audit, "get_runtime_status", None, result);
}
#[cfg(test)]
#[path = "runtime_http_tests.rs"]
mod tests;