返回 CodeWhale
tests.rs
1 //! The TypeScript half of the protocol, generated from the Rust types.
2 //!
3 //! `schemars` reads each wire type's serde shape (field names, `Option` and
4 //! `default` fields, `deny_unknown_fields`, tags); [`render`] normalizes that
5 //! into the small vocabulary the host's validator checks and renders
6 //! `extension-host/src/protocol.generated.ts`. The committed file must equal
7 //! the rendering: re-record it with `CODEWHALE_CONFORMANCE_UPDATE=1` (refused
8 //! under CI, like every conformance golden), then rebuild `dist/`.
9 //!
10 //! Known limit: a wire shape outside that vocabulary (floats, inline
11 //! objects, multi-variant unions in params) panics here rather than being approximated.
12
13 use std::collections::{BTreeMap, BTreeSet};
14 use std::fmt::Write as _;
15 use std::path::Path;
16
17 use codewhale_app_server_protocol::schema::{
18 Def, Field, SchemaMode, Ty, innermost, parse_def, quote, ref_name, typescript_defs,
19 };
20 use schemars::generate::SchemaSettings;
21 use schemars::{Schema, SchemaGenerator};
22
23 // `Value` and every wire type come from the parent module.
24 use super::*;
25
26 /// The params type of every method in [`METHODS`].
27 fn params_schema(method: &str, generator: &mut SchemaGenerator) -> Schema {
28 match method {
29 "host/initialize" => generator.subschema_for::<InitializeParams>(),
30 "host/ping" | "host/shutdown" | "host/ready" => generator.subschema_for::<EmptyParams>(),
31 "ext/activate" => generator.subschema_for::<ActivateParams>(),
32 "ext/deactivate" => generator.subschema_for::<DeactivateParams>(),
33 "tool/call" => generator.subschema_for::<ToolCallParams>(),
34 "command/run" => generator.subschema_for::<CommandRunParams>(),
35 "hook/evaluate" => generator.subschema_for::<HookEvaluateParams>(),
36 "plugin_route/dispatch" => generator.subschema_for::<PluginRouteDispatchParams>(),
37 "harness/run" => generator.subschema_for::<HarnessRunParams>(),
38 "exec/redeem" => generator.subschema_for::<ExecutionRedeemParams>(),
39 "mcp/open" => generator.subschema_for::<McpOpenParams>(),
40 "mcp/request" => generator.subschema_for::<McpRequestParams>(),
41 "mcp/close" => generator.subschema_for::<McpCloseParams>(),
42 "proc/launch" => generator.subschema_for::<ProcLaunchParams>(),
43 "proc/read" => generator.subschema_for::<ProcSessionParams>(),
44 "proc/write" => generator.subschema_for::<ProcWriteParams>(),
45 "proc/close" => generator.subschema_for::<ProcSessionParams>(),
46 "net/start" => generator.subschema_for::<ProcLaunchParams>(),
47 "net/fetch" => generator.subschema_for::<NetFetchParams>(),
48 "net/read" | "net/release" => generator.subschema_for::<NetReadParams>(),
49 "net/close" => generator.subschema_for::<ProcSessionParams>(),
50
51 "$/cancel" => generator.subschema_for::<CancelParams>(),
52 "host/hello" => generator.subschema_for::<HelloParams>(),
53 "registry/register" => generator.subschema_for::<RegisterParams>(),
54 "registry/unregister" => generator.subschema_for::<UnregisterParams>(),
55 "core/call" => generator.subschema_for::<CoreCallParams>(),
56 "session/checkpoint" => generator.subschema_for::<SessionCheckpointParams>(),
57 "user-questions/ask" => generator.subschema_for::<UserQuestionParams>(),
58 "subagent/start" => generator.subschema_for::<SubagentStartParams>(),
59 "subagent/result" | "subagent/dispose" => generator.subschema_for::<SubagentHandleParams>(),
60 "subagent/prompt" => generator.subschema_for::<SubagentPromptParams>(),
61 "dsh/broker" => generator.subschema_for::<DshBrokerParams>(),
62 "ext/faulted" => generator.subschema_for::<FaultedParams>(),
63 "log" => generator.subschema_for::<LogParams>(),
64 other => panic!("method `{other}` has no params type in the TypeScript generator"),
65 }
66 }
67
68 /// The validator's kind for `ty`: a string enum is inlined, an object is a
69 /// reference into `SHAPES`.
70 fn kind(ty: &Ty, defs: &BTreeMap<String, Def>) -> String {
71 match ty {
72 Ty::Nullable(_) => panic!("host validator does not accept nullable fields"),
73 Ty::String => "'string'".into(),
74 Ty::Boolean => "'boolean'".into(),
75 Ty::Uint => "'uint'".into(),
76 Ty::Integer => "'integer'".into(),
77 Ty::Object => "'object'".into(),
78 Ty::Json => "'json'".into(),
79 Ty::Ref(name) => match &defs[name] {
80 Def::Object { .. } => format!("{{ ref: {} }}", quote(name)),
81 Def::Enum(values) => format!(
82 "{{ enum: [{}] }}",
83 values
84 .iter()
85 .map(|v| quote(v))
86 .collect::<Vec<_>>()
87 .join(", ")
88 ),
89 Def::Union(_) => panic!("{name}: the host validator does not check unions"),
90 },
91 Ty::Const(value) => format!("{{ enum: [{}] }}", quote(value)),
92 Ty::Array(item) => format!("{{ items: {} }}", kind(item, defs)),
93 }
94 }
95
96 /// The kinds of the `fields` that are (or are not) `required`.
97 fn kinds(fields: &[Field], required: bool, defs: &BTreeMap<String, Def>) -> String {
98 let rendered: Vec<String> = fields
99 .iter()
100 .filter(|field| field.required == required)
101 .map(|field| format!("{}: {}", field.name, kind(&field.ty, defs)))
102 .collect();
103 if rendered.is_empty() {
104 "{}".into()
105 } else {
106 format!("{{ {} }}", rendered.join(", "))
107 }
108 }
109
110 const HEADER: &str = "\
111 // @generated from the Rust protocol types in crates/engine/src/extension_host/protocol.rs
112 // by `extension_host::protocol::tests`. Do not edit: change the Rust side, re-record with
113 // CODEWHALE_CONFORMANCE_UPDATE=1 cargo test -p codewhale-tui --lib extension_host::protocol
114 // and rebuild dist/ with `npm run build`.
115
116 ";
117
118 const VALIDATOR_TYPES: &str = "
119 /** A field's wire kind: the Rust field's serde type, normalized for validation. */
120 export type Kind =
121 | 'string'
122 | 'boolean'
123 | 'uint'
124 | 'integer'
125 | 'object'
126 | 'json'
127 | { readonly ref: string }
128 | { readonly enum: readonly string[] }
129 | { readonly items: Kind }
130
131 /** An object's fields; `strict` is Rust's `deny_unknown_fields`. */
132 export interface Shape {
133 readonly strict: boolean
134 readonly required: { readonly [field: string]: Kind }
135 readonly optional: { readonly [field: string]: Kind }
136 }
137 ";
138
139 /// Render `protocol.generated.ts` from [`METHODS`] and the wire types.
140 fn render() -> String {
141 let mut generator = SchemaSettings::draft2020_12().into_generator();
142 let methods: Vec<(&MethodSpec, String)> = METHODS
143 .iter()
144 .map(|spec| {
145 let schema = params_schema(spec.name, &mut generator);
146 let name = ref_name(schema.as_value())
147 .unwrap_or_else(|| panic!("{}: params must be a named type", spec.name));
148 (spec, name)
149 })
150 .collect();
151 let error = generator.subschema_for::<RpcErrorWire>();
152 let error = ref_name(error.as_value()).expect("RpcErrorWire is a named type");
153 // Results are typed for the host, not validated by it.
154 let _ = generator.subschema_for::<RegisterResult>();
155 let _ = generator.subschema_for::<ActivateResult>();
156 let _ = generator.subschema_for::<DeactivateResult>();
157 let _ = generator.subschema_for::<ToolResultWire>();
158 let _ = generator.subschema_for::<CommandResultWire>();
159 let _ = generator.subschema_for::<HookVerdictWire>();
160 let _ = generator.subschema_for::<PluginRouteDispatchResult>();
161 let _ = generator.subschema_for::<crate::tools::user_input::UserInputResponse>();
162 let defs: BTreeMap<String, Def> = generator
163 .definitions()
164 .iter()
165 .map(|(name, schema)| (name.clone(), parse_def(name, schema, SchemaMode::Host)))
166 .collect();
167
168 // What the validator checks: every params type and the error object,
169 // with the objects they reference.
170 let mut validated = BTreeSet::new();
171 let mut pending: Vec<String> = methods
172 .iter()
173 .map(|(_, name)| name.clone())
174 .chain([error])
175 .collect();
176 while let Some(name) = pending.pop() {
177 if let Def::Object { fields, .. } = &defs[&name]
178 && validated.insert(name.clone())
179 {
180 for field in fields {
181 if let Ty::Ref(name) = innermost(&field.ty) {
182 pending.push(name.clone());
183 }
184 }
185 }
186 }
187
188 let mut out = String::from(HEADER);
189 let magic = std::str::from_utf8(&MAGIC).expect("ASCII magic");
190 let _ = writeln!(out, "export const PROTOCOL_VERSION = {PROTOCOL_VERSION}");
191 let _ = writeln!(out, "export const MAGIC_ASCII = {}", quote(magic));
192 let _ = writeln!(out, "export const HEADER_LEN = {HEADER_LEN}");
193 let _ = writeln!(out, "export const MAX_FRAME = {MAX_FRAME}");
194 let _ = writeln!(out, "export const MAX_INFLIGHT = {MAX_INFLIGHT}");
195 let media_types: Vec<String> = crate::image_attach::ACCEPTED_IMAGE_MEDIA_TYPES
196 .iter()
197 .map(|kind| quote(kind))
198 .collect();
199 out.push_str("\nexport const IMAGE_LIMITS = {\n");
200 let _ = writeln!(
201 out,
202 " maxImageBytes: {},",
203 crate::image_attach::MAX_IMAGE_BYTES
204 );
205 let _ = writeln!(
206 out,
207 " maxImagesPerMessage: {},",
208 crate::image_attach::MAX_TOOL_RESULT_IMAGES
209 );
210 let _ = writeln!(
211 out,
212 " maxMessageImageBytes: {},",
213 codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_TOTAL_BYTES
214 );
215 let _ = writeln!(
216 out,
217 " maxImagePixels: {},",
218 crate::image_attach::MAX_IMAGE_PIXELS
219 );
220 let _ = writeln!(
221 out,
222 " maxImageDimension: {},",
223 crate::image_attach::MAX_IMAGE_DIMENSION
224 );
225 let _ = writeln!(out, " mediaTypes: [{}] as const,", media_types.join(", "));
226 out.push_str("} as const\n");
227 out.push_str(
228 "\n/** JSON-RPC error codes used on this channel. */\nexport const ErrorCode = {\n",
229 );
230 for (name, code) in error_code::ALL {
231 let _ = writeln!(out, " {name}: {code},");
232 }
233 out.push_str("} as const\n\nexport type Direction = 'core_to_host' | 'host_to_core'\n");
234 let services: Vec<String> = DshService::EVERY
235 .iter()
236 .map(|service| quote(service.name()))
237 .collect();
238 let _ = writeln!(
239 out,
240 "\nexport const DSH_SERVICES = [{}] as const\nexport type DshService = typeof DSH_SERVICES[number]",
241 services.join(", ")
242 );
243 out.push_str("\n/** Every method either side may send, and the trust tiers it is allowed on; nothing else is admitted. */\nexport const METHODS = [\n");
244 for (spec, params) in &methods {
245 let tiers: Vec<String> = spec.tiers.iter().map(|tier| quote(tier.name())).collect();
246 let _ = writeln!(
247 out,
248 " {{ name: {}, direction: {}, request: {}, params: {}, tiers: [{}] }},",
249 quote(spec.name),
250 quote(spec.direction.as_str()),
251 spec.request,
252 quote(params),
253 tiers.join(", ")
254 );
255 }
256 out.push_str("] as const\n");
257 out.push_str(VALIDATOR_TYPES);
258 out.push_str("\n/** Every method's params, and an error response's `error`. */\nexport const SHAPES: { readonly [name: string]: Shape } = {\n");
259 for name in &validated {
260 let Def::Object { strict, fields, .. } = &defs[name] else {
261 unreachable!("only objects are validated");
262 };
263 let _ = writeln!(out, " {name}: {{");
264 let _ = writeln!(out, " strict: {strict},");
265 let _ = writeln!(out, " required: {},", kinds(fields, true, &defs));
266 let _ = writeln!(out, " optional: {},", kinds(fields, false, &defs));
267 out.push_str(" },\n");
268 }
269 out.push_str("}\n");
270 out.push_str(&typescript_defs(&defs, SchemaMode::Host));
271 out
272 }
273
274 #[test]
275 fn typescript_protocol_is_generated_from_the_rust_types() {
276 let path = Path::new(env!("CARGO_MANIFEST_DIR"))
277 .join("extension-host")
278 .join("src")
279 .join("protocol.generated.ts");
280 if let Err(drift) = crate::test_support::check_golden(&path, &render()) {
281 panic!(
282 "{drift}\nThe TypeScript protocol is generated from protocol.rs; rebuild dist/ after re-recording."
283 );
284 }
285 }
286
287 #[test]
288 fn the_generated_image_limits_match_the_engines_own_constants() {
289 let path = Path::new(env!("CARGO_MANIFEST_DIR"))
290 .join("extension-host")
291 .join("src")
292 .join("protocol.generated.ts");
293 let generated = std::fs::read_to_string(&path).expect("read protocol.generated.ts");
294 let media_types: Vec<String> = crate::image_attach::ACCEPTED_IMAGE_MEDIA_TYPES
295 .iter()
296 .map(|kind| quote(kind))
297 .collect();
298 let expected = format!(
299 "export const IMAGE_LIMITS = {{\n maxImageBytes: {},\n maxImagesPerMessage: {},\n maxMessageImageBytes: {},\n maxImagePixels: {},\n maxImageDimension: {},\n mediaTypes: [{}] as const,\n}} as const",
300 crate::image_attach::MAX_IMAGE_BYTES,
301 crate::image_attach::MAX_TOOL_RESULT_IMAGES,
302 codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_TOTAL_BYTES,
303 crate::image_attach::MAX_IMAGE_PIXELS,
304 crate::image_attach::MAX_IMAGE_DIMENSION,
305 media_types.join(", ")
306 );
307 assert!(
308 generated.contains(&expected),
309 "protocol.generated.ts IMAGE_LIMITS drifted from image_attach/runtime constants:\n{expected}"
310 );
311 }
312
313 /// Authority only the core may hold (CURRENT_DECISIONS §26): the event
314 /// authority, the store, approval, secrets and credentials, the turn loop,
315 /// sessions and the prompt. Names remain refused except the exact reviewed
316 /// invocation-bound checkpoint request, whose state and writer stay in Core.
317 const CORE_ONLY: &[&str] = &[
318 "event",
319 "store",
320 "approv",
321 "secret",
322 "credential",
323 "token",
324 "auth",
325 "turn",
326 "loop",
327 "session",
328 "prompt",
329 ];
330
331 /// Every method, with why it gives the host no core authority. Adding a
332 /// method means adding its row here, in review, with that reason.
333 const REVIEWED: &[(&str, &str, &str)] = &[
334 (
335 "host_to_core",
336 "subagent/start",
337 "opaque live root-invocation subagent ticket and bounded prompt, persona and tool narrowing; the existing nested-call gate plans and approves the typed agent start and SharedSubAgentManager owns the child, its loop, limits and receipts; no host-selected model route, widened tools or second executor",
338 ),
339 (
340 "host_to_core",
341 "subagent/result",
342 "opaque live ticket and a child id this invocation started; reads the manager's settled output only; no session, transcript or other child",
343 ),
344 (
345 "host_to_core",
346 "subagent/dispose",
347 "opaque live ticket and a child id this invocation started; asks the manager to cancel and dispose its own child; no other child, session or turn",
348 ),
349 (
350 "host_to_core",
351 "subagent/prompt",
352 "opaque live root-invocation subagent ticket and a child id this invocation started; delivers a bounded text prompt to that live child through SharedSubAgentManager::followup_child while refusing retired children; no other child, session, approval or model route",
353 ),
354 (
355 "host_to_core",
356 "dsh/broker",
357 "opaque live invocation ticket minted per plugin owner, DSH service and session; Rust redeems it under the same owner, tier, host-generation, lifetime and use checks as core/call, takes the session from the ticket and never from the host, and dispatches only to that service's typed Rust arm, which refuses an unknown method or an unimplemented service; no tool name, approval, credential or model route",
358 ),
359 (
360 "host_to_core",
361 "user-questions/ask",
362 "opaque live root-invocation ticket and bounded question data; the existing Engine owns request identity, human wait, typed answer validation and cancellation; no host-selected session, reply, approval or new turn",
363 ),
364 (
365 "host_to_core",
366 "session/checkpoint",
367 "opaque live root-invocation ticket only; Core captures its own prefix and the existing host persistence owner acknowledges the exact request; no host-supplied session selector, state, writer, restore or turn authority",
368 ),
369 (
370 "core_to_host",
371 "harness/run",
372 "pinned Builtin orchestration of an opaque exact Rust-gated job; no launch, environment, approval or session writer",
373 ),
374 (
375 "host_to_core",
376 "exec/redeem",
377 "Builtin-only host:harness; one single-use Execution grant for a Rust-held caller and prepared launch, current owner/generation/selection checks and bounded process cleanup",
378 ),
379 (
380 "host_to_core",
381 "net/start",
382 "builtin only; opaque Rust HTTP session selectors and exact decoded operation tickets, shared OAuth/egress authority, bounded revocable response reads, no credential exposure",
383 ),
384 (
385 "host_to_core",
386 "net/fetch",
387 "builtin only; opaque Rust HTTP session selectors and exact decoded operation tickets, shared OAuth/egress authority, bounded revocable response reads, no credential exposure",
388 ),
389 (
390 "host_to_core",
391 "net/read",
392 "builtin only; opaque Rust HTTP session selectors and exact decoded operation tickets, shared OAuth/egress authority, bounded revocable response reads, no credential exposure",
393 ),
394 (
395 "host_to_core",
396 "net/release",
397 "builtin only; opaque Rust HTTP session selectors and exact decoded operation tickets, shared OAuth/egress authority, bounded revocable response reads, no credential exposure",
398 ),
399 (
400 "host_to_core",
401 "net/close",
402 "builtin only; opaque Rust HTTP session selectors and exact decoded operation tickets, shared OAuth/egress authority, bounded revocable response reads, no credential exposure",
403 ),
404 (
405 "core_to_host",
406 "mcp/open",
407 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
408 ),
409 (
410 "core_to_host",
411 "mcp/request",
412 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
413 ),
414 (
415 "core_to_host",
416 "mcp/close",
417 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
418 ),
419 (
420 "host_to_core",
421 "proc/launch",
422 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
423 ),
424 (
425 "host_to_core",
426 "proc/read",
427 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
428 ),
429 (
430 "host_to_core",
431 "proc/write",
432 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
433 ),
434 (
435 "host_to_core",
436 "proc/close",
437 "builtin only; Rust mints exact owner/host-generation operation tickets, owns spawn and validates the decoded frame before a pipe write; the SDK only executes the admitted protocol exchange",
438 ),
439 (
440 "core_to_host",
441 "host/initialize",
442 "the core states its limits; the host answers `{}`",
443 ),
444 (
445 "core_to_host",
446 "host/ping",
447 "heartbeat; the host answers `{}`",
448 ),
449 (
450 "core_to_host",
451 "host/shutdown",
452 "bounded teardown, sent by tests only",
453 ),
454 (
455 "core_to_host",
456 "ext/activate",
457 "the core names the reviewed entry and its hash; the host reports tool names",
458 ),
459 (
460 "core_to_host",
461 "ext/deactivate",
462 "sent after the core has already revoked the owner",
463 ),
464 (
465 "core_to_host",
466 "tool/call",
467 "sent only after the core's approval gate has passed the call",
468 ),
469 (
470 "core_to_host",
471 "command/run",
472 "sent only when the user runs the command themselves; the answer is text or a prompt that the core shows or submits through the ordinary turn",
473 ),
474 (
475 "core_to_host",
476 "plugin_route/dispatch",
477 "loopback-only Engine-brokered HTTP route dispatch scoped to one verified plugin owner with bounded request/response bodies and sanitized headers; no raw sockets, credentials, or core authority",
478 ),
479 (
480 "core_to_host",
481 "$/cancel",
482 "the core withdraws its own request",
483 ),
484 (
485 "core_to_host",
486 "hook/evaluate",
487 "the core evaluates a reviewed owner's listener; monotonic proposals are folded and any input revision is re-gated in Rust, with no approval or tool handle exposed",
488 ),
489 (
490 "host_to_core",
491 "host/hello",
492 "handshake facts the core checks against what it launched",
493 ),
494 (
495 "host_to_core",
496 "host/ready",
497 "handshake completion; no payload",
498 ),
499 (
500 "host_to_core",
501 "registry/register",
502 "a proposal the core admits or refuses; an admitted tool always needs approval, and an admitted command only runs when the user invokes it",
503 ),
504 (
505 "host_to_core",
506 "registry/unregister",
507 "the host can only withdraw its own owner's registration",
508 ),
509 (
510 "host_to_core",
511 "core/call",
512 "a request the core serves only for a ticket it minted for a call that already passed its gate, then plans and approves through the same gate as a model's call; the host names a tool and an input, never an approval, a card text, an argv, a URL or a ticket's contents",
513 ),
514 (
515 "host_to_core",
516 "ext/faulted",
517 "a report; the core revokes the owner",
518 ),
519 (
520 "host_to_core",
521 "log",
522 "diagnostic text the core bounds and escapes",
523 ),
524 (
525 "host_to_core",
526 "$/cancel",
527 "the host withdraws its own in-flight request; the core cancels that request's task and drops whatever it produces",
528 ),
529 ];
530
531 /// The CI lint for the host protocol. It covers both directions, host→core
532 /// requests included: [`METHODS`] is every method either parser admits, and
533 /// the TypeScript validator admits only its generated copy, so the host can
534 /// neither send nor answer anything outside it.
535 #[test]
536 fn host_protocol_never_gains_core_authority() {
537 for spec in METHODS {
538 let name = spec.name.to_ascii_lowercase();
539 for word in CORE_ONLY {
540 assert!(
541 !name.contains(word)
542 || (*word == "session"
543 && name == "session/checkpoint"
544 && spec.direction == Direction::HostToCore
545 && spec.request)
546 || (*word == "prompt"
547 && name == "subagent/prompt"
548 && spec.direction == Direction::HostToCore
549 && spec.request),
550 "{} method `{}` reaches for core-only authority (`{word}`); \
551 the extension host must never hold it (CURRENT_DECISIONS §26)",
552 spec.direction.as_str(),
553 spec.name
554 );
555 }
556 }
557 let table: BTreeSet<(&str, &str)> = METHODS
558 .iter()
559 .map(|spec| (spec.direction.as_str(), spec.name))
560 .collect();
561 let reviewed: BTreeSet<(&str, &str)> = REVIEWED
562 .iter()
563 .map(|(direction, name, _)| (*direction, *name))
564 .collect();
565 assert_eq!(
566 table, reviewed,
567 "the method table changed: review each method in REVIEWED with why it gives the host no core authority"
568 );
569 // Nothing is decoded or sent outside the table: every method-shaped
570 // literal in this module is a table row.
571 let literal = regex::Regex::new(r#""([A-Za-z$][\w$-]*/[A-Za-z_]+)""#).expect("regex");
572 let source = include_str!("../protocol.rs");
573 let mut seen = 0;
574 for capture in literal.captures_iter(source) {
575 let name = &capture[1];
576 assert!(
577 METHODS.iter().any(|spec| spec.name == name),
578 "protocol.rs uses method `{name}` outside METHODS"
579 );
580 seen += 1;
581 }
582 assert!(
583 seen >= METHODS.len(),
584 "the source scan matched only {seen} literals"
585 );
586 }
587
588 /// The tier rule, against a table with methods reserved for the built-in tier
589 /// (the production table has none yet): refused to a plugin-tier host in both
590 /// directions, by the parser and by the sender's check, and open methods stay
591 /// open to both.
592 #[test]
593 fn a_method_reserved_for_the_builtin_tier_is_refused_in_both_directions() {
594 const RESERVED: &[MethodSpec] = &[
595 MethodSpec {
596 tiers: &[HostTier::Builtin],
597 ..row(Direction::HostToCore, "test/reserved", true)
598 },
599 MethodSpec {
600 tiers: &[HostTier::Builtin],
601 ..row(Direction::CoreToHost, "test/reserved-in", false)
602 },
603 row(Direction::HostToCore, "test/shared", true),
604 ];
605 use Direction::{CoreToHost, HostToCore};
606 use HostTier::{Builtin, Plugin};
607
608 assert_eq!(
609 admit_in(RESERVED, HostToCore, "test/reserved", Some(1), Builtin),
610 Ok(Some(1))
611 );
612 assert_eq!(
613 admit_in(RESERVED, CoreToHost, "test/reserved-in", None, Builtin),
614 Ok(None)
615 );
616 for (direction, method, id) in [
617 (HostToCore, "test/reserved", Some(1)),
618 (CoreToHost, "test/reserved-in", None),
619 ] {
620 let refused = admit_in(RESERVED, direction, method, id, Plugin).unwrap_err();
621 assert!(
622 refused.0.contains("not allowed on the plugin tier"),
623 "{refused}"
624 );
625 assert!(allowed_in(RESERVED, direction, method, Builtin));
626 assert!(!allowed_in(RESERVED, direction, method, Plugin));
627 }
628 // Open to both tiers, and a name or direction the table lacks is unknown
629 // (not "reserved"), whatever the tier.
630 for tier in HostTier::ALL {
631 assert_eq!(
632 admit_in(RESERVED, HostToCore, "test/shared", Some(2), tier),
633 Ok(Some(2))
634 );
635 assert!(allowed_in(RESERVED, HostToCore, "test/shared", tier));
636 for (direction, method) in [(HostToCore, "test/none"), (CoreToHost, "test/reserved")] {
637 assert!(
638 admit_in(RESERVED, direction, method, Some(3), tier)
639 .unwrap_err()
640 .0
641 .contains("unknown"),
642 "{method}"
643 );
644 assert!(!allowed_in(RESERVED, direction, method, tier));
645 }
646 }
647 }
648
649 /// The production table: `allowed_on` says what each row says, and the
650 /// families the design reserves for the built-in tier (the process broker, the
651 /// fetch proxy and the MCP client; none exist yet) can never be added to the
652 /// plugin tier by accident.
653 #[test]
654 fn production_methods_follow_their_tier_rows_and_reserved_families_stay_builtin_only() {
655 for count in [0, 1, 100] {
656 let mut questions = json!([{
657 "id": "q", "question": "Choose", "header": "",
658 "options": (0..count).map(|index| json!({"label": format!("choice-{index}"), "description": ""})).collect::<Vec<_>>(),
659 "allow_free_text": true, "multi_select": true,
660 }]);
661 if count > 0 {
662 questions[0]["detail"] = json!("Review this exact plan");
663 questions[0]["intent"] =
664 json!({"kind":"plan-review", "approve":"choice-0", "call_id":"plan-call"});
665 }
666 let frame = json!({
667 "jsonrpc": "2.0", "id": 87, "method": "user-questions/ask",
668 "params": { "owner": {"plugin_id":"question-owner", "owner_token":"opaque", "generation":1}, "ticket":"question-ticket", "questions":questions },
669 });
670 for tier in HostTier::ALL {
671 let parsed = parse_host_message(frame.clone(), tier).unwrap();
672 assert_eq!(parsed.to_value(), frame);
673 let HostMessage::Request { request, .. } = parsed else {
674 panic!("wrong question variant")
675 };
676 let HostRequest::UserQuestion(params) = *request else {
677 panic!("wrong question variant")
678 };
679 assert_eq!(params.questions[0].options.len(), count);
680 assert!(parse_core_message(frame.clone(), tier).is_err());
681 for field in ["session_id", "request_id", "require_typed_answers"] {
682 let mut forged = frame.clone();
683 forged["params"][field] = json!("foreign-selector");
684 assert!(parse_host_message(forged, tier).is_err());
685 }
686 }
687 }
688 for spec in METHODS {
689 for tier in HostTier::ALL {
690 assert_eq!(
691 allowed_on(spec.direction, spec.name, tier),
692 spec.tiers.contains(&tier),
693 "{}",
694 spec.name
695 );
696 }
697 assert!(!spec.tiers.is_empty(), "{} allows no tier", spec.name);
698 if ["proc/", "net/", "mcp/"]
699 .iter()
700 .any(|family| spec.name.starts_with(family))
701 {
702 assert_eq!(
703 spec.tiers,
704 &[HostTier::Builtin],
705 "{} is reserved for the built-in tier",
706 spec.name
707 );
708 }
709 }
710 assert!(!allowed_on(
711 Direction::HostToCore,
712 "no/such-method",
713 HostTier::Builtin
714 ));
715 }
716
717 #[test]
718 fn dsh_broker_is_one_strict_envelope_and_names_only_the_closed_service_list() {
719 let frame = json!({
720 "jsonrpc": "2.0", "id": 91, "method": "dsh/broker",
721 "params": {
722 "owner": {"plugin_id": "dsh-owner", "owner_token": "opaque", "generation": 1},
723 "ticket": "broker-ticket", "service": "workspace", "method": "read", "input": {"path": "a"},
724 },
725 });
726 for tier in HostTier::ALL {
727 let parsed = parse_host_message(frame.clone(), tier).unwrap();
728 assert_eq!(parsed.to_value(), frame);
729 let HostMessage::Request { request, .. } = parsed else {
730 panic!("dsh/broker is a request")
731 };
732 let HostRequest::DshBroker(params) = *request else {
733 panic!("wrong broker variant")
734 };
735 assert_eq!(params.service, "workspace");
736 assert!(parse_core_message(frame.clone(), tier).is_err());
737 for field in ["session_id", "call_id", "approval", "name"] {
738 let mut forged = frame.clone();
739 forged["params"][field] = json!("foreign-selector");
740 assert!(parse_host_message(forged, tier).is_err(), "{field}");
741 }
742 for field in ["owner", "ticket", "service", "method", "input"] {
743 let mut missing = frame.clone();
744 missing["params"].as_object_mut().unwrap().remove(field);
745 assert!(parse_host_message(missing, tier).is_err(), "{field}");
746 }
747 let mut notification = frame.clone();
748 notification.as_object_mut().unwrap().remove("id");
749 assert!(parse_host_message(notification, tier).is_err());
750 let mut unknown = frame.clone();
751 unknown["params"]["service"] = json!("vault");
752 assert!(parse_host_message(unknown, tier).is_ok());
753 }
754 let names: Vec<&str> = DshService::EVERY
755 .iter()
756 .map(|service| service.name())
757 .collect();
758 assert_eq!(
759 names,
760 [
761 "workspace",
762 "llm",
763 "network",
764 "settings",
765 "catalog",
766 "terminal",
767 "remote",
768 "attachments",
769 "plugins"
770 ]
771 );
772 assert_eq!(DshService::BUILTIN_ONLY, [DshService::Plugins]);
773 assert!(
774 DshService::ALL
775 .iter()
776 .all(|service| !service.builtin_only())
777 );
778 for service in DshService::EVERY {
779 assert_eq!(DshService::parse(service.name()), Some(service));
780 }
781 assert_eq!(DshService::parse("Workspace"), None);
782 assert_eq!(DshService::parse("vault"), None);
783 }
784
784 lines RUST