Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions pkgs/id/contract/shell-contract.v1.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"contract": "id-shell",
"version": 1,
"revision": 11,
"revision": 12,
"description": "The client-server frame protocol every id shell (terminal, web, native) speaks to a world host. Version 1 is the protocol behind the /id-world/1 ALPN. A shell sends only frames and fields named here; it ignores server frame types and fields it does not know. Additive changes bump `revision`; removing or changing a frame or field needs version 2 and a new ALPN. Event-producing frames must name their stable world-event contract here.",
"max_frame_bytes": 1048576,
"routing_fields": ["world"],
Expand All @@ -13,7 +13,7 @@
},
"websocket": {
"path": "/ws/world",
"envelope": "text-message",
"envelope": "text-message; binary-message for negotiated binary view patches (revision 12)",
"session": "one WebSocket connection"
},
"ssh-exec": {
Expand Down Expand Up @@ -45,6 +45,7 @@
"capability": { "type": "string", "max_bytes": 256 },
"after": "u64?",
"screen_patches": { "type": "bool", "optional": true, "nullable": false },
"screen_msgpack": { "type": "bool", "optional": true, "nullable": false },
"agent_profile": { "type": "bool", "optional": true, "nullable": false },
"resume_token": { "type": "string", "optional": true, "nullable": true, "max_bytes": 64 }
}
Expand Down Expand Up @@ -589,6 +590,7 @@
"redacted_keys": ["seed"]
},
"features": {
"screen_msgpack": "Revision 12 (negotiated binary screen patches, F12.11 phase 3, issue #12242; design doc/2026-11-01_design_id805.md sections 3, 5, 6): the join frame's `screen_msgpack` field is the capability flag — a shell that sets it, together with `screen_patches`, on a byte-capable transport receives screen patch frames as binary frames instead of JSON `view` frames. A binary patch frame is one versioned MessagePack value (id-core `screen_codec`, codec version 1) carrying exactly the fields of the `view` frame it replaces — `sequence`, `view_revision`, `base_view_revision`, `resume_token`, and the `patch` — with the same world-event cursor and view-revision semantics; full views, resume-token issuance, and every other frame stay on the text path. On the length-prefixed transports (iroh, ssh-exec) a binary frame body is marked with a single leading NUL byte, which no JSON text frame can start with; on WebSocket it is a binary message. Negotiation is offer-and-observe: a host or transport without the revision simply keeps sending JSON patch frames, and a shell must accept both for a session that offered the flag. Client frames remain text JSON in both directions of the negotiation; a binary frame from a client is malformed input and fails the session safely, like a non-UTF-8 frame. A host never sends a binary frame to a session that did not offer the flag, and never guesses an encoding: an unsupported codec version or a malformed binary payload is a decode failure for the shell, which falls back to a full view by rejoining or presenting its retained full-view path.",
"agent_profile": "Revision 11 (agent profile for #6300, design doc/2026-11-09_design_id6300_agents_in_worlds_v1.md sections 4.2, 4.3, 8, 9.1): the capability flag is the join frame's `agent_profile` field — a shell that sets it advertises it can consume semantic diffs. A joined agent-profile shell may send `screen_subscribe` naming a screen region (an object with u16 `x`, `y`, `width`, `height` in screen cells) and/or semantic event classes (`chat_posted`, `input_applied`, `object_changed`, `system_event`, `program_changed`; an empty list means all classes, an absent field means no event diffs). The host answers with a `screen_subscription` frame echoing the active subscription and the current screen revision, then sends `semantic_diff` frames scoped to the subscription: event diffs for subscribed classes as world events commit, and region diffs (changes of kind `region_changed`, one per changed row inside the region, carrying that row's new text) as views change. Each semantic_diff names the world `sequence` it follows, the `view_revision` it was computed at, and its `base_view_revision` when it diffs against a known earlier screen. Agent input frames (`input`, `chat`, `paste`, `form_result`, `pointer`) may carry `screen_revision`, the stale-decision token: the screen revision the input was decided against. The host applies such an input only while that revision is still the session's current screen revision; otherwise it rejects the input with an `error` frame whose code is `stale_decision`, commits nothing, and returns the current view. A host without this revision does not know the flag and serves the agent full view frames at reduced fidelity with identical authority; a shell that never sets the flag is unaffected.",
"surface": "A view frame may carry a typed `surface` (the portable screen document). A shell that does not understand it renders `data`.",
"input_events": "Pointer input per the input event model design (doc/2026-11-08T05-48-47Z_design_input_event_model, issue #1831 slice S2; landed in revision 10). Coordinates are cells in the target surface's grid: producers map device pixels to cells at the edge, so frames never carry pixels. `pointer` frames are class event — journaled and replayed like `input`; a drag is a press, a sequence of drag_move frames, and a release, and each drag_move is its own frame, so the frame limit bounds one move, never the whole path. `hover` frames are class ephemeral: connection-local presentation context, never journaled and never seen by other sessions. A pointer_id is unique only within its producing connection; the host namespaces it with the connection's identity when journaling, and press/release pairing is scoped to that (connection, pointer_id) pair. An event an environment cannot produce, or that the target app did not declare in its manifest `interfaces.input`, is refused explicitly: the host answers `input_refused` naming the event and a reason from that frame's enum — an input event is never silently dropped."
Expand Down
34 changes: 34 additions & 0 deletions pkgs/id/crates/id-core/src/frames.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,30 @@ pub async fn write_frame_to<W: AsyncWrite + Unpin>(send: &mut W, payload: &[u8])
Ok(())
}

/// First byte of a binary frame body on a length-prefixed transport
/// (F12.11 phase 3, #12242). Text frames are JSON objects and always
/// start with `{`; a leading NUL therefore marks a frame body as
/// binary unambiguously, without changing the v1 text envelope bytes.
/// Only sessions that negotiated binary frames ever emit one, and a
/// receiver that did not negotiate treats the body as malformed input,
/// exactly like a non-UTF-8 body.
pub const BINARY_FRAME_MARKER: u8 = 0;

/// The frame body for `payload` as a binary frame: the marker byte
/// followed by the payload.
pub fn mark_binary_frame(payload: &[u8]) -> Vec<u8> {
let mut body = Vec::with_capacity(1 + payload.len());
body.push(BINARY_FRAME_MARKER);
body.extend_from_slice(payload);
body
}

/// The binary payload of a frame body, when the body carries the
/// binary marker; `None` for text bodies.
pub fn unmark_binary_frame(body: &[u8]) -> Option<&[u8]> {
body.strip_prefix(&[BINARY_FRAME_MARKER])
}

/// Read one frame from any byte stream. `Ok(None)` means the peer finished
/// cleanly between frames.
///
Expand Down Expand Up @@ -315,6 +339,16 @@ pub async fn read_frame(recv: &mut RecvStream) -> Result<Option<Vec<u8>>> {
mod tests {
use super::*;

#[test]
fn binary_frame_marking_round_trips_and_leaves_text_alone() {
let marked = mark_binary_frame(&[0x82, 0xa7, b'v']);
assert_eq!(unmark_binary_frame(&marked), Some(&[0x82, 0xa7, b'v'][..]));
assert_eq!(unmark_binary_frame(&[]), None);
assert_eq!(unmark_binary_frame(br#"{"type":"view"}"#), None);
// An empty binary payload is still a binary frame.
assert_eq!(unmark_binary_frame(&mark_binary_frame(&[])), Some(&[][..]));
}

#[tokio::test]
async fn the_byte_stream_framing_round_trips_and_ends_cleanly() {
let (mut client, mut server) = tokio::io::duplex(64);
Expand Down
153 changes: 152 additions & 1 deletion pkgs/id/crates/id-core/src/screen_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,93 @@ pub fn decode_patch(bytes: &[u8]) -> Result<ScreenPatch, ScreenCodecError> {
Ok(frame.patch)
}

/// One negotiated binary view frame (F12.11 phase 3, #12242): the
/// `ScreenPatch` a `view` server frame carries, plus the envelope
/// fields that frame carries alongside the patch — the world-event
/// `sequence`, the target `view_revision`, the `base_view_revision`
/// the patch applies to, and the resume token naming the target
/// revision. A session sends this instead of the JSON `view` frame
/// only after the client negotiated binary patches at join; the
/// world-event cursor and view-revision semantics are unchanged.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ViewPatchFrame {
/// World-event cursor this view follows.
pub sequence: u64,
/// The session view revision this patch produces.
pub view_revision: u64,
/// The view revision the patch applies to.
pub base_view_revision: Option<u64>,
/// Resume token naming `view_revision`, when one is issued.
pub resume_token: Option<String>,
/// The screen delta itself.
pub patch: ScreenPatch,
}

#[derive(Serialize)]
#[serde(deny_unknown_fields)]
struct VersionedViewPatch<'a> {
version: u8,
#[serde(borrow)]
frame: &'a ViewPatchFrame,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct OwnedVersionedViewPatch {
version: u8,
frame: ViewPatchFrame,
}

/// Encodes a view frame as one versioned MessagePack value.
pub fn encode_view_patch(frame: &ViewPatchFrame) -> Result<Vec<u8>, ScreenCodecError> {
let bytes = rmp_serde::to_vec_named(&VersionedViewPatch {
version: SCREEN_CODEC_VERSION,
frame,
})?;
if bytes.len() > MAX_SCREEN_FRAME_BYTES {
return Err(ScreenCodecError::TooLarge);
}
Ok(bytes)
}

/// Decodes one bounded, versioned MessagePack view frame.
pub fn decode_view_patch(bytes: &[u8]) -> Result<ViewPatchFrame, ScreenCodecError> {
if bytes.len() > MAX_SCREEN_FRAME_BYTES {
return Err(ScreenCodecError::TooLarge);
}
let mut deserializer = rmp_serde::Deserializer::new(Cursor::new(bytes));
let frame = <OwnedVersionedViewPatch as Deserialize>::deserialize(&mut deserializer)?;
if usize::try_from(deserializer.into_inner().position()).ok() != Some(bytes.len()) {
return Err(ScreenCodecError::TrailingBytes);
}
if frame.version != SCREEN_CODEC_VERSION {
return Err(ScreenCodecError::UnsupportedVersion(frame.version));
}
Ok(frame.frame)
}

#[cfg(test)]
mod tests {
use proptest::prelude::*;

use super::{decode_patch, encode_patch};
use super::{
MAX_SCREEN_FRAME_BYTES, ScreenCodecError, ViewPatchFrame, decode_patch, decode_view_patch,
encode_patch, encode_view_patch,
};
use crate::world_presentation::{CellRun, ScreenCell, ScreenPatch, StyleToken};

const GOLDEN_VIEW_PATCH: &[u8] = &[
0x82, 0xa7, b'v', b'e', b'r', b's', b'i', b'o', b'n', 0x01, 0xa5, b'f', b'r', b'a', b'm',
b'e', 0x85, 0xa8, b's', b'e', b'q', b'u', b'e', b'n', b'c', b'e', 0x07, 0xad, b'v', b'i',
b'e', b'w', b'_', b'r', b'e', b'v', b'i', b's', b'i', b'o', b'n', 0x03, 0xb2, b'b', b'a',
b's', b'e', b'_', b'v', b'i', b'e', b'w', b'_', b'r', b'e', b'v', b'i', b's', b'i', b'o',
b'n', 0x02, 0xac, b'r', b'e', b's', b'u', b'm', b'e', b'_', b't', b'o', b'k', b'e', b'n',
0xc0, 0xa5, b'p', b'a', b't', b'c', b'h', 0x84, 0xa7, b'v', b'e', b'r', b's', b'i', b'o',
b'n', 0x01, 0xa5, b'w', b'i', b'd', b't', b'h', 0x02, 0xa6, b'h', b'e', b'i', b'g', b'h',
b't', 0x01, 0xa4, b'r', b'u', b'n', b's', 0x90,
];

fn screen_cell() -> impl Strategy<Value = ScreenCell> {
(
prop_oneof![
Expand Down Expand Up @@ -153,5 +233,76 @@ mod tests {
let encoded = encode_patch(&patch).unwrap();
prop_assert_eq!(decode_patch(&encoded).unwrap(), patch);
}

#[test]
fn view_patch_frames_round_trip_through_messagepack(
patch in populated_patch(),
sequence in any::<u64>(),
view_revision in any::<u64>(),
base_view_revision in prop::option::of(any::<u64>()),
resume_token in prop::option::of("[0-9a-f]{1,64}"),
) {
let frame = ViewPatchFrame {
sequence,
view_revision,
base_view_revision,
resume_token,
patch,
};
let encoded = encode_view_patch(&frame).unwrap();
prop_assert_eq!(decode_view_patch(&encoded).unwrap(), frame);
}
}

fn sample_view_patch() -> ViewPatchFrame {
ViewPatchFrame {
sequence: 7,
view_revision: 3,
base_view_revision: Some(2),
resume_token: None,
patch: ScreenPatch {
version: 1,
width: 2,
height: 1,
runs: Vec::new(),
},
}
}

#[test]
fn view_patch_matches_versioned_messagepack_golden_vector() {
let encoded = encode_view_patch(&sample_view_patch()).unwrap();
assert_eq!(encoded, GOLDEN_VIEW_PATCH);
assert_eq!(
decode_view_patch(GOLDEN_VIEW_PATCH).unwrap(),
sample_view_patch()
);
}

#[test]
fn view_patch_rejects_unsupported_version_and_malformed_frames() {
let mut unsupported = encode_view_patch(&sample_view_patch()).unwrap();
unsupported[9] = 2;
assert!(matches!(
decode_view_patch(&unsupported),
Err(ScreenCodecError::UnsupportedVersion(2))
));
assert!(matches!(
decode_view_patch(&[0xc1]),
Err(ScreenCodecError::Invalid(_))
));

let mut trailing = encode_view_patch(&sample_view_patch()).unwrap();
trailing.push(0xc0);
assert!(matches!(
decode_view_patch(&trailing),
Err(ScreenCodecError::TrailingBytes)
));

let oversized = vec![0; MAX_SCREEN_FRAME_BYTES + 1];
assert!(matches!(
decode_view_patch(&oversized),
Err(ScreenCodecError::TooLarge)
));
}
}
16 changes: 15 additions & 1 deletion pkgs/id/crates/id-web/src/world_ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,10 @@ impl SessionIo for WsIo {
return Inbound::Text(text.to_string());
}
Some(Ok(Message::Text(_))) => return Inbound::Oversized,
Some(Ok(Message::Binary(_))) => return Inbound::Unsupported,
Some(Ok(Message::Binary(bytes))) if bytes.len() <= MAX_FRAME_BYTES => {
return Inbound::Bytes(bytes.to_vec());
}
Some(Ok(Message::Binary(_))) => return Inbound::Oversized,
Some(Ok(Message::Ping(payload))) => {
if self.sender.send(Message::Pong(payload)).await.is_err() {
return Inbound::Closed;
Expand All @@ -693,6 +696,17 @@ impl SessionIo for WsIo {
async fn send(&mut self, frame: String) -> bool {
self.sender.send(Message::Text(frame.into())).await.is_ok()
}

fn supports_bytes(&self) -> bool {
true
}

async fn send_bytes(&mut self, frame: Vec<u8>) -> bool {
self.sender
.send(Message::Binary(frame.into()))
.await
.is_ok()
}
}

#[cfg(test)]
Expand Down
4 changes: 2 additions & 2 deletions pkgs/id/crates/id-worlds/src/shell_contract/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ fn pointer_and_hover_frames_conform_to_the_input_event_model() {
// (class event), hover is ephemeral, refusals name a reason from
// the design's table, and scroll deltas are signed cell units.
let contract = contract();
assert_eq!(contract.revision, 11);
assert_eq!(contract.revision, 12);
assert_eq!(contract.client_frames["pointer"].class, FrameClass::Event);
assert_eq!(contract.client_frames["hover"].class, FrameClass::Ephemeral);
assert_eq!(
Expand Down Expand Up @@ -719,7 +719,7 @@ fn agent_profile_frames_conform_and_are_additive() {
// stale-decision token on agent input frames. Human shells, which
// never set the flag or send the new frames, are unaffected.
let contract = contract();
assert_eq!(contract.revision, 11);
assert_eq!(contract.revision, 12);
assert_eq!(
contract.client_frames["screen_subscribe"].class,
FrameClass::Ephemeral
Expand Down
30 changes: 27 additions & 3 deletions pkgs/id/crates/id-worlds/src/world_net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,9 +417,12 @@ impl StreamIo {
.await;
if admitted {
match read_frame_body(&mut recv, len).await {
Ok(body) => match String::from_utf8(body) {
Ok(text) => Inbound::Text(text),
Err(_) => Inbound::Unsupported,
Ok(body) => match crate::frames::unmark_binary_frame(&body) {
Some(payload) => Inbound::Bytes(payload.to_vec()),
None => match String::from_utf8(body) {
Ok(text) => Inbound::Text(text),
Err(_) => Inbound::Unsupported,
},
},
Err(_) => Inbound::Closed,
}
Expand Down Expand Up @@ -478,6 +481,27 @@ impl SessionIo for StreamIo {
write_frame(&mut self.send, frame.as_bytes()).await.is_ok()
}

fn supports_bytes(&self) -> bool {
true
}

async fn send_bytes(&mut self, frame: Vec<u8>) -> bool {
// Same charge and envelope as a text frame; the body carries
// the binary marker so the peer's reader reports it as bytes.
let body = crate::frames::mark_binary_frame(&frame);
let admitted = charge_frame_with_backpressure(
&self.abuse,
self.remote,
self.authorized.load(Ordering::Acquire),
body.len(),
)
.await;
if !admitted {
return false;
}
write_frame(&mut self.send, &body).await.is_ok()
}

fn mark_authorized(&mut self) {
self.authorized.store(true, Ordering::Release);
}
Expand Down
Loading