返回 CodeWhale
owner_calls.rs
根目录 / crates / app-server / src / runtime_api / owner_calls.rs
1 use super::*;
2 use crate::{RuntimeOwnerFailure, RuntimeOwnerRequest};
3
4 async fn validate_workspace_scope(state: &RuntimeApiState) -> Result<()> {
5 state
6 .workspace_scope
7 .validate()
8 .await
9 .map_err(|_| RuntimeOwnerFailure {
10 status: 409,
11 message: "selected workspace identity changed".to_owned(),
12 code: None,
13 })?;
14 Ok(())
15 }
16
17 async fn validate(state: &RuntimeApiState) -> Result<()> {
18 if state.runtime_threads.is_acp_host() {
19 return Err(RuntimeOwnerFailure {
20 status: 403,
21 message: "immutable ACP-base owner cannot admit ordinary native services".to_owned(),
22 code: Some("acp_owner_read_only".to_owned()),
23 }
24 .into());
25 }
26 validate_workspace_scope(state).await?;
27 if state.shutdown.requested.is_cancelled() {
28 return Err(RuntimeOwnerFailure {
29 status: 503,
30 message: "captured Runtime is stopping".to_owned(),
31 code: Some("owner_stopping".to_owned()),
32 }
33 .into());
34 }
35 Ok(())
36 }
37
38 fn api<T>(result: std::result::Result<T, ApiError>) -> Result<T> {
39 result.map_err(|error| {
40 RuntimeOwnerFailure {
41 status: error.status.as_u16(),
42 message: error.message,
43 code: error.code.map(str::to_owned),
44 }
45 .into()
46 })
47 }
48
49 fn decode<T: serde::de::DeserializeOwned>(body: Value) -> Result<T> {
50 serde_json::from_value(body).map_err(|error| {
51 RuntimeOwnerFailure {
52 status: 400,
53 message: error.to_string(),
54 code: None,
55 }
56 .into()
57 })
58 }
59
60 fn user_input_receipt(input_id: String, delivered: bool) -> Result<Value, ApiError> {
61 if !delivered {
62 return Err(ApiError::not_found(format!(
63 "no pending user-input request with id '{input_id}'"
64 )));
65 }
66 serde_json::to_value(SubmitUserInputResponse {
67 ok: true,
68 input_id,
69 delivered,
70 })
71 .map_err(|error| ApiError::internal(error.to_string()))
72 }
73
74 pub(super) async fn execute(state: RuntimeApiState, request: RuntimeOwnerRequest) -> Result<Value> {
75 validate(&state).await?;
76 match request {
77 RuntimeOwnerRequest::Native { workspace, request } => {
78 Box::pin(execute_native(state, workspace, request)).await
79 }
80 request => Box::pin(execute_ordinary(state, request)).await,
81 }
82 }
83
84 async fn execute_ordinary(state: RuntimeApiState, request: RuntimeOwnerRequest) -> Result<Value> {
85 Ok(match request {
86 RuntimeOwnerRequest::Native { .. } => anyhow::bail!("nested native dispatch refused"),
87 RuntimeOwnerRequest::Capabilities => {
88 json!({ "capabilities": default_runtime_capabilities() })
89 }
90 RuntimeOwnerRequest::Providers => {
91 let Json(value) = api(list_providers(State(state)).await)?;
92 serde_json::to_value(value)?
93 }
94 RuntimeOwnerRequest::ProviderModels {
95 provider,
96 provider_id,
97 cursor,
98 } => {
99 let Json(value) = api(list_provider_models(
100 State(state),
101 Path(provider),
102 Query(ListProviderModelsParams {
103 model_provider_id: provider_id,
104 cursor,
105 filter: None,
106 limit: Some(250),
107 }),
108 )
109 .await)?;
110 serde_json::to_value(value)?
111 }
112 RuntimeOwnerRequest::ReloadConfig => {
113 let Json(value) = api(reload_config(State(state)).await)?;
114 serde_json::to_value(value)?
115 }
116 RuntimeOwnerRequest::CreateThread(body) => {
117 let (_, Json(value)) = api(create_thread(State(state), Json(decode(body)?)).await)?;
118 serde_json::to_value(value)?
119 }
120 RuntimeOwnerRequest::ListThreads {
121 include_archived,
122 limit,
123 } => {
124 let Json(value) = api(list_threads(
125 State(state),
126 None,
127 Query(ThreadsQuery {
128 limit: Some(limit),
129 include_archived: Some(include_archived),
130 archived_only: None,
131 }),
132 )
133 .await)?;
134 serde_json::to_value(value)?
135 }
136 RuntimeOwnerRequest::LoadedThreads => {
137 serde_json::to_value(state.runtime_threads.loaded_threads().await?)?
138 }
139 RuntimeOwnerRequest::RunningThreads => {
140 let Json(value) = api(list_running_threads(State(state)).await)?;
141 serde_json::to_value(value)?
142 }
143 RuntimeOwnerRequest::GetThread { thread_id } => {
144 let Json(value) = api(get_thread(State(state), Path(thread_id)).await)?;
145 serde_json::to_value(value)?
146 }
147 RuntimeOwnerRequest::UpdateThread { thread_id, body } => {
148 let Json(value) =
149 api(update_thread(State(state), Path(thread_id), Json(decode(body)?)).await)?;
150 serde_json::to_value(value)?
151 }
152 RuntimeOwnerRequest::GetGoal { thread_id } => {
153 let Json(value) = api(get_thread_goal(State(state), Path(thread_id)).await)?;
154 serde_json::to_value(value)?
155 }
156 RuntimeOwnerRequest::ClearGoal { thread_id } => {
157 api(delete_thread_goal(State(state), Path(thread_id)).await)?;
158 Value::Null
159 }
160 RuntimeOwnerRequest::HistorySnapshot { thread_id } => {
161 let Json(value) =
162 api(thread_history::snapshot_thread_history(State(state), Path(thread_id)).await)?;
163 serde_json::to_value(value)?
164 }
165 RuntimeOwnerRequest::HistoryImport(body) => {
166 let Json(value) =
167 api(thread_history::import_thread_history(State(state), Json(body)).await)?;
168 serde_json::to_value(value)?
169 }
170 RuntimeOwnerRequest::HistoryMutate(body) => {
171 let Json(value) =
172 api(thread_history::mutate_thread_history(State(state), Json(body)).await)?;
173 serde_json::to_value(value)?
174 }
175 RuntimeOwnerRequest::HistoryLookup(body) => {
176 let Json(value) =
177 api(
178 thread_history::lookup_thread_history_operation(State(state), Json(body)).await,
179 )?;
180 serde_json::to_value(value)?
181 }
182 RuntimeOwnerRequest::HistoryRecover(body) => {
183 let Json(value) = api(thread_history::recover_thread_history_operation(
184 State(state),
185 Json(body),
186 )
187 .await)?;
188 serde_json::to_value(value)?
189 }
190 RuntimeOwnerRequest::LookupTurnOperation {
191 thread_id,
192 operation_key,
193 } => {
194 let Json(receipt) =
195 api(
196 get_thread_turn_operation(State(state), Path((thread_id, operation_key))).await,
197 )?;
198 serde_json::to_value(receipt)?
199 }
200 RuntimeOwnerRequest::StartTurn { thread_id, body } => {
201 let (_, Json(value)) = api(start_thread_turn_for_caller(
202 State(state),
203 Path(thread_id),
204 Json(decode(body)?),
205 false,
206 None,
207 )
208 .await)?;
209 serde_json::to_value(value)?
210 }
211 RuntimeOwnerRequest::DecideApproval {
212 approval_id,
213 binding,
214 decision,
215 } => {
216 let value = api(settle_approval_request(
217 &state,
218 approval_id,
219 binding.as_ref(),
220 decision,
221 Some(codewhale_engine::runtime_threads::manager::ApprovalResponder::Desktop),
222 )
223 .await)?;
224 serde_json::to_value(value)?
225 }
226 RuntimeOwnerRequest::SubmitUserInput {
227 thread_id,
228 input_id,
229 turn_id,
230 response,
231 } => {
232 let delivered = api(state
233 .runtime_threads
234 .submit_user_input_for_turn(&thread_id, &input_id, turn_id.as_deref(), response)
235 .await
236 .map_err(map_thread_err))?;
237 api(user_input_receipt(input_id, delivered))?
238 }
239 RuntimeOwnerRequest::CancelUserInput {
240 thread_id,
241 input_id,
242 turn_id,
243 } => {
244 let delivered = api(state
245 .runtime_threads
246 .cancel_user_input_for_turn(&thread_id, &input_id, turn_id.as_deref())
247 .await
248 .map_err(map_thread_err))?;
249 api(user_input_receipt(input_id, delivered))?
250 }
251 RuntimeOwnerRequest::DeliverDynamicToolResult {
252 thread_id,
253 turn_id,
254 call_id,
255 result,
256 } => {
257 api(deliver_dynamic_tool_result(
258 State(state),
259 Path((thread_id, turn_id, call_id)),
260 Json(result),
261 )
262 .await)?;
263 json!({ "ok": true, "delivered": true })
264 }
265 RuntimeOwnerRequest::InterruptTurn { thread_id, turn_id } => {
266 let Json(value) =
267 api(interrupt_thread_turn(State(state), Path((thread_id, turn_id))).await)?;
268 serde_json::to_value(value)?
269 }
270 })
271 }
272
273 pub(super) async fn events(
274 state: RuntimeApiState,
275 thread_id: String,
276 since_seq: u64,
277 ) -> Result<crate::RuntimeOwnerEventStream> {
278 validate(&state).await?;
279 api(open_thread_event_frames(
280 state,
281 thread_id,
282 ThreadEventsQuery {
283 since_seq: Some(since_seq),
284 replay_limit: None,
285 progress: false,
286 },
287 )
288 .await)
289 }
290
291 pub(super) async fn events_in_workspace(
292 state: RuntimeApiState,
293 workspace: PathBuf,
294 thread_id: String,
295 since_seq: u64,
296 ) -> Result<crate::RuntimeOwnerEventStream> {
297 validate(&state).await?;
298 if !workspace.is_absolute() || workspace != state.workspace {
299 return api(Err(ApiError::forbidden(
300 "native workspace does not match captured owner",
301 )
302 .with_code("workspace_mismatch")));
303 }
304 api(open_thread_event_frames_in_workspace(
305 state,
306 thread_id,
307 ThreadEventsQuery {
308 since_seq: Some(since_seq),
309 replay_limit: None,
310 progress: false,
311 },
312 Some(workspace),
313 )
314 .await)
315 }
316
317 async fn native_thread(state: &RuntimeApiState, thread_id: &str) -> Result<()> {
318 let (_, selected) = api(workspace::thread_workspace(state, thread_id).await)?;
319 if selected != state.workspace {
320 return api(Err(ApiError::forbidden(
321 "thread is outside the selected workspace",
322 )
323 .with_code("workspace_mismatch")));
324 }
325 Ok(())
326 }
327
328 async fn native_response(response: Response) -> Result<Value> {
329 let status = response.status();
330 let bytes = axum::body::to_bytes(
331 response.into_body(),
332 codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES,
333 )
334 .await?;
335 let value: Value = serde_json::from_slice(&bytes)?;
336 if !status.is_success() {
337 return Err(RuntimeOwnerFailure {
338 status: status.as_u16(),
339 message: value["error"]["message"]
340 .as_str()
341 .unwrap_or("Runtime operation refused")
342 .to_owned(),
343 code: value["error"]["code"].as_str().map(str::to_owned),
344 }
345 .into());
346 }
347 Ok(value)
348 }
349
350 fn native_headers(key: &str) -> Result<HeaderMap> {
351 let mut headers = HeaderMap::new();
352 headers.insert(
353 "idempotency-key",
354 api(HeaderValue::from_str(key)
355 .map_err(|_| ApiError::bad_request("operation_key must be visible ASCII")))?,
356 );
357 api(automation_idempotency_key(&headers))?;
358 Ok(headers)
359 }
360
361 async fn native_automation(state: &RuntimeApiState, record: &AutomationRecord) -> Result<()> {
362 if record.cwds.len() != 1 || record.cwds[0] != state.workspace {
363 return api(Err(ApiError::forbidden(
364 "automation is outside the selected workspace",
365 )
366 .with_code("workspace_mismatch")));
367 }
368 native_thread(
369 state,
370 record
371 .destination_thread_id
372 .as_deref()
373 .ok_or_else(|| RuntimeOwnerFailure {
374 status: 403,
375 message: "automation has no selected destination".to_owned(),
376 code: Some("workspace_mismatch".to_owned()),
377 })?,
378 )
379 .await
380 }
381
382 async fn execute_native(
383 state: RuntimeApiState,
384 selected: PathBuf,
385 request: codewhale_app_server_protocol::runtime::NativeRuntimeRequest,
386 ) -> Result<Value> {
387 use codewhale_app_server_protocol::runtime::NativeApprovalDecision;
388 use codewhale_app_server_protocol::runtime::NativeRuntimeRequest as N;
389 use codewhale_engine::runtime_threads::manager::{
390 ExternalApprovalBinding, ExternalApprovalDecision,
391 };
392 if !selected.is_absolute() || selected != state.workspace {
393 return api(Err(ApiError::forbidden(
394 "native workspace does not match captured owner",
395 )
396 .with_code("workspace_mismatch")));
397 }
398 validate_workspace_scope(&state).await?;
399 let resume = matches!(&request, N::ResumeAutomation(_));
400 let delegated = match request {
401 N::Capabilities(_) => {
402 return Ok(
403 json!({"capabilities": default_runtime_capabilities(), "native_runtime": crate::native_runtime::capabilities()}),
404 );
405 }
406 N::ListThreads(params) => {
407 let limit = params.limit.unwrap_or(100);
408 if !(1..=100).contains(&limit) {
409 return api(Err(ApiError::bad_request("limit must be 1..100")));
410 }
411 let Json(records) = api(list_threads(
412 State(state.clone()),
413 None,
414 Query(ThreadsQuery {
415 limit: None,
416 include_archived: params.include_archived,
417 archived_only: None,
418 }),
419 )
420 .await)?;
421 let mut scoped = Vec::new();
422 for record in records {
423 if record.workspace == state.workspace
424 && native_thread(&state, &record.id).await.is_ok()
425 {
426 scoped.push(record);
427 if scoped.len() == limit as usize {
428 break;
429 }
430 }
431 }
432 return Ok(serde_json::to_value(scoped)?);
433 }
434 N::ReadThread(params) => {
435 native_thread(&state, &params.thread_id).await?;
436 return Ok(serde_json::to_value(api(state
437 .runtime_threads
438 .get_thread_detail_in_workspace(&params.thread_id, Some(&selected))
439 .await
440 .map_err(map_thread_err))?)?);
441 }
442 N::CreateThread(params) => {
443 let mut body = serde_json::to_value(params.body)?;
444 body["workspace"] = json!(selected);
445 RuntimeOwnerRequest::CreateThread(body)
446 }
447 N::UpdateThread(params) => {
448 native_thread(&state, &params.thread_id).await?;
449 let mut body = serde_json::to_value(params.body)?;
450 body["expected_workspace"] = json!(selected);
451 RuntimeOwnerRequest::UpdateThread {
452 thread_id: params.thread_id,
453 body,
454 }
455 }
456 N::Providers(_) => RuntimeOwnerRequest::Providers,
457 N::ProviderModels(params) => RuntimeOwnerRequest::ProviderModels {
458 provider: params.provider,
459 provider_id: params.provider_id,
460 cursor: params.cursor,
461 },
462 N::StartTurn(params) => {
463 native_thread(&state, &params.thread_id).await?;
464 if params
465 .body
466 .allowed_tools
467 .as_ref()
468 .is_some_and(|tools| !tools.is_empty())
469 {
470 return api(Err(ApiError::bad_request(
471 "allowed_tools may only narrow to an empty list",
472 )));
473 }
474 let images = params.body.images.clone().unwrap_or_default();
475 let mut body = serde_json::to_value(params.body)?;
476 body["images"] = json!(images);
477 body["expected_workspace"] = json!(selected);
478 let (_, Json(value)) = api(start_thread_turn_for_caller(
479 State(state),
480 Path(params.thread_id),
481 Json(decode(body)?),
482 true,
483 None,
484 )
485 .await)?;
486 return Ok(serde_json::to_value(value)?);
487 }
488 N::InterruptTurn(params) => {
489 native_thread(&state, &params.thread_id).await?;
490 let turn = api(state
491 .runtime_threads
492 .interrupt_turn_in_workspace(&params.thread_id, &params.turn_id, Some(&selected))
493 .await
494 .map_err(map_thread_err))?;
495 return Ok(serde_json::to_value(turn)?);
496 }
497 N::DecideApproval(params) => {
498 native_thread(&state, &params.thread_id).await?;
499 if params.remember.unwrap_or(false) {
500 return api(Err(ApiError::bad_request("remember is not supported")));
501 }
502 let binding = ExternalApprovalBinding {
503 thread_id: params.thread_id,
504 turn_id: params.turn_id,
505 tool_call_id: params.tool_call_id,
506 };
507 let decision = match params.decision {
508 NativeApprovalDecision::Allow => {
509 ExternalApprovalDecision::Allow { remember: false }
510 }
511 NativeApprovalDecision::Deny => ExternalApprovalDecision::Deny { remember: false },
512 };
513 return Ok(serde_json::to_value(api(
514 settle_approval_request_in_workspace(
515 &state,
516 params.approval_id,
517 Some(&binding),
518 decision,
519 Some(codewhale_engine::runtime_threads::manager::ApprovalResponder::Desktop),
520 Some(&selected),
521 )
522 .await,
523 )?)?);
524 }
525 N::Subscribe(params) => {
526 native_thread(&state, &params.thread_id).await?;
527 return Ok(Value::Null);
528 }
529 N::Unsubscribe(_) => {
530 return api(Err(ApiError::bad_request(
531 "subscription belongs to its connection",
532 )));
533 }
534 N::AccountStatus(_) => return api(account::status_receipt(state).await),
535 N::ListAutomations(_) => {
536 let Json(records) = api(list_automations(State(state.clone())).await)?;
537 let mut scoped = Vec::new();
538 for record in records {
539 if native_automation(&state, &record.record).await.is_ok() {
540 scoped.push(record);
541 }
542 }
543 return Ok(serde_json::to_value(scoped)?);
544 }
545 N::CreateAutomation(params) => {
546 api(reject_automation_permission_elevation(
547 None,
548 params.body.trust_mode,
549 params.body.auto_approve,
550 ))?;
551 native_thread(&state, &params.body.destination_thread_id).await?;
552 let headers = native_headers(&params.operation_key)?;
553 let mut body = serde_json::to_value(params.body)?;
554 body["cwds"] = json!([selected]);
555 return native_response(api(create_automation_in_workspace(
556 state,
557 headers,
558 decode(body)?,
559 Some(selected.clone()),
560 )
561 .await)?)
562 .await;
563 }
564 N::PauseAutomation(params) | N::ResumeAutomation(params) => {
565 let existing = state
566 .automations
567 .lock()
568 .await
569 .get_automation(&params.automation_id);
570 if let Ok(record) = existing {
571 native_automation(&state, &record).await?;
572 }
573 let headers = native_headers(&params.operation_key)?;
574 let query = AutomationPreconditionQuery {
575 expected_revision: Some(params.expected_revision),
576 };
577 let (action, status) = if resume {
578 (
579 "resume",
580 codewhale_engine::automation_manager::AutomationStatus::Active,
581 )
582 } else {
583 (
584 "pause",
585 codewhale_engine::automation_manager::AutomationStatus::Paused,
586 )
587 };
588 return native_response(api(set_automation_status_in_workspace(
589 state,
590 params.automation_id,
591 query,
592 headers,
593 action,
594 status,
595 Some(selected),
596 )
597 .await)?)
598 .await;
599 }
600 };
601 execute_ordinary(state, delegated).await
602 }
603
603 lines RUST