opencode/packages/cli-rs/docs/F.2.md
Simon Klee 26cfacbbf9
fix(cli-rs): fix the API types carbon found wrong in F.2
carbon-1: a union member that is itself a union with several tags joins the
outer tag, so SessionLogItem routes log.synced to LogSynced and its tag()
delegates to the inner enum.
carbon-2: Schema.NonEmptyArray(T) is Vec<T>, so form fields and tool
content are typed (FormField, ToolContent).
carbon-3: Ref_1 twins that Rust decodes the same as Ref share its type
(FormInfo, ShellInfo, FormAnswer, the inbox payloads, message parts).
carbon-4: untagged unions get a generated Deserialize that skips a member
whose required literal field holds another value, so an LSP server entry
with disabled: false keeps its command.
carbon-5: generated errors implement TaggedError, and DeclaredError::decode
checks the tag.

Call sites in crates/store and crates/ui follow the renamed types.
2026-11-04 19:51:14 +01:00

6.5 KiB

F.2: type mapping of the generated API client

script/gen/api.ts calls compile(ClientApi, …) with the options of the Promise client (packages/client/script/generate.ts:56-61). It projects every schema to its encoded (wire) form, or to its decoded form for query fields as the Promise client does, normalizes declarations as codegenAsts does (packages/httpapi-codegen/src/index.ts:1507-1550), and feeds them to SchemaRepresentation.toRepresentations. The emitter in script/rust/ walks the representations and writes crates/api/src/generated/{types,methods}.rs.

Types

Representation Rust
Named reference to an object pub struct named by identifierPart($ref) (Session.Info becomes SessionInfo)
Named reference to a string (branded IDs, paths) newtype pub struct SessionID(pub String), #[serde(transparent)]
Named reference to anything else pub type alias, or the enum below
Anonymous object struct named <Parent><Field> (for union members <Parent><Tag>), deduplicated by name and shape
Object with index signatures only BTreeMap<String, T>
Object with fields and an index signature struct with #[serde(flatten)] extra: BTreeMap<String, T>
String, template literal, single string literal String
Number with an isInt check i64, else f64
Boolean bool
Unknown, Any, Schema.Json, other declarations serde_json::Value
Uint8Array (binary bodies and responses) bytes::Bytes
Array with rest only, or Schema.NonEmptyArray(T) ([T, ...T[]]) Vec<T>; a tuple becomes a Rust tuple
Ref_1 that differs from Ref only in what Rust cannot see the type of Ref (see below)
Fields of type Never dropped (they can only be absent)

Fields:

  • An optional field becomes Option<T> with default and skip_serializing_if = "Option::is_none".
  • A nullable field (T | null) becomes Option<T>. Optional and nullable together becomes Option<Option<T>> with de::double_option, so absent (None) and null (Some(None)) stay distinct.
  • Unknown fields are ignored (no deny_unknown_fields), so a newer server's additions decode.

Twins: a schema reached both through REST (after the JSON transport) and through the event stream comes out as Ref and Ref_1. Types.sameRust compares them as Rust would decode them: it ignores annotations and checks other than isInt, treats Unknown, Any, and declarations alike, treats null and undefined members alike, and drops the JSON transport's "Infinity", "-Infinity", and "NaN" literals beside a number. Equal twins share the type of Ref, as httpapi-codegen collapses them. Twins that really differ (Session.Inbox.MovePayload has LocationRef on one side and LocationPublicRef on the other) keep two types.

Unions

Nested unions are flattened, and null and undefined members become Option. The rest falls in one of four kinds:

  1. String literals only. An enum with one unit variant per literal and Unknown(String). Its Deserialize and Serialize are written out by the emitter, so an unknown literal decodes.

  2. String literals and String (string suggestions). String.

  3. Objects that share a discriminator field whose value in every member is a literal, a union of literals, or a template literal with a literal prefix. Candidate keys in order: type, _tag, and then the first shared field that separates the members. The enum has one newtype variant per member and Unknown(serde_json::Value). Its Deserialize is generated by hand: it buffers a Value, reads the tag, matches exact literals first and then template prefixes (rpc. becomes the Rpc variant, which keeps the full name in its type field), and decodes the member with serde_json::from_value. A known tag that fails to decode is an error, not Unknown, so emitter mistakes show; an unknown tag or a missing tag is Unknown. Serialize writes the member as it is. Member structs keep the tag field as a String, so a variant shared by several tags still knows its tag.

    A member may itself be a union of objects. With one shared tag (Session.Message.Compaction, tagged inside by status), tag() returns that tag. With several (Session.Event.Durable inside SessionLogItem), every tag routes to the member, the inner enum must be tagged by the same key (the emitter fails otherwise), and tag() delegates to it.

    #[serde(tag = "...")] is not used: serde rejects a payload on #[serde(other)], and it cannot route a prefix (plan.review-carbon.md, carbon-3).

  4. Anything else (String | Object, Boolean | Object, objects told apart by required fields). An enum with variants in schema order and a last Unknown(serde_json::Value), serialized untagged. Its generated Deserialize tries the members in order. It skips an object member when one of its required literal fields holds another value: the Rust field is a plain bool or String, so without the check Config.LSP.Entry would read { command, disabled: false } as { disabled: true }.

Declared errors: every generated *Error struct implements error::TaggedError with its _tag (or name). DeclaredError::decode::<T>() rejects a body with another tag, as the TypeScript is<Error> guards do, and DeclaredError::is::<T>() checks only the tag.

Methods

  • One async fn per endpoint on Client, named by the client path in snake case (session.message.get becomes session_message_get, experimental.session.log becomes experimental_session_log).
  • Inputs are flattened as in the Promise client: one <Prefix>Input struct with every params, query, headers, and payload field. An opaque payload is one payload field. A trailing * path adds a path field encoded per segment. An input whose fields are all optional derives Default.
  • Every method takes &RequestOptions (per-call headers).
  • { data } envelopes are unwrapped. A no-content endpoint returns (). A binary endpoint returns Bytes; a binary payload is sent as application/octet-stream.
  • An SSE endpoint returns SseResponse<T>: the checked response body and the event type. F.3 parses it into a stream of T.
  • Query values serialize to JSON values and are bracket-encoded like appendQuery (packages/client/src/promise/generated/client.ts:2795-2810).
  • A response with a declared status decodes into Error::Declared with the status, _tag, message, and the body as a Value; any other status is Error::UnexpectedStatus. Other failures map to the remaining ClientError reasons.