返回 CodeWhale
protocol.rs
根目录 / crates / engine / src / extension_host / protocol.rs
1 //! Extension-host protocol v1 — the phase-1 subset, and its source of truth.
2 //!
3 //! Frame: 4-byte magic `CWX1`, u32 little-endian payload length, UTF-8 JSON.
4 //! Envelope: JSON-RPC 2.0. A length prefix (not NDJSON) makes a plugin that
5 //! writes raw bytes to the channel detectable: bad magic or length ends the
6 //! host instead of desynchronising it.
7 //!
8 //! Host→core types use `deny_unknown_fields` — host output is untrusted
9 //! input. Core→host types are what this side writes.
10 //!
11 //! **This file is the protocol's single source.** [`METHODS`] is every method
12 //! either side may send; both parsers admit nothing else. The TypeScript
13 //! side's constants, method table, params shapes and wire types are generated
14 //! from the types here into `crates/engine/extension-host/src/protocol.generated.ts`
15 //! by `protocol/tests.rs`, which fails when the committed file drifts. What
16 //! stays hand-written in `protocol.ts`: the frame codec, the JSON-RPC envelope
17 //! checks, and the one rule [`parse_host_message`] applies beyond the types
18 //! (`host/hello`'s runtime name). Both sides also parse the shared corpus in
19 //! `tests/fixtures/extension_host/protocol`. Known limit: result shapes are
20 //! generated as TypeScript types only; the host does not validate the
21 //! results the core sends it, and the core validates what it reads.
22 //!
23 //! **Tiers.** Each [`MethodSpec`] carries the trust tiers (`HostTier`) that may
24 //! send or be sent it, and both parsers and the sender enforce that: a
25 //! plugin-tier host is never sent, and a plugin-tier host's frame is never
26 //! admitted for, a method reserved for the built-in tier. Every method allows
27 //! both tiers today ([`ALL_TIERS`]); a reserved method is a row written as
28 //! `MethodSpec { tiers: &[HostTier::Builtin], ..row(direction, name, request) }`.
29 //! `host/hello` carries the tier the host serves and the digests of the built-in
30 //! modules its bundle embeds, which the core checks against what it launched
31 //! (`supervisor::check_hello_identity`).
32 //!
33 //! There is deliberately no method that expresses approval. Registrations
34 //! are admitted or refused and tool calls flow core→host after the gate. The
35 //! builtin-only broker methods redeem single-use exact Rust-issued operation
36 //! tickets; they expose no launch command, credential or decision key. `command/run`
37 //! flows core→host only when the user invokes the command themselves; the
38 //! host answers with text or a prompt, and the core decides whether and how
39 //! to show or submit it. The authority lint in `protocol/tests.rs` keeps
40 //! [`METHODS`] that way.
41
42 use codewhale_config::{EntryRef, OwnerRef};
43 use std::time::Duration;
44
45 use serde::de::DeserializeOwned;
46 use serde::{Deserialize, Deserializer, Serialize};
47 use serde_json::{Map, Value, json};
48 use tokio::io::{AsyncRead, AsyncReadExt};
49
50 use super::tier::HostTier;
51
52 pub const PROTOCOL_VERSION: u32 = 1;
53 pub const MAGIC: [u8; 4] = *b"CWX1";
54 pub const HEADER_LEN: usize = 8;
55 /// Enough for base64 screenshots later; anything larger is refused, never truncated.
56 pub const MAX_FRAME: usize = 32 * 1024 * 1024;
57 /// Requests in flight per direction.
58 pub const MAX_INFLIGHT: usize = 256;
59
60 /// JSON-RPC error codes used on this channel.
61 pub mod error_code {
62 /// A method the receiver has no handler for (the core never sends one the
63 /// host's tier may not receive; see `MethodSpec::tiers`).
64 pub const METHOD_NOT_FOUND: i64 = -32601;
65 pub const INVALID_PARAMS: i64 = -32602;
66 /// Unknown, revoked, or not-yet-active handle.
67 pub const NOT_AVAILABLE: i64 = -32001;
68 /// Cancelled by `$/cancel`.
69 pub const CANCELLED: i64 = -32800;
70 /// `core/call`: the core's policy refuses the call (a tool the extension
71 /// may not reach, a limit, an invalid ticket), or the host's request is
72 /// refused for a reason that is not a person's answer.
73 pub const REFUSED: i64 = -32002;
74 /// `core/call`: the user declined the approval card for it.
75 pub const DENIED: i64 = -32003;
76
77 /// Every code on the channel, by the name the TypeScript side uses. The
78 /// core interprets only the three above; the host also answers with the
79 /// standard JSON-RPC codes and `ExecutionFailed` (a tool body threw),
80 /// which reach the caller as `HostCallError::Rpc`.
81 #[cfg(any(test, feature = "test-support"))]
82 pub const ALL: &[(&str, i64)] = &[
83 ("ParseError", -32700),
84 ("InvalidRequest", -32600),
85 ("MethodNotFound", METHOD_NOT_FOUND),
86 ("InvalidParams", INVALID_PARAMS),
87 ("Internal", -32603),
88 ("ExecutionFailed", -32000),
89 ("NotAvailable", NOT_AVAILABLE),
90 ("Refused", REFUSED),
91 ("Denied", DENIED),
92 ("Cancelled", CANCELLED),
93 ];
94 }
95
96 /// Which side sends a method.
97 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
98 pub enum Direction {
99 CoreToHost,
100 HostToCore,
101 }
102
103 impl Direction {
104 /// The corpus and TypeScript spelling.
105 #[must_use]
106 pub fn as_str(self) -> &'static str {
107 match self {
108 Self::CoreToHost => "core_to_host",
109 Self::HostToCore => "host_to_core",
110 }
111 }
112 }
113
114 /// One method either side may send.
115 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
116 pub struct MethodSpec {
117 pub name: &'static str,
118 pub direction: Direction,
119 /// A request carries an id and gets a response; a notification does not.
120 pub request: bool,
121 /// The trust tiers whose host may send (host to core) or be sent (core to
122 /// host) this method. Enforced in both directions: [`admit_in`] on what is
123 /// received, [`allowed_on`] before the core sends.
124 pub tiers: &'static [HostTier],
125 }
126
127 /// Both trust tiers: what a method allows unless it is reserved.
128 pub const ALL_TIERS: &[HostTier] = &HostTier::ALL;
129
130 /// A method open to both tiers. Reserve one for a tier with struct update:
131 /// `MethodSpec { tiers: &[HostTier::Builtin], ..row(..) }`.
132 const fn row(direction: Direction, name: &'static str, request: bool) -> MethodSpec {
133 MethodSpec {
134 name,
135 direction,
136 request,
137 tiers: ALL_TIERS,
138 }
139 }
140
141 /// The whole protocol surface. A method missing here is refused by both
142 /// parsers; a method added here must pass the authority lint.
143 pub const METHODS: &[MethodSpec] = &[
144 row(Direction::CoreToHost, "host/initialize", true),
145 row(Direction::CoreToHost, "host/ping", true),
146 row(Direction::CoreToHost, "host/shutdown", true),
147 row(Direction::CoreToHost, "ext/activate", true),
148 row(Direction::CoreToHost, "ext/deactivate", true),
149 row(Direction::CoreToHost, "tool/call", true),
150 row(Direction::CoreToHost, "command/run", true),
151 row(Direction::CoreToHost, "hook/evaluate", true),
152 row(Direction::CoreToHost, "plugin_route/dispatch", true),
153 MethodSpec {
154 tiers: &[HostTier::Builtin],
155 ..row(Direction::CoreToHost, "mcp/open", true)
156 },
157 MethodSpec {
158 tiers: &[HostTier::Builtin],
159 ..row(Direction::CoreToHost, "mcp/request", true)
160 },
161 MethodSpec {
162 tiers: &[HostTier::Builtin],
163 ..row(Direction::CoreToHost, "mcp/close", true)
164 },
165 MethodSpec {
166 tiers: &[HostTier::Builtin],
167 ..row(Direction::CoreToHost, "harness/run", true)
168 },
169 row(Direction::CoreToHost, "$/cancel", false),
170 row(Direction::HostToCore, "host/hello", false),
171 row(Direction::HostToCore, "host/ready", false),
172 row(Direction::HostToCore, "registry/register", true),
173 row(Direction::HostToCore, "registry/unregister", true),
174 row(Direction::HostToCore, "core/call", true),
175 row(Direction::HostToCore, "session/checkpoint", true),
176 row(Direction::HostToCore, "user-questions/ask", true),
177 row(Direction::HostToCore, "subagent/start", true),
178 row(Direction::HostToCore, "subagent/result", true),
179 row(Direction::HostToCore, "subagent/dispose", true),
180 row(Direction::HostToCore, "subagent/prompt", true),
181 row(Direction::HostToCore, "dsh/broker", true),
182 MethodSpec {
183 tiers: &[HostTier::Builtin],
184 ..row(Direction::HostToCore, "proc/launch", true)
185 },
186 MethodSpec {
187 tiers: &[HostTier::Builtin],
188 ..row(Direction::HostToCore, "proc/read", true)
189 },
190 MethodSpec {
191 tiers: &[HostTier::Builtin],
192 ..row(Direction::HostToCore, "proc/write", true)
193 },
194 MethodSpec {
195 tiers: &[HostTier::Builtin],
196 ..row(Direction::HostToCore, "proc/close", true)
197 },
198 MethodSpec {
199 tiers: &[HostTier::Builtin],
200 ..row(Direction::HostToCore, "net/start", true)
201 },
202 MethodSpec {
203 tiers: &[HostTier::Builtin],
204 ..row(Direction::HostToCore, "net/fetch", true)
205 },
206 MethodSpec {
207 tiers: &[HostTier::Builtin],
208 ..row(Direction::HostToCore, "net/read", true)
209 },
210 MethodSpec {
211 tiers: &[HostTier::Builtin],
212 ..row(Direction::HostToCore, "net/release", true)
213 },
214 MethodSpec {
215 tiers: &[HostTier::Builtin],
216 ..row(Direction::HostToCore, "net/close", true)
217 },
218 MethodSpec {
219 tiers: &[HostTier::Builtin],
220 ..row(Direction::HostToCore, "exec/redeem", true)
221 },
222 row(Direction::HostToCore, "ext/faulted", false),
223 row(Direction::HostToCore, "log", false),
224 row(Direction::HostToCore, "$/cancel", false),
225 ];
226
227 /// Admit `method` travelling in `direction` from [`METHODS`]: anything not
228 /// in the table is refused, a request must carry an id and a notification
229 /// must not. Returns the id.
230 fn admit(
231 direction: Direction,
232 method: &str,
233 id: Option<u64>,
234 tier: HostTier,
235 ) -> Result<Option<u64>, ProtocolError> {
236 admit_in(METHODS, direction, method, id, tier)
237 }
238
239 /// [`admit`] over `table`, so the tier rule is testable with a reserved row
240 /// that production does not have.
241 fn admit_in(
242 table: &[MethodSpec],
243 direction: Direction,
244 method: &str,
245 id: Option<u64>,
246 tier: HostTier,
247 ) -> Result<Option<u64>, ProtocolError> {
248 let spec = table
249 .iter()
250 .find(|spec| spec.direction == direction && spec.name == method)
251 .ok_or_else(|| perr(format!("unknown {} method `{method}`", direction.as_str())))?;
252 if !spec.tiers.contains(&tier) {
253 return Err(perr(format!(
254 "`{method}` is not allowed on the {} tier",
255 tier.name()
256 )));
257 }
258 match (spec.request, id) {
259 (true, Some(_)) | (false, None) => Ok(id),
260 (true, None) => Err(perr(format!("`{method}` must be a request (with id)"))),
261 (false, Some(_)) => Err(perr(format!("`{method}` must be a notification (no id)"))),
262 }
263 }
264
265 /// Whether a host of `tier` may be sent (core to host) or send (host to core)
266 /// `method`. A method not in [`METHODS`] is not allowed.
267 #[must_use]
268 pub fn allowed_on(direction: Direction, method: &str, tier: HostTier) -> bool {
269 allowed_in(METHODS, direction, method, tier)
270 }
271
272 fn allowed_in(table: &[MethodSpec], direction: Direction, method: &str, tier: HostTier) -> bool {
273 table.iter().any(|spec| {
274 spec.direction == direction && spec.name == method && spec.tiers.contains(&tier)
275 })
276 }
277
278 fn undecoded(method: &str) -> ProtocolError {
279 perr(format!(
280 "`{method}` is in the method table but has no decoder"
281 ))
282 }
283
284 #[derive(Debug, thiserror::Error)]
285 pub enum FrameError {
286 #[error("bad frame magic")]
287 BadMagic,
288 #[error("frame of {0} bytes exceeds MAX_FRAME")]
289 TooLarge(usize),
290 #[error("frame payload is not JSON: {0}")]
291 Json(#[from] serde_json::Error),
292 #[error("channel read failed: {0}")]
293 Io(#[from] std::io::Error),
294 }
295
296 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
297 #[error("{0}")]
298 pub struct ProtocolError(pub String);
299
300 fn perr(message: impl Into<String>) -> ProtocolError {
301 ProtocolError(message.into())
302 }
303
304 /// Encode one message into a `CWX1` frame.
305 pub fn encode_frame(message: &Value) -> Result<Vec<u8>, FrameError> {
306 let payload = serde_json::to_vec(message)?;
307 if payload.len() > MAX_FRAME {
308 return Err(FrameError::TooLarge(payload.len()));
309 }
310 let mut frame = Vec::with_capacity(HEADER_LEN + payload.len());
311 frame.extend_from_slice(&MAGIC);
312 frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
313 frame.extend_from_slice(&payload);
314 Ok(frame)
315 }
316
317 /// Read one frame. `Ok(None)` is a clean EOF at a frame boundary. The payload
318 /// buffer is allocated only after the length is checked against `MAX_FRAME`.
319 pub async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> Result<Option<Value>, FrameError> {
320 let mut header = [0u8; HEADER_LEN];
321 let mut filled = 0;
322 while filled < HEADER_LEN {
323 let read = reader.read(&mut header[filled..]).await?;
324 if read == 0 {
325 if filled == 0 {
326 return Ok(None);
327 }
328 return Err(FrameError::Io(std::io::ErrorKind::UnexpectedEof.into()));
329 }
330 filled += read;
331 }
332 if header[..4] != MAGIC {
333 return Err(FrameError::BadMagic);
334 }
335 let length = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize;
336 if length > MAX_FRAME {
337 return Err(FrameError::TooLarge(length));
338 }
339 let mut payload = vec![0u8; length];
340 reader.read_exact(&mut payload).await?;
341 Ok(Some(serde_json::from_slice(&payload)?))
342 }
343
344 /// `Some(value)` even for an explicit JSON `null`, so `"result": null` is a
345 /// present result and round-trips.
346 fn present_entry<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<EntryRef>, D::Error> {
347 EntryRef::deserialize(deserializer).map(Some)
348 }
349 fn present<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Value>, D::Error> {
350 Value::deserialize(deserializer).map(Some)
351 }
352
353 // ---------------------------------------------------------------------------
354 // Shared types
355 // ---------------------------------------------------------------------------
356
357 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
358 #[cfg_attr(test, derive(schemars::JsonSchema))]
359 #[serde(deny_unknown_fields)]
360 pub struct RpcErrorWire {
361 pub code: i64,
362 pub message: String,
363 #[serde(
364 default,
365 skip_serializing_if = "Option::is_none",
366 deserialize_with = "present"
367 )]
368 pub data: Option<Value>,
369 }
370
371 // ---------------------------------------------------------------------------
372 // Host → core (strict)
373 // ---------------------------------------------------------------------------
374
375 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376 #[cfg_attr(test, derive(schemars::JsonSchema))]
377 #[serde(deny_unknown_fields)]
378 pub struct ProtocolRange {
379 pub min: u32,
380 pub max: u32,
381 }
382
383 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384 #[cfg_attr(test, derive(schemars::JsonSchema))]
385 #[serde(deny_unknown_fields)]
386 pub struct HelloParams {
387 pub protocol: ProtocolRange,
388 pub host_version: String,
389 pub bundle_sha256: String,
390 /// The runtime actually running the host. Under Bun this comes from
391 /// `process.versions.bun`, not the Node version Bun emulates.
392 pub runtime: HelloRuntime,
393 /// The trust tier this host process serves (`--tier=`). The core refuses a
394 /// host that reports any tier but the one it launched.
395 pub tier: HostTier,
396 /// The SHA-256 of every built-in module source this host build embeds
397 /// (`dist/builtin-modules.json`), one row per module, in id order. The
398 /// core refuses a host whose list is not the one its own table pins.
399 pub builtin_modules: Vec<ModuleDigestWire>,
400 /// A kernel memory limit the host applied to itself before loading any
401 /// plugin, in MiB: macOS + Bun, when the core asked for one
402 /// (`supervisor::MemoryEnforcement::Jetsam`). Absent otherwise.
403 #[serde(default, skip_serializing_if = "Option::is_none")]
404 pub memory_limit_mib: Option<u64>,
405 }
406
407 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
408 #[cfg_attr(test, derive(schemars::JsonSchema))]
409 #[serde(deny_unknown_fields)]
410 pub struct HelloRuntime {
411 /// `bun` or `node`.
412 pub name: String,
413 pub version: String,
414 }
415
416 /// One built-in module's pinned source digest, as the host build records it.
417 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
418 #[cfg_attr(test, derive(schemars::JsonSchema))]
419 #[serde(deny_unknown_fields)]
420 pub struct ModuleDigestWire {
421 pub id: String,
422 pub sha256: String,
423 }
424
425 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
426 #[cfg_attr(test, derive(schemars::JsonSchema))]
427 #[serde(deny_unknown_fields)]
428 pub struct EmptyParams {}
429
430 /// What a registration is: a `tool` the model calls (`tool/call`), or a slash
431 /// `command` the user runs (`/name args`, `command/run`). No variant docs:
432 /// schemars would then render the enum as a mix the generator does not read.
433 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
434 #[cfg_attr(test, derive(schemars::JsonSchema))]
435 #[serde(rename_all = "snake_case")]
436 pub enum RegisterKind {
437 Tool,
438 Command,
439 Hook,
440 PromptSection,
441 PromptTemplate,
442 SkillRoot,
443 AvatarPack,
444 ShellHook,
445 McpServer,
446 }
447
448 /// What a registration proposes. The fields a kind uses are fixed by
449 /// [`RegisterParams::check_spec`] (the generated shapes cannot express a
450 /// per-kind union): a tool has an `input_schema` and no `argument_hint`; a
451 /// command has no `input_schema` and may have an `argument_hint`.
452 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
453 #[cfg_attr(test, derive(schemars::JsonSchema))]
454 #[serde(deny_unknown_fields)]
455 pub struct RegisterSpecWire {
456 pub name: String,
457 pub description: String,
458 /// Tools only: the JSON object schema of the call's input.
459 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub input_schema: Option<Map<String, Value>>,
461 /// Commands only: the argument placeholder shown after the name (for
462 /// example `<topic>`). A command with a hint waits in the composer for
463 /// arguments; one without runs directly from the palette.
464 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub argument_hint: Option<String>,
466 }
467
468 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
469 #[cfg_attr(test, derive(schemars::JsonSchema))]
470 #[serde(deny_unknown_fields)]
471 pub struct RegisterParams {
472 pub owner: OwnerRef,
473 #[serde(
474 default,
475 skip_serializing_if = "Option::is_none",
476 deserialize_with = "present_entry"
477 )]
478 pub scope: Option<EntryRef>,
479 pub kind: RegisterKind,
480 pub spec: RegisterSpecWire,
481 }
482
483 impl RegisterParams {
484 /// The rule [`RegisterSpecWire`]'s docs state: which spec fields each
485 /// kind uses. Applied by [`parse_host_message`] and mirrored in the
486 /// host's `validateMessage`; the corpus holds both to it.
487 pub fn check_spec(&self) -> Result<(), String> {
488 let spec = &self.spec;
489 match self.kind {
490 RegisterKind::Tool if spec.input_schema.is_none() => {
491 Err("a tool registration needs `spec.input_schema`".to_string())
492 }
493 RegisterKind::Tool if spec.argument_hint.is_some() => {
494 Err("a tool registration has no `spec.argument_hint`".to_string())
495 }
496 RegisterKind::Command if spec.input_schema.is_some() => {
497 Err("a command registration has no `spec.input_schema`".to_string())
498 }
499 RegisterKind::Hook | RegisterKind::PromptSection | RegisterKind::PromptTemplate | RegisterKind::SkillRoot | RegisterKind::AvatarPack | RegisterKind::ShellHook | RegisterKind::McpServer
500 if spec.input_schema.is_some() || spec.argument_hint.is_some() =>
501 {
502 Err(
503 "a hook, prompt or skill root registration has no input schema or argument hint"
504 .to_string(),
505 )
506 }
507 _ => Ok(()),
508 }
509 }
510 }
511
512 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
513 #[cfg_attr(test, derive(schemars::JsonSchema))]
514 #[serde(deny_unknown_fields)]
515 pub struct UnregisterParams {
516 pub owner: OwnerRef,
517 pub handle: u64,
518 }
519
520 /// A tool asking the core to run one of the core's tools for it
521 /// (`core/call`, answered with a [`ToolResultWire`]). The `ticket` is the
522 /// invocation ticket the core put in this call's `tool/call`; the core checks
523 /// it against its own row (owner, tier, host generation, method, limits) and
524 /// the host never decides anything: policy, approval and the approval card's
525 /// text are the core's.
526 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
527 #[cfg_attr(test, derive(schemars::JsonSchema))]
528 #[serde(deny_unknown_fields)]
529 pub struct CoreCallParams {
530 pub owner: OwnerRef,
531 pub ticket: String,
532 pub name: String,
533 pub input: Value,
534 }
535
536 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
537 pub enum DshService {
538 Workspace,
539 Llm,
540 Network,
541 Settings,
542 Catalog,
543 Terminal,
544 Remote,
545 Attachments,
546 Plugins,
547 }
548
549 impl DshService {
550 pub const ALL: [Self; 8] = [
551 Self::Workspace,
552 Self::Llm,
553 Self::Network,
554 Self::Settings,
555 Self::Catalog,
556 Self::Terminal,
557 Self::Remote,
558 Self::Attachments,
559 ];
560
561 pub const BUILTIN_ONLY: [Self; 1] = [Self::Plugins];
562
563 pub const EVERY: [Self; 9] = [
564 Self::Workspace,
565 Self::Llm,
566 Self::Network,
567 Self::Settings,
568 Self::Catalog,
569 Self::Terminal,
570 Self::Remote,
571 Self::Attachments,
572 Self::Plugins,
573 ];
574
575 #[must_use]
576 pub fn name(self) -> &'static str {
577 match self {
578 Self::Workspace => "workspace",
579 Self::Llm => "llm",
580 Self::Network => "network",
581 Self::Settings => "settings",
582 Self::Catalog => "catalog",
583 Self::Terminal => "terminal",
584 Self::Remote => "remote",
585 Self::Attachments => "attachments",
586 Self::Plugins => "plugins",
587 }
588 }
589
590 #[must_use]
591 pub fn parse(name: &str) -> Option<Self> {
592 Self::EVERY
593 .into_iter()
594 .find(|service| service.name() == name)
595 }
596
597 #[must_use]
598 pub fn builtin_only(self) -> bool {
599 Self::BUILTIN_ONLY.contains(&self)
600 }
601 }
602
603 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
604 #[cfg_attr(test, derive(schemars::JsonSchema))]
605 #[serde(deny_unknown_fields)]
606 pub struct DshBrokerParams {
607 pub owner: OwnerRef,
608 pub ticket: String,
609 pub service: String,
610 pub method: String,
611 pub input: Value,
612 }
613
614 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
615 #[cfg_attr(test, derive(schemars::JsonSchema))]
616 #[serde(deny_unknown_fields)]
617 pub struct DshBrokerTicketWire {
618 pub service: String,
619 pub ticket: String,
620 }
621
622 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
623 #[cfg_attr(test, derive(schemars::JsonSchema))]
624 #[serde(deny_unknown_fields)]
625 pub struct SessionCheckpointParams {
626 pub owner: OwnerRef,
627 pub ticket: String,
628 }
629
630 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
631 #[cfg_attr(test, derive(schemars::JsonSchema))]
632 #[serde(deny_unknown_fields)]
633 pub struct UserQuestionParams {
634 pub owner: OwnerRef,
635 pub ticket: String,
636 pub questions: Vec<crate::tools::user_input::UserInputQuestion>,
637 }
638
639 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
640 #[cfg_attr(test, derive(schemars::JsonSchema))]
641 #[serde(deny_unknown_fields)]
642 pub struct SubagentStartParams {
643 pub owner: OwnerRef,
644 pub ticket: String,
645 pub child_id: String,
646 pub prompt: String,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
648 pub model: Option<String>,
649 #[serde(default, skip_serializing_if = "Option::is_none")]
650 pub persona: Option<String>,
651 #[serde(default)]
652 pub denied_tools: Vec<String>,
653 pub delivery: String,
654 }
655
656 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
657 #[cfg_attr(test, derive(schemars::JsonSchema))]
658 #[serde(deny_unknown_fields)]
659 pub struct SubagentHandleParams {
660 pub owner: OwnerRef,
661 pub ticket: String,
662 pub child_id: String,
663 }
664
665 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
666 #[cfg_attr(test, derive(schemars::JsonSchema))]
667 #[serde(deny_unknown_fields)]
668 pub struct SubagentPromptParams {
669 pub owner: OwnerRef,
670 pub ticket: String,
671 pub child_id: String,
672 pub prompt: String,
673 pub mode: String,
674 }
675
676 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
677 #[cfg_attr(test, derive(schemars::JsonSchema))]
678 #[serde(deny_unknown_fields)]
679 pub struct FaultedParams {
680 pub owner: OwnerRef,
681 pub error: String,
682 }
683
684 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
685 #[cfg_attr(test, derive(schemars::JsonSchema))]
686 #[serde(deny_unknown_fields)]
687 pub struct LogParams {
688 pub level: String,
689 pub msg: String,
690 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub plugin_id: Option<String>,
692 }
693
694 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
695 #[cfg_attr(test, derive(schemars::JsonSchema))]
696 #[serde(deny_unknown_fields)]
697 pub struct CancelParams {
698 pub id: u64,
699 }
700
701 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
702 #[cfg_attr(test, derive(schemars::JsonSchema))]
703 #[serde(deny_unknown_fields)]
704 pub struct HookDispatchWire {
705 pub event: String,
706 pub dialect: String,
707 pub point: String,
708 #[serde(default, skip_serializing_if = "Option::is_none")]
709 pub matcher: Option<String>,
710 pub query: String,
711 }
712
713 // Opaque execution references only. Rust never sends commands, inputs, environment or credentials.
714 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
715 #[cfg_attr(test, derive(schemars::JsonSchema))]
716 #[serde(deny_unknown_fields)]
717 pub struct HarnessRunParams {
718 pub owner: OwnerRef,
719 pub execution_id: String,
720 pub ticket: String,
721 pub deadline_ms: u64,
722 #[serde(default, skip_serializing_if = "Option::is_none")]
723 pub hook: Option<HookDispatchWire>,
724 }
725 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
726 #[cfg_attr(test, derive(schemars::JsonSchema))]
727 #[serde(deny_unknown_fields)]
728 pub struct ExecutionRedeemParams {
729 pub owner: OwnerRef,
730 pub execution_id: String,
731 pub ticket: String,
732 }
733
734 // Tier-0 MCP semantic operations and broker pipe access. Launch details and
735 // Computer Use keys are Rust-only; every write is an exact single-use grant.
736 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
737 #[cfg_attr(test, derive(schemars::JsonSchema))]
738 #[serde(deny_unknown_fields)]
739 pub struct McpOperationGrant {
740 pub ticket: String,
741 pub operation_id: String,
742 pub method: String,
743 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub wire_id: Option<String>,
745 pub params: Value,
746 }
747
748 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
749 #[cfg_attr(test, derive(schemars::JsonSchema))]
750 #[serde(deny_unknown_fields)]
751 pub struct McpOpenParams {
752 pub owner: OwnerRef,
753 pub session_id: String,
754 pub launch_ticket: String,
755 pub transport: String,
756 #[serde(default, skip_serializing_if = "Option::is_none")]
757 pub discover_grant: Option<McpOperationGrant>,
758 pub initialize_grant: McpOperationGrant,
759 pub initialized_grant: McpOperationGrant,
760 pub client_version: String,
761 pub deadline_ms: u64,
762 }
763
764 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
765 #[cfg_attr(test, derive(schemars::JsonSchema))]
766 #[serde(deny_unknown_fields)]
767 pub struct McpRequestParams {
768 pub owner: OwnerRef,
769 pub session_id: String,
770 pub grant: McpOperationGrant,
771 pub deadline_ms: u64,
772 }
773
774 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
775 #[cfg_attr(test, derive(schemars::JsonSchema))]
776 #[serde(deny_unknown_fields)]
777 pub struct McpCloseParams {
778 pub owner: OwnerRef,
779 pub session_id: String,
780 pub deadline_ms: u64,
781 }
782
783 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
784 #[cfg_attr(test, derive(schemars::JsonSchema))]
785 #[serde(deny_unknown_fields)]
786 pub struct ProcLaunchParams {
787 pub owner: OwnerRef,
788 pub session_id: String,
789 pub ticket: String,
790 }
791
792 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
793 #[cfg_attr(test, derive(schemars::JsonSchema))]
794 #[serde(deny_unknown_fields)]
795 pub struct ProcSessionParams {
796 pub owner: OwnerRef,
797 pub session_id: String,
798 }
799
800 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
801 #[cfg_attr(test, derive(schemars::JsonSchema))]
802 #[serde(deny_unknown_fields)]
803 pub struct ProcWriteParams {
804 pub owner: OwnerRef,
805 pub session_id: String,
806 pub frame: Value,
807 #[serde(default, skip_serializing_if = "Option::is_none")]
808 pub ticket: Option<String>,
809 #[serde(default, skip_serializing_if = "Option::is_none")]
810 pub operation_id: Option<String>,
811 }
812
813 /// The SDK can propose framing headers only. Rust adds credentials itself.
814 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
815 #[cfg_attr(test, derive(schemars::JsonSchema))]
816 #[serde(deny_unknown_fields)]
817 pub struct McpHttpHeaders {
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 pub accept: Option<String>,
820 #[serde(default, skip_serializing_if = "Option::is_none")]
821 pub content_type: Option<String>,
822 #[serde(default, skip_serializing_if = "Option::is_none")]
823 pub mcp_session_id: Option<String>,
824 #[serde(default, skip_serializing_if = "Option::is_none")]
825 pub mcp_protocol_version: Option<String>,
826 #[serde(default, skip_serializing_if = "Option::is_none")]
827 pub mcp_method: Option<String>,
828 #[serde(default, skip_serializing_if = "Option::is_none")]
829 pub mcp_name: Option<String>,
830 }
831
832 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
833 #[cfg_attr(test, derive(schemars::JsonSchema))]
834 #[serde(deny_unknown_fields)]
835 pub struct NetFetchParams {
836 pub owner: OwnerRef,
837 pub session_id: String,
838 pub url: String,
839 pub method: String,
840 pub headers: McpHttpHeaders,
841 #[serde(default, skip_serializing_if = "Option::is_none")]
842 pub frame: Option<Value>,
843 #[serde(default, skip_serializing_if = "Option::is_none")]
844 pub ticket: Option<String>,
845 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub operation_id: Option<String>,
847 }
848 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
849 #[cfg_attr(test, derive(schemars::JsonSchema))]
850 #[serde(deny_unknown_fields)]
851 pub struct NetReadParams {
852 pub owner: OwnerRef,
853 pub session_id: String,
854 pub response_id: String,
855 }
856
857 #[derive(Debug, Clone, PartialEq)]
858 pub enum HostRequest {
859 Register(RegisterParams),
860 Unregister(UnregisterParams),
861 CoreCall(CoreCallParams),
862 SessionCheckpoint(SessionCheckpointParams),
863 UserQuestion(UserQuestionParams),
864 SubagentStart(SubagentStartParams),
865 SubagentResult(SubagentHandleParams),
866 SubagentDispose(SubagentHandleParams),
867 SubagentPrompt(SubagentPromptParams),
868 DshBroker(DshBrokerParams),
869 ExecutionRedeem(ExecutionRedeemParams),
870 ProcClose(ProcSessionParams),
871 NetStart(ProcLaunchParams),
872 NetFetch(NetFetchParams),
873 NetRead(NetReadParams),
874 NetRelease(NetReadParams),
875 NetClose(ProcSessionParams),
876 ProcWrite(ProcWriteParams),
877 ProcRead(ProcSessionParams),
878 ProcLaunch(ProcLaunchParams),
879 }
880
881 impl HostRequest {
882 /// The plugin whose revocation cancels this request in flight.
883 #[must_use]
884 pub fn plugin_id(&self) -> &str {
885 match self {
886 Self::Register(params) => &params.owner.plugin_id,
887 Self::Unregister(params) => &params.owner.plugin_id,
888 Self::CoreCall(params) => &params.owner.plugin_id,
889 Self::SessionCheckpoint(params) => &params.owner.plugin_id,
890 Self::UserQuestion(params) => &params.owner.plugin_id,
891 Self::SubagentStart(params) => &params.owner.plugin_id,
892 Self::SubagentResult(params) | Self::SubagentDispose(params) => &params.owner.plugin_id,
893 Self::SubagentPrompt(params) => &params.owner.plugin_id,
894 Self::DshBroker(params) => &params.owner.plugin_id,
895 Self::ExecutionRedeem(params) => &params.owner.plugin_id,
896 Self::ProcClose(params) => &params.owner.plugin_id,
897 Self::NetClose(params) => &params.owner.plugin_id,
898 Self::NetRelease(params) => &params.owner.plugin_id,
899 Self::NetRead(params) => &params.owner.plugin_id,
900 Self::NetFetch(params) => &params.owner.plugin_id,
901 Self::NetStart(params) => &params.owner.plugin_id,
902 Self::ProcWrite(params) => &params.owner.plugin_id,
903 Self::ProcRead(params) => &params.owner.plugin_id,
904 Self::ProcLaunch(params) => &params.owner.plugin_id,
905 }
906 }
907 }
908
909 #[derive(Debug, Clone, PartialEq)]
910 pub enum HostNotification {
911 Hello(HelloParams),
912 Ready,
913 Faulted(FaultedParams),
914 Log(LogParams),
915 Cancel(CancelParams),
916 }
917
918 /// One decoded, validated host→core message.
919 #[derive(Debug, Clone, PartialEq)]
920 pub enum HostMessage {
921 Request {
922 id: u64,
923 request: Box<HostRequest>,
924 },
925 Notification(HostNotification),
926 Response {
927 id: u64,
928 outcome: Result<Value, RpcErrorWire>,
929 },
930 }
931
932 #[derive(Deserialize)]
933 #[serde(deny_unknown_fields)]
934 struct Envelope {
935 jsonrpc: String,
936 #[serde(default)]
937 id: Option<u64>,
938 #[serde(default)]
939 method: Option<String>,
940 #[serde(default, deserialize_with = "present")]
941 params: Option<Value>,
942 #[serde(default, deserialize_with = "present")]
943 result: Option<Value>,
944 #[serde(default)]
945 error: Option<RpcErrorWire>,
946 }
947
948 fn decode_envelope(value: Value) -> Result<Envelope, ProtocolError> {
949 let envelope: Envelope =
950 serde_json::from_value(value).map_err(|e| perr(format!("envelope: {e}")))?;
951 if envelope.jsonrpc != "2.0" {
952 return Err(perr("envelope: jsonrpc must be \"2.0\""));
953 }
954 Ok(envelope)
955 }
956
957 /// Params are always named: an array would otherwise decode positionally
958 /// into a struct (`[]` into [`EmptyParams`]), which the TypeScript side
959 /// rejects.
960 fn params<T: DeserializeOwned>(method: &str, params: Option<Value>) -> Result<T, ProtocolError> {
961 let params = params.unwrap_or_else(|| json!({}));
962 if !params.is_object() {
963 return Err(perr(format!("{method}: params must be an object")));
964 }
965 serde_json::from_value(params).map_err(|e| perr(format!("{method}: {e}")))
966 }
967
968 fn decode_response(
969 envelope: Envelope,
970 ) -> Result<(u64, Result<Value, RpcErrorWire>), ProtocolError> {
971 let id = envelope.id.ok_or_else(|| perr("response: missing id"))?;
972 if envelope.params.is_some() {
973 return Err(perr("response: unexpected params"));
974 }
975 match (envelope.result, envelope.error) {
976 (Some(result), None) => Ok((id, Ok(result))),
977 (None, Some(error)) => Ok((id, Err(error))),
978 _ => Err(perr("response: needs exactly one of result or error")),
979 }
980 }
981
982 /// Parse and strictly validate one host→core message from a host of `tier`: a
983 /// method reserved for another tier is refused like an unknown one.
984 pub fn parse_host_message(value: Value, tier: HostTier) -> Result<HostMessage, ProtocolError> {
985 let envelope = decode_envelope(value)?;
986 let Some(method) = envelope.method.clone() else {
987 let (id, outcome) = decode_response(envelope)?;
988 return Ok(HostMessage::Response { id, outcome });
989 };
990 if envelope.result.is_some() || envelope.error.is_some() {
991 return Err(perr(format!(
992 "`{method}`: a request carries no result or error"
993 )));
994 }
995 let id = admit(Direction::HostToCore, &method, envelope.id, tier)?;
996 let p = envelope.params;
997 let message = match (method.as_str(), id) {
998 ("registry/register", Some(id)) => {
999 let register: RegisterParams = params(&method, p)?;
1000 register
1001 .check_spec()
1002 .map_err(|reason| perr(format!("{method}: {reason}")))?;
1003 HostMessage::Request {
1004 id,
1005 request: Box::new(HostRequest::Register(register)),
1006 }
1007 }
1008 ("registry/unregister", Some(id)) => HostMessage::Request {
1009 id,
1010 request: Box::new(HostRequest::Unregister(params(&method, p)?)),
1011 },
1012 ("user-questions/ask", Some(id)) => HostMessage::Request {
1013 id,
1014 request: Box::new(HostRequest::UserQuestion(params(&method, p)?)),
1015 },
1016 ("subagent/start", Some(id)) => HostMessage::Request {
1017 id,
1018 request: Box::new(HostRequest::SubagentStart(params(&method, p)?)),
1019 },
1020 ("subagent/result", Some(id)) => HostMessage::Request {
1021 id,
1022 request: Box::new(HostRequest::SubagentResult(params(&method, p)?)),
1023 },
1024 ("subagent/dispose", Some(id)) => HostMessage::Request {
1025 id,
1026 request: Box::new(HostRequest::SubagentDispose(params(&method, p)?)),
1027 },
1028 ("subagent/prompt", Some(id)) => HostMessage::Request {
1029 id,
1030 request: Box::new(HostRequest::SubagentPrompt(params(&method, p)?)),
1031 },
1032 ("dsh/broker", Some(id)) => HostMessage::Request {
1033 id,
1034 request: Box::new(HostRequest::DshBroker(params(&method, p)?)),
1035 },
1036 ("session/checkpoint", Some(id)) => HostMessage::Request {
1037 id,
1038 request: Box::new(HostRequest::SessionCheckpoint(params(&method, p)?)),
1039 },
1040 ("core/call", Some(id)) => HostMessage::Request {
1041 id,
1042 request: Box::new(HostRequest::CoreCall(params(&method, p)?)),
1043 },
1044 ("net/start", Some(id)) => HostMessage::Request {
1045 id,
1046 request: Box::new(HostRequest::NetStart(params(&method, p)?)),
1047 },
1048 ("net/fetch", Some(id)) => HostMessage::Request {
1049 id,
1050 request: Box::new(HostRequest::NetFetch(params(&method, p)?)),
1051 },
1052 ("net/read", Some(id)) => HostMessage::Request {
1053 id,
1054 request: Box::new(HostRequest::NetRead(params(&method, p)?)),
1055 },
1056 ("net/release", Some(id)) => HostMessage::Request {
1057 id,
1058 request: Box::new(HostRequest::NetRelease(params(&method, p)?)),
1059 },
1060 ("net/close", Some(id)) => HostMessage::Request {
1061 id,
1062 request: Box::new(HostRequest::NetClose(params(&method, p)?)),
1063 },
1064 ("proc/close", Some(id)) => HostMessage::Request {
1065 id,
1066 request: Box::new(HostRequest::ProcClose(params(&method, p)?)),
1067 },
1068 ("proc/write", Some(id)) => HostMessage::Request {
1069 id,
1070 request: Box::new(HostRequest::ProcWrite(params(&method, p)?)),
1071 },
1072 ("proc/read", Some(id)) => HostMessage::Request {
1073 id,
1074 request: Box::new(HostRequest::ProcRead(params(&method, p)?)),
1075 },
1076 ("exec/redeem", Some(id)) => HostMessage::Request {
1077 id,
1078 request: Box::new(HostRequest::ExecutionRedeem(params(&method, p)?)),
1079 },
1080 ("proc/launch", Some(id)) => HostMessage::Request {
1081 id,
1082 request: Box::new(HostRequest::ProcLaunch(params(&method, p)?)),
1083 },
1084 ("host/hello", None) => {
1085 let hello: HelloParams = params(&method, p)?;
1086 if !matches!(hello.runtime.name.as_str(), "bun" | "node") {
1087 return Err(perr(format!(
1088 "host/hello.runtime.name: unknown runtime `{}`",
1089 hello.runtime.name
1090 )));
1091 }
1092 HostMessage::Notification(HostNotification::Hello(hello))
1093 }
1094 ("host/ready", None) => {
1095 let _: EmptyParams = params(&method, p)?;
1096 HostMessage::Notification(HostNotification::Ready)
1097 }
1098 ("ext/faulted", None) => {
1099 HostMessage::Notification(HostNotification::Faulted(params(&method, p)?))
1100 }
1101 ("log", None) => HostMessage::Notification(HostNotification::Log(params(&method, p)?)),
1102 ("$/cancel", None) => {
1103 HostMessage::Notification(HostNotification::Cancel(params(&method, p)?))
1104 }
1105 _ => return Err(undecoded(&method)),
1106 };
1107 Ok(message)
1108 }
1109
1110 fn request_value(id: u64, method: &str, params: Value) -> Value {
1111 json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
1112 }
1113
1114 fn notification_value(method: &str, params: Value) -> Value {
1115 json!({"jsonrpc": "2.0", "method": method, "params": params})
1116 }
1117
1118 pub fn response_value(id: u64, outcome: &Result<Value, RpcErrorWire>) -> Value {
1119 match outcome {
1120 Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
1121 Err(error) => json!({"jsonrpc": "2.0", "id": id, "error": error}),
1122 }
1123 }
1124
1125 fn to_value<T: Serialize>(value: &T) -> Value {
1126 serde_json::to_value(value).expect("protocol types serialize")
1127 }
1128
1129 #[cfg(any(test, feature = "test-support"))]
1130 impl HostMessage {
1131 /// Re-encode (used by the conformance corpus round-trip).
1132 #[must_use]
1133 pub fn to_value(&self) -> Value {
1134 match self {
1135 Self::Request { id, request } => match request.as_ref() {
1136 HostRequest::Register(p) => request_value(*id, "registry/register", to_value(p)),
1137 HostRequest::Unregister(p) => {
1138 request_value(*id, "registry/unregister", to_value(p))
1139 }
1140 HostRequest::ExecutionRedeem(p) => request_value(*id, "exec/redeem", to_value(p)),
1141 HostRequest::CoreCall(p) => request_value(*id, "core/call", to_value(p)),
1142 HostRequest::UserQuestion(p) => {
1143 request_value(*id, "user-questions/ask", to_value(p))
1144 }
1145 HostRequest::SubagentStart(p) => request_value(*id, "subagent/start", to_value(p)),
1146 HostRequest::SubagentResult(p) => {
1147 request_value(*id, "subagent/result", to_value(p))
1148 }
1149 HostRequest::SubagentDispose(p) => {
1150 request_value(*id, "subagent/dispose", to_value(p))
1151 }
1152 HostRequest::SubagentPrompt(p) => {
1153 request_value(*id, "subagent/prompt", to_value(p))
1154 }
1155 HostRequest::SessionCheckpoint(p) => {
1156 request_value(*id, "session/checkpoint", to_value(p))
1157 }
1158 HostRequest::DshBroker(p) => request_value(*id, "dsh/broker", to_value(p)),
1159 HostRequest::ProcClose(p) => request_value(*id, "proc/close", to_value(p)),
1160 HostRequest::NetStart(p) => request_value(*id, "net/start", to_value(p)),
1161 HostRequest::NetFetch(p) => request_value(*id, "net/fetch", to_value(p)),
1162 HostRequest::NetRead(p) => request_value(*id, "net/read", to_value(p)),
1163 HostRequest::NetRelease(p) => request_value(*id, "net/release", to_value(p)),
1164 HostRequest::NetClose(p) => request_value(*id, "net/close", to_value(p)),
1165
1166 HostRequest::ProcWrite(p) => request_value(*id, "proc/write", to_value(p)),
1167 HostRequest::ProcRead(p) => request_value(*id, "proc/read", to_value(p)),
1168 HostRequest::ProcLaunch(p) => request_value(*id, "proc/launch", to_value(p)),
1169 },
1170 Self::Notification(notification) => match notification {
1171 HostNotification::Hello(p) => notification_value("host/hello", to_value(p)),
1172 HostNotification::Ready => notification_value("host/ready", json!({})),
1173 HostNotification::Faulted(p) => notification_value("ext/faulted", to_value(p)),
1174 HostNotification::Log(p) => notification_value("log", to_value(p)),
1175 HostNotification::Cancel(p) => notification_value("$/cancel", to_value(p)),
1176 },
1177 Self::Response { id, outcome } => response_value(*id, outcome),
1178 }
1179 }
1180 }
1181
1182 // ---------------------------------------------------------------------------
1183 // Core → host (written by this side)
1184 // ---------------------------------------------------------------------------
1185
1186 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1187 #[cfg_attr(test, derive(schemars::JsonSchema))]
1188 pub struct HostLimits {
1189 pub max_frame: u64,
1190 pub max_inflight: u64,
1191 pub dispose_deadline_ms: u64,
1192 pub activate_deadline_ms: u64,
1193 }
1194
1195 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1196 #[cfg_attr(test, derive(schemars::JsonSchema))]
1197 pub struct InitializeParams {
1198 pub protocol: u32,
1199 pub limits: HostLimits,
1200 }
1201
1202 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1203 #[cfg_attr(test, derive(schemars::JsonSchema))]
1204 pub struct ActivateParams {
1205 pub owner: OwnerRef,
1206 #[serde(
1207 default,
1208 skip_serializing_if = "Option::is_none",
1209 deserialize_with = "present_entry"
1210 )]
1211 pub scope: Option<EntryRef>,
1212 pub plugin_name: String,
1213 pub entry: EntryRef,
1214 /// The plugin's settings (`[plugins."<name>".config]`), delivered as the
1215 /// second argument of `apply`. Always an object; `{}` when none.
1216 #[serde(default = "empty_object")]
1217 pub config: Value,
1218 /// The plugin's own writable directory (read-only string to the plugin).
1219 /// The same for every entry of one owner.
1220 #[serde(default, skip_serializing_if = "Option::is_none")]
1221 pub data_dir: Option<String>,
1222 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1223 pub bundled_first_party: bool,
1224 }
1225
1226 fn empty_object() -> Value {
1227 json!({})
1228 }
1229
1230 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1231 #[cfg_attr(test, derive(schemars::JsonSchema))]
1232 pub struct DeactivateParams {
1233 pub owner: OwnerRef,
1234 #[serde(
1235 default,
1236 skip_serializing_if = "Option::is_none",
1237 deserialize_with = "present_entry"
1238 )]
1239 pub entry: Option<EntryRef>,
1240 }
1241
1242 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1243 #[cfg_attr(test, derive(schemars::JsonSchema))]
1244 pub struct ToolCallParams {
1245 pub handle: u64,
1246 pub call_id: String,
1247 pub input: Value,
1248 pub deadline_ms: u64,
1249 /// The workspace of the session the call comes from, and no other. Absent
1250 /// when its path is not valid UTF-8.
1251 #[serde(default, skip_serializing_if = "Option::is_none")]
1252 pub workspace: Option<String>,
1253 /// The invocation ticket: present only when this call runs under the turn
1254 /// loop's permission gate, and what `core/call` must present. Absent for a
1255 /// call with no gate (one nested in `execute_tools`, a test), whose tool
1256 /// then has no way to ask the core for anything.
1257 #[serde(default, skip_serializing_if = "Option::is_none")]
1258 pub ticket: Option<String>,
1259 #[serde(default, skip_serializing_if = "Option::is_none")]
1260 pub checkpoint_ticket: Option<String>,
1261 #[serde(default, skip_serializing_if = "Option::is_none")]
1262 pub question_ticket: Option<String>,
1263 #[serde(default, skip_serializing_if = "Option::is_none")]
1264 pub subagent_ticket: Option<String>,
1265 #[serde(default, skip_serializing_if = "Option::is_none")]
1266 pub broker_tickets: Option<Vec<DshBrokerTicketWire>>,
1267 #[serde(default, skip_serializing_if = "Option::is_none")]
1268 pub caller_tools: Option<Vec<String>>,
1269 /// Per-invocation identity; never cached at activation or by the host root.
1270 #[serde(default, skip_serializing_if = "Option::is_none")]
1271 pub session_id: Option<String>,
1272 #[serde(default, skip_serializing_if = "Option::is_none")]
1273 pub agent_id: Option<String>,
1274 #[serde(default, skip_serializing_if = "Option::is_none")]
1275 pub origin_turn_id: Option<String>,
1276 }
1277
1278 /// One user invocation of a registered command. `raw_input` is what follows
1279 /// the command name, trimmed (the core's slash-command parser trims it).
1280 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1281 #[cfg_attr(test, derive(schemars::JsonSchema))]
1282 pub struct CommandRunParams {
1283 pub handle: u64,
1284 pub command_id: String,
1285 pub raw_input: String,
1286 pub deadline_ms: u64,
1287 /// The workspace the user ran the command in, and no other.
1288 #[serde(default, skip_serializing_if = "Option::is_none")]
1289 pub workspace: Option<String>,
1290 #[serde(default, skip_serializing_if = "Option::is_none")]
1291 pub session_id: Option<String>,
1292 #[serde(default, skip_serializing_if = "Option::is_none")]
1293 pub agent_id: Option<String>,
1294 #[serde(default, skip_serializing_if = "Option::is_none")]
1295 pub origin_turn_id: Option<String>,
1296 }
1297
1298 /// A Rust-composed view of a pending call. No session handle or invocation
1299 /// ticket crosses this boundary.
1300 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1301 #[cfg_attr(test, derive(schemars::JsonSchema))]
1302 #[serde(deny_unknown_fields)]
1303 pub struct HookCallPayload {
1304 pub name: String,
1305 pub call_id: String,
1306 pub input: Value,
1307 pub mode: String,
1308 pub workspace: String,
1309 pub model: String,
1310 }
1311
1312 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1313 #[cfg_attr(test, derive(schemars::JsonSchema))]
1314 #[serde(deny_unknown_fields)]
1315 pub struct HookEvaluateParams {
1316 pub handle: u64,
1317 pub event: String,
1318 pub payload: HookCallPayload,
1319 pub deadline_ms: u64,
1320 }
1321
1322 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1323 #[cfg_attr(test, derive(schemars::JsonSchema))]
1324 #[serde(deny_unknown_fields)]
1325 pub struct PluginRouteHeaderWire {
1326 pub name: String,
1327 pub value: String,
1328 }
1329
1330 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1331 #[cfg_attr(test, derive(schemars::JsonSchema))]
1332 #[serde(deny_unknown_fields)]
1333 pub struct PluginRouteDispatchParams {
1334 pub owner: OwnerRef,
1335 pub method: String,
1336 pub path: String,
1337 #[serde(default, skip_serializing_if = "Option::is_none")]
1338 pub query: Option<String>,
1339 pub headers: Vec<PluginRouteHeaderWire>,
1340 #[serde(default, skip_serializing_if = "Option::is_none")]
1341 pub body_base64: Option<String>,
1342 pub deadline_ms: u64,
1343 }
1344
1345 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1346 #[cfg_attr(test, derive(schemars::JsonSchema))]
1347 #[serde(deny_unknown_fields)]
1348 pub struct PluginRouteDispatchResult {
1349 pub matched: bool,
1350 pub status: u16,
1351 pub headers: Vec<PluginRouteHeaderWire>,
1352 #[serde(default, skip_serializing_if = "Option::is_none")]
1353 pub body_base64: Option<String>,
1354 }
1355
1356 /// Monotonic proposals. Rust folds them with native hooks and re-prepares
1357 /// revised input through every policy and approval gate.
1358 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1359 #[cfg_attr(test, derive(schemars::JsonSchema))]
1360 #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1361 pub enum HookVerdictWire {
1362 Abstain,
1363 Deny { reason: String },
1364 Ask { reason: String },
1365 Annotate { text: String },
1366 Revise { input: Map<String, Value> },
1367 }
1368
1369 #[derive(Debug, Clone, PartialEq)]
1370 pub enum CoreRequest {
1371 Ping,
1372 Initialize(InitializeParams),
1373 /// Production relies on stdin EOF at process exit (the host is shared by
1374 /// every engine in the process); the bounded shutdown is test-driven.
1375 #[cfg(any(test, feature = "test-support"))]
1376 Shutdown,
1377 Activate(ActivateParams),
1378 Deactivate(DeactivateParams),
1379 ToolCall(ToolCallParams),
1380 CommandRun(CommandRunParams),
1381 HookEvaluate(HookEvaluateParams),
1382 PluginRouteDispatch(PluginRouteDispatchParams),
1383 HarnessRun(HarnessRunParams),
1384 McpClose(McpCloseParams),
1385 McpRequest(McpRequestParams),
1386 McpOpen(Box<McpOpenParams>),
1387 }
1388
1389 impl CoreRequest {
1390 #[must_use]
1391 pub fn method(&self) -> &'static str {
1392 match self {
1393 Self::Ping => "host/ping",
1394 Self::Initialize(_) => "host/initialize",
1395 #[cfg(any(test, feature = "test-support"))]
1396 Self::Shutdown => "host/shutdown",
1397 Self::Activate(_) => "ext/activate",
1398 Self::Deactivate(_) => "ext/deactivate",
1399 Self::ToolCall(_) => "tool/call",
1400 Self::CommandRun(_) => "command/run",
1401 Self::HookEvaluate(_) => "hook/evaluate",
1402 Self::PluginRouteDispatch(_) => "plugin_route/dispatch",
1403 Self::HarnessRun(_) => "harness/run",
1404 Self::McpClose(_) => "mcp/close",
1405 Self::McpRequest(_) => "mcp/request",
1406 Self::McpOpen(_) => "mcp/open",
1407 }
1408 }
1409
1410 #[must_use]
1411 pub fn params(&self) -> Value {
1412 match self {
1413 Self::Ping => json!({}),
1414 Self::Initialize(p) => to_value(p),
1415 #[cfg(any(test, feature = "test-support"))]
1416 Self::Shutdown => json!({}),
1417 Self::Activate(p) => to_value(p),
1418 Self::Deactivate(p) => to_value(p),
1419 Self::ToolCall(p) => to_value(p),
1420 Self::CommandRun(p) => to_value(p),
1421 Self::HookEvaluate(p) => to_value(p),
1422 Self::PluginRouteDispatch(p) => to_value(p),
1423 Self::HarnessRun(p) => to_value(p),
1424 Self::McpClose(p) => to_value(p),
1425 Self::McpRequest(p) => to_value(p),
1426 Self::McpOpen(p) => to_value(p),
1427 }
1428 }
1429
1430 /// How long the core waits for this request's answer before it sends
1431 /// `$/cancel`, forgets the call and fails it with
1432 /// `HostCallError::Timeout` (`HostProcess::call`). The match is
1433 /// exhaustive, so no request can be added without a deadline.
1434 ///
1435 /// | method | deadline | why |
1436 /// |---|---|---|
1437 /// | `host/initialize` | `HANDSHAKE_DEADLINE` (30 s) | the whole handshake has the same budget |
1438 /// | `host/ping` | `PING_DEADLINE` (10 s) | the heartbeat supervises pings with its own `ping_timeout`/`hang_timeout` and kills a silent host; this bounds any other caller |
1439 /// | `host/shutdown` | 2 s | tests only |
1440 /// | `ext/activate` | `ACTIVATE_DEADLINE` + 1 s | the host enforces activation's own deadline; 1 s for its answer to arrive |
1441 /// | `ext/deactivate` | `DISPOSE_DEADLINE` + 500 ms | the same, for disposal |
1442 /// | `tool/call` | its `deadline_ms` | the host is told the bound the core enforces (`SupervisionOptions::tool_call_deadline`, 120 s) |
1443 /// | `command/run` | its `deadline_ms` | the same, for a command the user is waiting on (`SupervisionOptions::command_run_deadline`, 30 s) |
1444 #[must_use]
1445 pub fn deadline(&self) -> Duration {
1446 use super::supervisor::{
1447 ACTIVATE_DEADLINE, DISPOSE_DEADLINE, HANDSHAKE_DEADLINE, PING_DEADLINE,
1448 };
1449 match self {
1450 Self::Ping => PING_DEADLINE,
1451 Self::Initialize(_) => HANDSHAKE_DEADLINE,
1452 #[cfg(any(test, feature = "test-support"))]
1453 Self::Shutdown => Duration::from_secs(2),
1454 Self::Activate(_) => ACTIVATE_DEADLINE + Duration::from_secs(1),
1455 Self::Deactivate(_) => DISPOSE_DEADLINE + Duration::from_millis(500),
1456 Self::ToolCall(params) => Duration::from_millis(params.deadline_ms),
1457 Self::CommandRun(params) => Duration::from_millis(params.deadline_ms),
1458 Self::HookEvaluate(params) => Duration::from_millis(params.deadline_ms),
1459 Self::PluginRouteDispatch(params) => Duration::from_millis(params.deadline_ms),
1460 Self::HarnessRun(params) => Duration::from_millis(params.deadline_ms),
1461 Self::McpClose(params) => Duration::from_millis(params.deadline_ms),
1462 Self::McpRequest(params) => Duration::from_millis(params.deadline_ms),
1463 Self::McpOpen(params) => Duration::from_millis(params.deadline_ms),
1464 }
1465 }
1466
1467 #[must_use]
1468 pub fn to_value(&self, id: u64) -> Value {
1469 request_value(id, self.method(), self.params())
1470 }
1471 }
1472
1473 /// `registry/register` answer: a handle, or a refusal the host reports as a
1474 /// failed activation.
1475 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1476 #[cfg_attr(test, derive(schemars::JsonSchema))]
1477 #[serde(untagged)]
1478 pub enum RegisterResult {
1479 Admitted { handle: u64 },
1480 Refused { refused: String },
1481 }
1482
1483 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1484 #[cfg_attr(test, derive(schemars::JsonSchema))]
1485 #[serde(tag = "status", rename_all = "snake_case")]
1486 pub enum ActivateResult {
1487 Ok {
1488 tools: Vec<String>,
1489 #[serde(default)]
1490 commands: Vec<String>,
1491 },
1492 Failed {
1493 diagnostic: String,
1494 },
1495 }
1496
1497 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1498 #[cfg_attr(test, derive(schemars::JsonSchema))]
1499 pub struct DeactivateResult {
1500 pub disposed: bool,
1501 pub leaked: Vec<String>,
1502 }
1503
1504 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1505 #[cfg_attr(test, derive(schemars::JsonSchema))]
1506 #[serde(tag = "type", rename_all = "snake_case")]
1507 pub enum ContentBlockWire {
1508 Text { text: String },
1509 ImageRef { attachment_id: String },
1510 }
1511
1512 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1513 #[cfg_attr(test, derive(schemars::JsonSchema))]
1514 pub struct ToolResultWire {
1515 pub content: Vec<ContentBlockWire>,
1516 pub is_error: bool,
1517 #[serde(
1518 default,
1519 skip_serializing_if = "Option::is_none",
1520 deserialize_with = "present"
1521 )]
1522 pub structured: Option<Value>,
1523 }
1524
1525 /// A command's answer. The core shows `text` to the user (stripped of
1526 /// terminal escapes and bounded) and, for `submit`, sends `prompt` as the
1527 /// user's next message through the ordinary turn: the model's work after that
1528 /// is gated like any other. `error` is shown as a failure.
1529 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1530 #[cfg_attr(test, derive(schemars::JsonSchema))]
1531 #[serde(tag = "kind", rename_all = "snake_case")]
1532 pub enum CommandResultWire {
1533 Success {
1534 #[serde(default, skip_serializing_if = "Option::is_none")]
1535 text: Option<String>,
1536 },
1537 Error {
1538 text: String,
1539 },
1540 Submit {
1541 prompt: String,
1542 /// An optional note shown to the user alongside the submission.
1543 #[serde(default, skip_serializing_if = "Option::is_none")]
1544 text: Option<String>,
1545 },
1546 }
1547
1548 /// One core→host message, parsed back (tests and the corpus only).
1549 #[cfg(any(test, feature = "test-support"))]
1550 #[derive(Debug, Clone, PartialEq)]
1551 pub enum CoreMessage {
1552 Request {
1553 id: u64,
1554 request: Box<CoreRequest>,
1555 },
1556 Cancel(CancelParams),
1557 Response {
1558 id: u64,
1559 outcome: Result<Value, RpcErrorWire>,
1560 },
1561 }
1562
1563 /// Parse a core→host message (the shape this side writes) bound for a host of
1564 /// `tier`.
1565 #[cfg(any(test, feature = "test-support"))]
1566 pub fn parse_core_message(value: Value, tier: HostTier) -> Result<CoreMessage, ProtocolError> {
1567 let envelope = decode_envelope(value)?;
1568 let Some(method) = envelope.method.clone() else {
1569 let (id, outcome) = decode_response(envelope)?;
1570 return Ok(CoreMessage::Response { id, outcome });
1571 };
1572 let p = envelope.params;
1573 let Some(id) = admit(Direction::CoreToHost, &method, envelope.id, tier)? else {
1574 return match method.as_str() {
1575 "$/cancel" => Ok(CoreMessage::Cancel(params(&method, p)?)),
1576 _ => Err(undecoded(&method)),
1577 };
1578 };
1579 let request = match method.as_str() {
1580 "host/initialize" => CoreRequest::Initialize(params(&method, p)?),
1581 "host/shutdown" => {
1582 let _: EmptyParams = params(&method, p)?;
1583 CoreRequest::Shutdown
1584 }
1585 "host/ping" => {
1586 let _: EmptyParams = params(&method, p)?;
1587 CoreRequest::Ping
1588 }
1589 "ext/activate" => CoreRequest::Activate(params(&method, p)?),
1590 "ext/deactivate" => CoreRequest::Deactivate(params(&method, p)?),
1591 "tool/call" => CoreRequest::ToolCall(params(&method, p)?),
1592 "command/run" => CoreRequest::CommandRun(params(&method, p)?),
1593 "hook/evaluate" => CoreRequest::HookEvaluate(params(&method, p)?),
1594 "plugin_route/dispatch" => CoreRequest::PluginRouteDispatch(params(&method, p)?),
1595 "harness/run" => CoreRequest::HarnessRun(params(&method, p)?),
1596 "mcp/close" => CoreRequest::McpClose(params(&method, p)?),
1597 "mcp/request" => CoreRequest::McpRequest(params(&method, p)?),
1598 "mcp/open" => CoreRequest::McpOpen(params(&method, p)?),
1599 _ => return Err(undecoded(&method)),
1600 };
1601 Ok(CoreMessage::Request {
1602 id,
1603 request: Box::new(request),
1604 })
1605 }
1606
1607 #[cfg(any(test, feature = "test-support"))]
1608 impl CoreMessage {
1609 #[must_use]
1610 pub fn to_value(&self) -> Value {
1611 match self {
1612 Self::Request { id, request } => request.to_value(*id),
1613 Self::Cancel(p) => notification_value("$/cancel", to_value(p)),
1614 Self::Response { id, outcome } => response_value(*id, outcome),
1615 }
1616 }
1617 }
1618
1619 #[must_use]
1620 pub fn cancel_value(id: u64) -> Value {
1621 notification_value("$/cancel", json!({ "id": id }))
1622 }
1623
1624 #[cfg(test)]
1625 mod tests;
1626
1626 lines RUST