返回 CodeWhale
command_catalog.rs
根目录 / crates / app-server / src / runtime_api / tests / command_catalog.rs
1 use super::*;
2 use codewhale_engine::command_catalog::{BuiltinCommand, CommandCatalog, UserCommand};
3
4 fn builtin(name: &str, aliases: Vec<String>) -> BuiltinCommand {
5 BuiltinCommand {
6 name: name.to_string(),
7 aliases,
8 usage: format!("/{name} [value]"),
9 description_id: codewhale_localization::MessageId::CmdModelDescription,
10 subcommands: Vec::new(),
11 takes_arguments: true,
12 requires_argument: true,
13 requires_required_argument: false,
14 composer_wants_trailing_space: true,
15 palette_runs_directly: false,
16 show_in_empty_discovery: true,
17 discovery: codewhale_command_contract::CommandDiscovery::Primary,
18 unlisted: false,
19 }
20 }
21
22 fn user(name: &str) -> UserCommand {
23 UserCommand {
24 name: name.to_string(),
25 aliases: Vec::new(),
26 description: Some("Pick the fast route.".to_string()),
27 usage: None,
28 takes_arguments: false,
29 hidden: false,
30 extension: false,
31 plugin_id: None,
32 workspace_sourced: false,
33 builtin_bindings: vec![name.to_string()],
34 }
35 }
36
37 struct Catalog(PathBuf);
38 impl CommandCatalog for Catalog {
39 fn answers_to(&self, name: &str) -> bool {
40 matches!(name, "model" | "profile")
41 }
42 fn builtins(&self) -> Vec<BuiltinCommand> {
43 let mut profile = builtin("profile", Vec::new());
44 profile.requires_required_argument = true;
45 vec![builtin("model", Vec::new()), profile]
46 }
47 fn user_commands(&self, workspace: &Path) -> Vec<UserCommand> {
48 if workspace == self.0 {
49 vec![user("model")]
50 } else {
51 Vec::new()
52 }
53 }
54 }
55
56 fn entry<'a>(commands: &'a [CommandCatalogEntry], name: &str) -> &'a CommandCatalogEntry {
57 commands
58 .iter()
59 .find(|command| command.name == name)
60 .unwrap_or_else(|| panic!("catalog must contain {name}"))
61 }
62
63 #[test]
64 fn command_catalog_marks_user_shadowing_of_builtin_names_and_aliases() {
65 let builtins = [
66 builtin("model", vec![]),
67 builtin("subagents", vec!["agents".to_string()]),
68 ];
69 let users = [user("model"), user("agents")];
70 let commands = command_catalog(&builtins, &users, false);
71
72 let model = entry(&commands, "model");
73 assert_eq!(model.shadowed_by.as_deref(), Some("model"));
74
75 // The shadowing user command is served as a prompt-bound row.
76 let user_model = commands
77 .iter()
78 .find(|command| command.name == "model" && command.kind == "user")
79 .expect("user command row");
80 assert_eq!(user_model.binding, "prompt");
81
82 // A user command colliding with a builtin's alias shadows that spelling:
83 // `agents` is a `subagents` alias, so the builtin reports it while keeping
84 // its canonical name.
85 let subagents = entry(&commands, "subagents");
86 assert_eq!(subagents.kind, "builtin");
87 assert_eq!(subagents.shadowed_by, None);
88 assert!(
89 subagents.shadowed_aliases.iter().any(|a| a == "agents"),
90 "shadowed_aliases must report the taken spelling: {:?}",
91 subagents.shadowed_aliases
92 );
93 }
94
95 #[tokio::test]
96 async fn get_v1_commands_serves_the_catalog_over_http() -> Result<()> {
97 let _env = lock_test_env();
98 let temp = tempfile::tempdir()?;
99 let root = temp.path().join("commands-route");
100 let sessions_dir = root.join("sessions");
101 let workspace = root.join("workspace");
102 fs::create_dir_all(&workspace)?;
103 let _catalog = codewhale_engine::command_catalog::CatalogGuard::install(Arc::new(Catalog(
104 workspace.clone(),
105 )));
106
107 let Some((addr, runtime_threads, handle)) = spawn_test_server_with_root_token_mobile_workspace(
108 root,
109 sessions_dir,
110 None,
111 false,
112 workspace,
113 )
114 .await?
115 else {
116 return Ok(());
117 };
118 let client = codewhale_release::tls::reqwest_client();
119
120 let body: serde_json::Value = client
121 .get(format!("http://{addr}/v1/commands"))
122 .send()
123 .await?
124 .error_for_status()?
125 .json()
126 .await?;
127 let commands = body["commands"].as_array().expect("commands array");
128 assert!(
129 commands
130 .iter()
131 .any(|command| command["kind"] == "builtin" && command["binding"] == "host"),
132 "the route must serve builtins: {commands:?}"
133 );
134
135 // The workspace user command named `model` shadows the builtin: the
136 // builtin reports the shadow and the winning definition is served.
137 let builtin_model = commands
138 .iter()
139 .find(|command| command["name"] == "model" && command["kind"] == "builtin")
140 .expect("builtin model row");
141 assert_eq!(builtin_model["shadowed_by"], "model");
142 let user_model = commands
143 .iter()
144 .find(|command| command["name"] == "model" && command["kind"] == "user")
145 .expect("user model row");
146 assert_eq!(user_model["binding"], "prompt");
147 // A template without `$ARGUMENTS` runs bare from the palette.
148 assert_eq!(user_model["requires_required_argument"], false);
149 assert_eq!(user_model["palette_runs_directly"], true);
150 assert_eq!(user_model["show_in_empty_discovery"], true);
151
152 let profile = commands
153 .iter()
154 .find(|command| command["name"] == "profile" && command["kind"] == "builtin")
155 .expect("builtin profile row");
156 assert_eq!(profile["requires_required_argument"], true);
157 assert_eq!(profile["palette_runs_directly"], false);
158
159 assert_eq!(
160 client
161 .get(format!(
162 "http://{addr}/v1/commands?thread_id=missing-thread"
163 ))
164 .send()
165 .await?
166 .status(),
167 StatusCode::NOT_FOUND
168 );
169 let thread = runtime_threads
170 .create_thread(CreateThreadRequest::default())
171 .await?;
172 let operation_url = format!(
173 "http://{addr}/v1/threads/{}/commands/cancel-before-admission",
174 thread.id
175 );
176 assert_eq!(
177 client.get(&operation_url).send().await?.status(),
178 StatusCode::NOT_FOUND
179 );
180 let cancelled: Value = client
181 .delete(&operation_url)
182 .send()
183 .await?
184 .error_for_status()?
185 .json()
186 .await?;
187 assert_eq!(cancelled["cancelled"], true);
188 let receipt: Value = client
189 .get(&operation_url)
190 .send()
191 .await?
192 .error_for_status()?
193 .json()
194 .await?;
195 assert_eq!(receipt["status"], "cancelled");
196 assert_eq!(receipt["operation_key"], "cancel-before-admission");
197 let response = client
198 .post(format!("http://{addr}/v1/threads/{}/commands", thread.id))
199 .json(&json!({
200 "name": "native", "args": "", "registration_id": "a".repeat(64),
201 "operation_key": "cancel-before-admission", "expected_workspace": thread.workspace,
202 }))
203 .send()
204 .await?;
205 assert_eq!(response.status(), StatusCode::CONFLICT);
206 let refusal: Value = response.json().await?;
207 assert_eq!(refusal["error"]["code"], "command_cancelled");
208 let cancelled_again: Value = client
209 .delete(&operation_url)
210 .send()
211 .await?
212 .error_for_status()?
213 .json()
214 .await?;
215 assert_eq!(cancelled_again["cancelled"], true);
216
217 handle.abort();
218 let Some(node) =
219 codewhale_engine::extension_host::test_support::node_for_tests("runtime_command_catalog")
220 else {
221 return Ok(());
222 };
223 let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(true);
224 let fixture = codewhale_engine::extension_host::test_support::FixturePlugins::new(&[]).await;
225 let source = temp.path().join("native-command-plugin");
226 fs::create_dir_all(&source)?;
227 fs::write(
228 source.join("plugin.json"),
229 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"native-command-fixture","version":"0.1.0","description":"Runtime command fixture","license":"MIT","extensions":{"net.codewhale":{"native":{"path":"index.mjs"}}}}"#,
230 )?;
231 fs::write(
232 source.join("index.mjs"),
233 r#"
234 export const name = 'native-command-fixture'
235 export const inject = ['commands']
236 export function apply(ctx) {
237 let shows = 0
238 ctx.commands.register({ name: 'native-show', description: 'Show a result', handler: () => String(++shows) })
239 ctx.commands.register({ name: 'native-submit', description: 'Submit a turn', handler: () => ({ kind: 'submit', prompt: 'Command-generated prompt', text: 'Submitted by plugin' }) })
240 ctx.commands.register({ name: 'native-fail', description: 'Fail visibly', handler: () => ({ kind: 'error', text: 'Expected fixture failure' }) })
241 ctx.commands.register({ name: 'native-slow', description: 'Wait for cancellation', handler: async () => new Promise(resolve => setTimeout(() => resolve('late result'), 10000)) })
242 }
243 "#,
244 )?;
245 codewhale_plugins::install::install(
246 codewhale_plugins::install::PluginInstallSource::LocalPath(source),
247 &fixture.config.user_plugins_dir,
248 codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
249 &codewhale_net::network_policy::NetworkPolicy::default(),
250 false,
251 &|_| None,
252 )
253 .await?;
254 let mut plugins = codewhale_plugins::discovery::discover_with_config(&fixture.config);
255 plugins
256 .trust("native-command-fixture")
257 .map_err(anyhow::Error::msg)?;
258 plugins
259 .enable("native-command-fixture")
260 .map_err(anyhow::Error::msg)?;
261 let extension_manager = fixture.manager(node);
262 let _extension_manager =
263 codewhale_engine::extension_host::TestManagerGuard::install(extension_manager.clone());
264 let mut config = Config::default().with_legacy_root(
265 Some("command-fixture-key".into()),
266 Some("http://127.0.0.1:1/v1".into()),
267 );
268 config.set_feature("extension_host", true)?;
269 let (addr, runtime_threads, handle) =
270 spawn_test_server_with_root_token_mobile_workspace_and_overrides(
271 temp.path().join("native-runtime"),
272 temp.path().join("native-sessions"),
273 None,
274 false,
275 fixture.workspace().to_path_buf(),
276 TestServerOverrides {
277 config: Some(config),
278 plugin_discovery: Some(
279 codewhale_plugins::PluginDiscoveryContext::from_config_and_environment(
280 &fixture.config,
281 codewhale_plugins::HostEnvironment::from_entries(Vec::new()),
282 ),
283 ),
284 ..TestServerOverrides::default()
285 },
286 )
287 .await?
288 .context("native command acceptance requires a loopback listener")?;
289 let model = Arc::new(codewhale_engine::llm_client::mock::MockLlmClient::new(
290 vec![codewhale_engine::llm_client::mock::canned::simple_text_turn("Plugin turn completed")],
291 ));
292 runtime_threads.set_test_model_client(model.clone());
293 let thread = runtime_threads
294 .create_thread(CreateThreadRequest {
295 model: Some("deepseek-v4-pro".into()),
296 ..Default::default()
297 })
298 .await?;
299 let catalog: Value = client
300 .get(format!("http://{addr}/v1/commands?thread_id={}", thread.id))
301 .send()
302 .await?
303 .error_for_status()?
304 .json()
305 .await?;
306 let rows = catalog["commands"].as_array().context("command rows")?;
307 let show = rows
308 .iter()
309 .find(|row| row["name"] == "native-show")
310 .context("live native command")?;
311 let submit = rows
312 .iter()
313 .find(|row| row["name"] == "native-submit")
314 .context("live submit command")?;
315 assert_eq!(show["binding"], "extension");
316 assert_eq!(show["origin"], "extension:native-command-fixture");
317 let command_url = format!("http://{addr}/v1/threads/{}/commands", thread.id);
318 let show_request = json!({ "name":"native-show", "args":"", "registration_id":show["registration_id"], "operation_key":"show-once", "expected_workspace":thread.workspace });
319 let shown: Value = client
320 .post(&command_url)
321 .json(&show_request)
322 .send()
323 .await?
324 .error_for_status()?
325 .json()
326 .await?;
327 assert_eq!(shown["status"], "completed");
328 assert_eq!(shown["text"], "1");
329 assert_eq!(shown["idempotent_replay"], false);
330 assert!(
331 shown["extension"]["content_hash"]
332 .as_str()
333 .is_some_and(|value| value.len() == 64)
334 );
335 assert!(shown["extension"]["entry"]["sha256"].is_string());
336 assert!(shown["extension"]["generation"].is_number());
337 let replay: Value = client
338 .post(&command_url)
339 .json(&show_request)
340 .send()
341 .await?
342 .error_for_status()?
343 .json()
344 .await?;
345 assert_eq!(replay["text"], "1");
346 assert_eq!(replay["idempotent_replay"], true);
347 let lookup: Value = client
348 .get(format!("{command_url}/show-once"))
349 .send()
350 .await?
351 .error_for_status()?
352 .json()
353 .await?;
354 assert_eq!(lookup, replay);
355 assert!(model.captured_requests().is_empty());
356 let failure = rows
357 .iter()
358 .find(|row| row["name"] == "native-fail")
359 .context("live failure command")?;
360 let failed: Value = client.post(&command_url).json(&json!({ "name":"native-fail", "args":"", "registration_id":failure["registration_id"], "operation_key":"failure-once", "expected_workspace":thread.workspace })).send().await?.error_for_status()?.json().await?;
361 assert_eq!(failed["status"], "failed");
362 let slow = rows
363 .iter()
364 .find(|row| row["name"] == "native-slow")
365 .context("live slow command")?;
366 let slow_request = json!({ "name":"native-slow", "args":"", "registration_id":slow["registration_id"], "operation_key":"cancel-running", "expected_workspace":thread.workspace });
367 let slow_client = client.clone();
368 let slow_url = command_url.clone();
369 let waiting =
370 tokio::spawn(async move { slow_client.post(&slow_url).json(&slow_request).send().await });
371 tokio::time::timeout(ci_scaled(Duration::from_secs(10)), async {
372 loop {
373 let response = client
374 .get(format!("{command_url}/cancel-running"))
375 .send()
376 .await?;
377 if response.status().is_success() {
378 let pending: Value = response.json().await?;
379 assert_eq!(pending["status"], "pending");
380 break;
381 }
382 assert_eq!(response.status(), StatusCode::NOT_FOUND);
383 sleep(Duration::from_millis(10)).await;
384 }
385 Ok::<_, anyhow::Error>(())
386 })
387 .await??;
388 client
389 .delete(format!("{command_url}/cancel-running"))
390 .send()
391 .await?
392 .error_for_status()?;
393 let cancelled: Value = waiting.await??.error_for_status()?.json().await?;
394 assert_eq!(cancelled["status"], "cancelled");
395 let snapshot: Value = client
396 .get(format!("http://{addr}/v1/threads/{}", thread.id))
397 .send()
398 .await?
399 .error_for_status()?
400 .json()
401 .await?;
402 let receipts = snapshot["command_receipts"]
403 .as_array()
404 .context("snapshot command receipts")?;
405 assert_eq!(receipts.len(), 3);
406 assert_eq!(receipts[0]["text"], "1");
407 assert_eq!(receipts[1]["status"], "failed");
408 assert_eq!(receipts[2]["status"], "cancelled");
409 assert!(receipts.iter().all(|receipt| {
410 receipt["id"]
411 .as_str()
412 .is_some_and(|id| id.starts_with("command_"))
413 && receipt["created_at"].is_string()
414 }));
415 let submit_request = json!({ "name":"native-submit", "args":"", "registration_id":submit["registration_id"], "operation_key":"submit-once", "expected_workspace":thread.workspace });
416 let submitted: Value = client
417 .post(&command_url)
418 .json(&submit_request)
419 .send()
420 .await?
421 .error_for_status()?
422 .json()
423 .await?;
424 assert_eq!(submitted["status"], "completed", "{submitted}");
425 let turn_id = submitted["turn"]["id"]
426 .as_str()
427 .context("Engine-admitted turn")?;
428 assert_eq!(
429 wait_for_terminal_turn_status(&client, addr, &thread.id, turn_id, Duration::from_secs(20))
430 .await?,
431 "completed"
432 );
433 let replayed_submit: Value = client
434 .post(&command_url)
435 .json(&submit_request)
436 .send()
437 .await?
438 .error_for_status()?
439 .json()
440 .await?;
441 assert_eq!(replayed_submit["turn"]["id"], turn_id);
442 assert_eq!(replayed_submit["idempotent_replay"], true);
443 assert_eq!(model.captured_requests().len(), 1);
444 let detail = runtime_threads.get_thread_detail(&thread.id).await?;
445 assert_eq!(
446 serde_json::to_value(&detail.command_receipts)?,
447 snapshot["command_receipts"]
448 );
449 let user_item = detail
450 .items
451 .iter()
452 .find(|item| item.kind == TurnItemKind::UserMessage)
453 .context("command input item")?;
454 assert_eq!(
455 user_item.metadata.as_ref().context("command provenance")?["input_provenance"],
456 "extension_command"
457 );
458 assert_eq!(
459 user_item.detail.as_deref(),
460 Some("Command-generated prompt")
461 );
462 let owner: Value = serde_json::from_slice(&fs::read(
463 runtime_threads
464 .session_store_binding()
465 .data_dir
466 .join("owner.json"),
467 )?)?;
468 let owner_id = owner["owner_id"].as_str().context("Runtime store owner")?;
469 for (key, original_request, original_result, recover_turn) in [
470 ("orphan-show", &show_request, &shown, false),
471 ("orphan-submit", &submit_request, &submitted, true),
472 ] {
473 let mut request = original_request.clone();
474 request["operation_key"] = json!(key);
475 let fingerprint = codewhale_runtime::hashing::sha256_hex(format!(
476 "runtime-turn-operation{sep}{owner_id}{sep}{}{sep}{key}",
477 thread.id,
478 sep = char::from(31)
479 ));
480 let request_fingerprint = codewhale_runtime::hashing::sha256_hex(
481 codewhale_runtime::hashing::canonical_json(&json!({
482 "name":request["name"], "args":request["args"], "registration_id":request["registration_id"], "expected_workspace":request["expected_workspace"],
483 })),
484 );
485 runtime_threads.emit_event_for_test(&thread.id, None, "extension_command_started", json!({
486 "operation_fingerprint":fingerprint, "request_fingerprint":request_fingerprint,
487 "name":request["name"], "args":request["args"], "extension":original_result["extension"],
488 })).await?;
489 let admitted = if recover_turn {
490 model.push_turn(
491 codewhale_engine::llm_client::mock::canned::simple_text_turn(
492 "Recovered admitted turn",
493 ),
494 );
495 let turn = runtime_threads
496 .start_turn(
497 &thread.id,
498 StartTurnRequest {
499 prompt: "Already-admitted command turn".into(),
500 operation_key: Some(format!("extension-command-{fingerprint}")),
501 ..Default::default()
502 },
503 )
504 .await?;
505 assert_eq!(
506 wait_for_terminal_turn_status(
507 &client,
508 addr,
509 &thread.id,
510 &turn.id,
511 Duration::from_secs(20),
512 )
513 .await?,
514 "completed",
515 "{}",
516 turn_detail(&client, addr, &thread.id, &turn.id).await?
517 );
518 let store = codewhale_engine::runtime_threads::RuntimeThreadStore::open(
519 runtime_threads.session_store_binding().data_dir,
520 )?;
521 let mut input =
522 store.load_item(turn.item_ids.first().context("orphan command input")?)?;
523 input.metadata = Some(json!({
524 "input_provenance": "extension_command", "command_operation": fingerprint,
525 "extension": original_result["extension"],
526 }));
527 store.save_item(&input)?;
528 client
529 .delete(format!("{command_url}/{key}"))
530 .send()
531 .await?
532 .error_for_status()?;
533 Some(turn)
534 } else {
535 None
536 };
537 let recovered: Value = client
538 .get(format!("{command_url}/{key}"))
539 .send()
540 .await?
541 .error_for_status()?
542 .json()
543 .await?;
544 assert_eq!(recovered["status"], "failed");
545 assert!(
546 recovered["text"]
547 .as_str()
548 .is_some_and(|text| text.contains("uncertain") && text.contains("not rerun"))
549 );
550 assert_eq!(recovered["extension"], original_result["extension"]);
551 if let Some(turn) = admitted {
552 assert_eq!(recovered["turn"]["id"], turn.id);
553 }
554 let replay: Value = client
555 .post(&command_url)
556 .json(&request)
557 .send()
558 .await?
559 .error_for_status()?
560 .json()
561 .await?;
562 assert_eq!(replay, recovered);
563 let repeated: Value = client
564 .get(format!("{command_url}/{key}"))
565 .send()
566 .await?
567 .error_for_status()?
568 .json()
569 .await?;
570 assert_eq!(repeated, recovered);
571 }
572 for (key, owned) in [
573 ("submit-acknowledgement-uncertain", true),
574 ("submit-unrelated-key-conflict", false),
575 ] {
576 let mut uncertain_request = submit_request.clone();
577 uncertain_request["operation_key"] = json!(key);
578 let uncertain_fingerprint = codewhale_runtime::hashing::sha256_hex(format!(
579 "runtime-turn-operation{sep}{owner_id}{sep}{}{sep}{key}",
580 thread.id,
581 sep = char::from(31)
582 ));
583 model.push_turn(
584 codewhale_engine::llm_client::mock::canned::simple_text_turn(
585 "Existing operation result",
586 ),
587 );
588 let accepted = runtime_threads
589 .start_turn(
590 &thread.id,
591 StartTurnRequest {
592 prompt: "Existing operation input".into(),
593 operation_key: Some(format!("extension-command-{uncertain_fingerprint}")),
594 ..Default::default()
595 },
596 )
597 .await?;
598 assert_eq!(
599 wait_for_terminal_turn_status(
600 &client,
601 addr,
602 &thread.id,
603 &accepted.id,
604 Duration::from_secs(20),
605 )
606 .await?,
607 "completed",
608 "{}",
609 turn_detail(&client, addr, &thread.id, &accepted.id).await?
610 );
611 if owned {
612 let store = codewhale_engine::runtime_threads::RuntimeThreadStore::open(
613 runtime_threads.session_store_binding().data_dir,
614 )?;
615 let mut input =
616 store.load_item(accepted.item_ids.first().context("owned command input")?)?;
617 input.metadata = Some(json!({
618 "input_provenance": "extension_command", "command_operation": uncertain_fingerprint,
619 "extension": submitted["extension"],
620 }));
621 store.save_item(&input)?;
622 }
623 let uncertain: Value = client
624 .post(&command_url)
625 .json(&uncertain_request)
626 .send()
627 .await?
628 .error_for_status()?
629 .json()
630 .await?;
631 assert_eq!(uncertain["status"], "failed");
632 if owned {
633 assert_eq!(uncertain["turn"]["id"], accepted.id);
634 assert_eq!(uncertain["thread"]["id"], thread.id);
635 assert!(uncertain["text"].as_str().is_some_and(|text| {
636 text.contains("uncertain")
637 && text.contains("recovered")
638 && text.contains("not rerun")
639 }));
640 } else {
641 assert!(uncertain["turn"].is_null());
642 assert!(uncertain["thread"].is_null());
643 assert!(uncertain["text"].as_str().is_some_and(|text| {
644 text.contains("no admitted turn was recovered")
645 && text.contains("different turn request")
646 }));
647 }
648 let uncertain_replay: Value = client
649 .post(&command_url)
650 .json(&uncertain_request)
651 .send()
652 .await?
653 .error_for_status()?
654 .json()
655 .await?;
656 assert_eq!(uncertain_replay["turn"], uncertain["turn"]);
657 assert_eq!(uncertain_replay["text"], uncertain["text"]);
658 assert_eq!(uncertain_replay["idempotent_replay"], true);
659 }
660 assert_eq!(model.captured_requests().len(), 4);
661 let mut fresh_show = show_request.clone();
662 fresh_show["operation_key"] = json!("after-orphans");
663 let fresh: Value = client
664 .post(&command_url)
665 .json(&fresh_show)
666 .send()
667 .await?
668 .error_for_status()?
669 .json()
670 .await?;
671 assert_eq!(fresh["text"], "2");
672 assert!(
673 runtime_threads
674 .get_thread_detail(&thread.id)
675 .await?
676 .command_receipts
677 .iter()
678 .any(|receipt| receipt.text.contains("uncertain"))
679 );
680 plugins
681 .disable("native-command-fixture")
682 .map_err(anyhow::Error::msg)?;
683 codewhale_engine::extension_host::plugins_changed(Arc::new(plugins));
684 extension_manager
685 .reconcile()
686 .await
687 .map_err(anyhow::Error::msg)?;
688 let mut plugins = codewhale_plugins::discovery::discover_with_config(&fixture.config);
689 plugins
690 .enable("native-command-fixture")
691 .map_err(anyhow::Error::msg)?;
692 codewhale_engine::extension_host::plugins_changed(Arc::new(plugins));
693 extension_manager
694 .reconcile()
695 .await
696 .map_err(anyhow::Error::msg)?;
697 let mut stale_request = show_request.clone();
698 stale_request["operation_key"] = json!("stale-after-reload");
699 let stale = client
700 .post(&command_url)
701 .json(&stale_request)
702 .send()
703 .await?;
704 assert_eq!(stale.status(), StatusCode::CONFLICT);
705 let stale: Value = stale.json().await?;
706 assert_eq!(stale["error"]["code"], "command_not_started");
707 let old_replay: Value = client
708 .post(&command_url)
709 .json(&show_request)
710 .send()
711 .await?
712 .error_for_status()?
713 .json()
714 .await?;
715 assert_eq!(old_replay["extension"], shown["extension"]);
716 assert_eq!(old_replay["text"], "1");
717 runtime_threads.shutdown_and_wait().await?;
718 extension_manager.shutdown().await;
719 handle.abort();
720 Ok(())
721 }
722
723 /// B4: `GET /v1/hooks` serves the hook set Runtime threads run, from the
724 /// engine's own loader, with credential-shaped values masked.
725 #[tokio::test]
726 async fn get_v1_hooks_serves_the_runtime_hook_set() -> Result<()> {
727 let _env = lock_test_env();
728 let temp = tempfile::tempdir()?;
729 let root = temp.path().join("hooks-route");
730 let sessions_dir = root.join("sessions");
731 let workspace = root.join("workspace");
732 fs::create_dir_all(&workspace)?;
733 let config = {
734 let __cw_config_init_0_0 = Some(codewhale_config::hooks::HooksConfig {
735 hooks: vec![
736 codewhale_config::hooks::Hook::new(
737 codewhale_config::hooks::HookEvent::ToolCallAfter,
738 "curl -H 'Authorization: Bearer sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789' https://example.invalid",
739 )
740 .with_name("notify"),
741 ],
742 enabled: true,
743 ..codewhale_config::hooks::HooksConfig::default()
744 });
745 let mut __cw_config_init_0_value: Config = Config::default();
746 __cw_config_init_0_value.hooks = __cw_config_init_0_0;
747 __cw_config_init_0_value
748 };
749
750 let Some((addr, _runtime_threads, handle)) =
751 spawn_test_server_with_root_token_mobile_workspace_and_overrides(
752 root,
753 sessions_dir,
754 None,
755 false,
756 workspace,
757 TestServerOverrides {
758 config: Some(config),
759 ..TestServerOverrides::default()
760 },
761 )
762 .await?
763 else {
764 return Ok(());
765 };
766 let client = codewhale_release::tls::reqwest_client();
767 let body: serde_json::Value = client
768 .get(format!("http://{addr}/v1/hooks"))
769 .send()
770 .await?
771 .error_for_status()?
772 .json()
773 .await?;
774 assert_eq!(body["enabled"], true);
775 let hooks = body["hooks"].as_array().expect("hooks array");
776 assert_eq!(hooks.len(), 1, "{body}");
777 assert_eq!(hooks[0]["name"], "notify");
778 assert_eq!(hooks[0]["event"], "tool_call_after");
779 assert_eq!(hooks[0]["source"], "global");
780 let command = hooks[0]["command"].as_str().expect("command");
781 assert!(command.starts_with("curl"), "{command}");
782 assert!(!command.contains("sk-ant-api03-AbCd"), "{command}");
783
784 let missing = client
785 .get(format!("http://{addr}/v1/hooks?thread_id=thr_missing"))
786 .send()
787 .await?;
788 assert_eq!(missing.status(), StatusCode::NOT_FOUND);
789 handle.abort();
790 Ok(())
791 }
792
793 #[test]
794 fn hook_listing_masks_url_paths_and_userinfo() {
795 assert_eq!(
796 redact_hook_command_for_listing(
797 "curl -X POST https://hooks.slack.com/services/T000/B000/XXXXsecret -d @-"
798 ),
799 "curl -X POST https://hooks.slack.com/[redacted] -d @-"
800 );
801 assert_eq!(
802 redact_hook_command_for_listing("notify 'https://user:pw@example.test/hook?k=v'"),
803 "notify 'https://example.test/[redacted]'"
804 );
805 assert_eq!(
806 redact_hook_command_for_listing("ping https://example.test"),
807 "ping https://example.test"
808 );
809 assert_eq!(
810 redact_hook_command_for_listing("./scripts/lint.sh --fix"),
811 "./scripts/lint.sh --fix"
812 );
813 }
814
815 async fn turn_detail(
816 client: &reqwest::Client,
817 addr: SocketAddr,
818 thread_id: &str,
819 turn_id: &str,
820 ) -> Result<String> {
821 let detail: Value = client
822 .get(format!("http://{addr}/v1/threads/{thread_id}"))
823 .send()
824 .await?
825 .error_for_status()?
826 .json()
827 .await?;
828 Ok(detail["turns"]
829 .as_array()
830 .and_then(|turns| turns.iter().find(|turn| turn["id"] == turn_id))
831 .map_or_else(|| "turn absent".to_string(), Value::to_string))
832 }
833
834 // ── Remote built-in execution ──
835
836 /// A catalog that serves exactly one built-in remotely, so the route's name
837 /// gate and snapshot hand-off can be observed without the terminal host.
838 struct RemoteBuiltinCatalog;
839
840 impl CommandCatalog for RemoteBuiltinCatalog {
841 fn answers_to(&self, name: &str) -> bool {
842 name == "system"
843 }
844 fn builtins(&self) -> Vec<BuiltinCommand> {
845 vec![builtin("system", vec!["xitong".to_string()])]
846 }
847 fn user_commands(&self, _workspace: &Path) -> Vec<UserCommand> {
848 Vec::new()
849 }
850 fn serves_builtin(&self, name: &str) -> bool {
851 matches!(name.trim_start_matches('/'), "system" | "xitong")
852 }
853 fn execute_builtin(
854 &self,
855 name: &str,
856 _args: Option<&str>,
857 host: &codewhale_engine::command_catalog::BuiltinCommandHostSnapshot,
858 ) -> Option<codewhale_engine::command_catalog::BuiltinCommandExecution> {
859 if !self.serves_builtin(name) {
860 return None;
861 }
862 Some(codewhale_engine::command_catalog::BuiltinCommandExecution {
863 name: "system".to_string(),
864 text: format!(
865 "{}|{}|{}",
866 host.mode_label,
867 host.model,
868 match &host.system_prompt {
869 codewhale_command_contract::facets::DebugSystemPrompt::None => 0,
870 codewhale_command_contract::facets::DebugSystemPrompt::Text(text) => text.len(),
871 codewhale_command_contract::facets::DebugSystemPrompt::Blocks(blocks) =>
872 blocks.iter().map(String::len).sum(),
873 }
874 ),
875 is_error: false,
876 text_only: true,
877 })
878 }
879 }
880
881 /// B5: `POST /v1/threads/{id}/commands/builtin` executes only the names the
882 /// installed host serves, and answers everything else like an unknown name.
883 #[tokio::test]
884 async fn post_thread_builtin_command_serves_only_the_host_allowlist() -> Result<()> {
885 let _env = lock_test_env();
886 let temp = tempfile::tempdir()?;
887 let token = "builtin-route-fixture-token";
888 let root = temp.path().join("builtin-commands-route");
889 let sessions_dir = root.join("sessions");
890 let workspace = root.join("workspace");
891 fs::create_dir_all(&workspace)?;
892 let _catalog =
893 codewhale_engine::command_catalog::CatalogGuard::install(Arc::new(RemoteBuiltinCatalog));
894
895 let Some((addr, runtime_threads, handle)) = spawn_test_server_with_root_token_mobile_workspace(
896 root,
897 sessions_dir,
898 Some(token.to_string()),
899 false,
900 workspace,
901 )
902 .await?
903 else {
904 return Ok(());
905 };
906 let client = codewhale_release::tls::reqwest_client();
907 let thread = runtime_threads
908 .create_thread(CreateThreadRequest::default())
909 .await?;
910 let url = format!("http://{addr}/v1/threads/{}/commands/builtin", thread.id);
911
912 let unauthorized = client
913 .post(&url)
914 .json(&json!({ "name": "system" }))
915 .send()
916 .await?;
917 assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);
918
919 let cold = client
920 .post(&url)
921 .bearer_auth(token)
922 .json(&json!({ "name": "system" }))
923 .send()
924 .await?;
925 assert_eq!(cold.status(), StatusCode::CONFLICT, "cold engine");
926 runtime_threads.get_engine(&thread.id).await?;
927
928 // Not on the host's remote surface: the same answer an unknown name gets.
929 for name in ["balance", "cache", "not-a-command"] {
930 let response = client
931 .post(&url)
932 .bearer_auth(token)
933 .json(&json!({ "name": name }))
934 .send()
935 .await?;
936 assert_eq!(response.status(), StatusCode::NOT_FOUND, "{name}");
937 }
938
939 // A served name (alias spelling included) reaches the host with the
940 // thread's own state, and its text comes back unchanged.
941 for name in ["system", "/system", "xitong"] {
942 let body: Value = client
943 .post(&url)
944 .bearer_auth(token)
945 .json(&json!({ "name": name, "args": "ignored" }))
946 .send()
947 .await?
948 .error_for_status()?
949 .json()
950 .await?;
951 assert_eq!(body["name"], "system");
952 assert_eq!(body["is_error"], false);
953 assert_eq!(body["text_only"], true);
954 // One snapshot field per segment, so a route that assembled the
955 // wrong thread's state cannot pass.
956 let text = body["text"].as_str().context("builtin text")?;
957 let fields: Vec<&str> = text.split('|').collect();
958 assert_eq!(fields.len(), 3, "{text}");
959 assert!(!fields[0].is_empty(), "mode label: {text}");
960 assert_eq!(fields[1], thread.model, "model: {text}");
961 let prompt_len: usize = fields[2].parse().context("system prompt length")?;
962 assert!(prompt_len > 0, "effective system prompt reported: {text}");
963 }
964
965 // The thread id is still the address: a missing thread stays 404.
966 let missing = client
967 .post(format!(
968 "http://{addr}/v1/threads/thr_missing/commands/builtin"
969 ))
970 .bearer_auth(token)
971 .json(&json!({ "name": "system" }))
972 .send()
973 .await?;
974 assert_eq!(missing.status(), StatusCode::NOT_FOUND);
975
976 handle.abort();
977 Ok(())
978 }
979
980 static SHIP_REVOKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
981
982 struct ShipCatalog;
983 impl CommandCatalog for ShipCatalog {
984 fn answers_to(&self, _name: &str) -> bool {
985 false
986 }
987 fn builtins(&self) -> Vec<BuiltinCommand> {
988 Vec::new()
989 }
990 fn user_commands(&self, _workspace: &Path) -> Vec<UserCommand> {
991 let mut ship = user("ship");
992 ship.builtin_bindings.clear();
993 ship.plugin_id = Some("user/fixture/release-kit".into());
994 vec![ship]
995 }
996 fn expands_user_commands(&self) -> bool {
997 true
998 }
999 fn expand_user_command(
1000 &self,
1001 _workspace: &Path,
1002 _plugins: &codewhale_plugins::PluginRegistry,
1003 input: &str,
1004 ) -> Option<Result<codewhale_engine::command_catalog::ExpandedUserCommand, String>> {
1005 (input.split_whitespace().next() == Some("/ship")).then(|| {
1006 if SHIP_REVOKED.load(std::sync::atomic::Ordering::SeqCst) {
1007 return Err("Plugin command '/ship' was denied: revoked".into());
1008 }
1009 Ok(codewhale_engine::command_catalog::ExpandedUserCommand {
1010 name: "ship".into(),
1011 message: "Reply with the single word shipped. Do not use tools.".into(),
1012 allowed_tools: Some(vec!["read_file".into()]),
1013 plugin_id: Some("user/fixture/release-kit".into()),
1014 })
1015 })
1016 }
1017 }
1018
1019 #[tokio::test]
1020 async fn a_runtime_turn_sends_a_prompt_bound_user_command_as_its_expanded_template() -> Result<()> {
1021 let _env = lock_test_env();
1022 let temp = tempfile::tempdir()?;
1023 let workspace = temp.path().join("workspace");
1024 fs::create_dir_all(&workspace)?;
1025 SHIP_REVOKED.store(false, std::sync::atomic::Ordering::SeqCst);
1026 let _catalog = codewhale_engine::command_catalog::CatalogGuard::install(Arc::new(ShipCatalog));
1027 let config = Config::default().with_legacy_root(
1028 Some("ship-fixture-key".into()),
1029 Some("http://127.0.0.1:1/v1".into()),
1030 );
1031 let Some((addr, runtime_threads, handle)) =
1032 spawn_test_server_with_root_token_mobile_workspace_and_overrides(
1033 temp.path().join("runtime"),
1034 temp.path().join("sessions"),
1035 None,
1036 false,
1037 workspace,
1038 TestServerOverrides {
1039 config: Some(config),
1040 ..TestServerOverrides::default()
1041 },
1042 )
1043 .await?
1044 else {
1045 return Ok(());
1046 };
1047 let client = codewhale_release::tls::reqwest_client();
1048 let model = Arc::new(codewhale_engine::llm_client::mock::MockLlmClient::new(
1049 vec![codewhale_engine::llm_client::mock::canned::simple_text_turn("shipped")],
1050 ));
1051 runtime_threads.set_test_model_client(model.clone());
1052 let thread = runtime_threads
1053 .create_thread(CreateThreadRequest {
1054 model: Some("deepseek-v4-pro".into()),
1055 ..Default::default()
1056 })
1057 .await?;
1058
1059 let catalog: Value = client
1060 .get(format!("http://{addr}/v1/commands?thread_id={}", thread.id))
1061 .send()
1062 .await?
1063 .error_for_status()?
1064 .json()
1065 .await?;
1066 let ship = catalog["commands"]
1067 .as_array()
1068 .and_then(|rows| rows.iter().find(|row| row["name"] == "ship"))
1069 .context("ship row")?;
1070 assert_eq!(ship["binding"], "prompt");
1071 assert_eq!(ship["runtime_expands"], true);
1072
1073 let started: Value = client
1074 .post(format!("http://{addr}/v1/threads/{}/turns", thread.id))
1075 .json(&json!({ "prompt": "/ship", "operation_key": "ship-once" }))
1076 .send()
1077 .await?
1078 .error_for_status()?
1079 .json()
1080 .await?;
1081 assert_eq!(started["user_command"]["name"], "ship");
1082 assert_eq!(
1083 started["user_command"]["plugin_id"],
1084 "user/fixture/release-kit"
1085 );
1086 assert_eq!(started["turn"]["input_summary"], "/ship");
1087 let turn_id = started["turn"]["id"].as_str().context("turn id")?;
1088 assert_eq!(
1089 wait_for_terminal_turn_status(&client, addr, &thread.id, turn_id, Duration::from_secs(20))
1090 .await?,
1091 "completed"
1092 );
1093 let requests = model.captured_requests();
1094 assert_eq!(requests.len(), 1);
1095 let sent = format!("{:?}", requests[0]);
1096 assert!(
1097 sent.contains("Reply with the single word shipped. Do not use tools."),
1098 "the model must receive the command template: {sent}"
1099 );
1100 assert!(!sent.contains("\"/ship\""), "{sent}");
1101
1102 SHIP_REVOKED.store(true, std::sync::atomic::Ordering::SeqCst);
1103 let retry = client
1104 .post(format!("http://{addr}/v1/threads/{}/turns", thread.id))
1105 .json(&json!({ "prompt": "/ship", "operation_key": "ship-once" }))
1106 .send()
1107 .await?;
1108 assert_eq!(retry.status(), StatusCode::OK);
1109 let retry: Value = retry.json().await?;
1110 assert_eq!(retry["idempotent_replay"], true);
1111 assert_eq!(retry["turn"]["id"], turn_id);
1112 let denied = client
1113 .post(format!("http://{addr}/v1/threads/{}/turns", thread.id))
1114 .json(&json!({ "prompt": "/ship", "operation_key": "ship-twice" }))
1115 .send()
1116 .await?;
1117 assert_eq!(denied.status(), StatusCode::UNPROCESSABLE_ENTITY);
1118 let denied: Value = denied.json().await?;
1119 assert_eq!(denied["error"]["code"], "user_command_denied");
1120 assert_eq!(model.captured_requests().len(), 1);
1121 SHIP_REVOKED.store(false, std::sync::atomic::Ordering::SeqCst);
1122 handle.abort();
1123 Ok(())
1124 }
1125
1125 lines RUST