docs/pkg/protocol.md

pkg/protocol — JSONL frame ownership

pkg/protocol defines the Go types behind every JSONL frame on EzAgent’s wire, the nested values those frames share, wire-compatible validation, and small encoding helpers. For every field, example, direction, and frame relationship, see the JSONL API catalog. It does not own transport (jsonlpipe), typed dispatch and RPC (ezagentapi), or command semantics and persistence (service, service/session).

Keep in sync: whenever any pkg/protocol/*.go file changes, update docs/agent-api/jsonl-api.html in the same change.

What does this package group together?

GroupWhat it owns
Lifecycle and agent streamStartup, prompt/steer/abort, and agent/turn/message frames
Sessions and configurationRoots, leaves, turns, queues, configuration requests, and model/provider results
CapabilitiesTool, plugin, macro, operation, heartbeat, and capability metadata frames
Shared values and validationMessages, content, usage, progress, attachments, and turn-role/storage validation
Encoding and ID helpersRequest/leaf ID extraction, framing, custom CSV, structural escaping, and display formatting

What must remain true when changing frames?

  • Only top-level frames carry Itr; nested values must not. ezagentapi stamps outbound copies and owns ordering, so protocol payloads must not acquire sequencing behavior.
  • Use PendingTurn as canonical ingress. Prompt, Steer, ToolResult, and QueuedMessage carry turn; it intentionally omits service-owned placement, identity, lifecycle, and storage fields. Its changes cross plugin, storage, and ingress boundaries.
  • Preserve validation boundaries. User-turn, tool-result, plugin, and storage validation deliberately differ. Attachment checks cover encoding, UTF-8/base64, size, metadata agreement, per-file, and aggregate limits; storage validates before persistence.
  • Treat JSON shape as compatibility surface. Tags, omitempty, pointer choices, and value-vs-pointer structs control emitted JSON. Do not simplify them without checking wire-shape tests and consumers.
  • Represent the earliest rewind boundary explicitly. rewind_leaf.new_tip_turn_id is a required JSON member; its empty string value means the boundary before the first turn. RewindLeaf.HasNewTipTurnID distinguishes that value from an omitted member after decoding.
  • Progress validation is producer-local; it is not service admission. ReportProgress validates descriptors and limits; a ProgressSnapshot replaces a subscriber projection, while the service remains authoritative for turn and capacity admission.
  • Pending questions are complete leaf state. LeafUpdated.PendingQuestions always encodes as an array, with [] as the clearing value. The only current question kind is the typed project_config_trust shape. question_reply accepts only that kind, a nonempty revision, and trust or reject.
  • Access source is optional and read-only. LeafUpdated.AccessSource and LeafStatsResponse.AccessSource project the same daemon-derived source: local, openai_subscription, muse_subscription, api_key, unknown, or unavailable. Active remote runs use host-reported information, never consumer credentials or model names. Idle/unloaded leaves can fall back to the last reported source saved in ordinary leaf properties for the same resolved model. Omitted discovery values preserve that record; an explicit unknown replaces it. Missing or unfamiliar wire values remain neutral. No credentials are exposed. See remembered model information.
  • Correlated responses may still reach callbacks. Error.RequestID and ExtractRequestID support service replies; ezagentapi owns typed RPC routing. Do not infer that every correlated response is hidden from callbacks.

What lives just outside this package?

  • jsonlpipe owns protocol-agnostic JSONL transport and connection lifecycle.
  • ezagentapi maps frames to typed operations, validates startup, dispatches callbacks, and correlates RPCs.
  • service gives frames command semantics; service/session materializes validated pending turns.
  • Capability authoring for tools, plugins, and macros starts at builtin capabilities.

Where are all fields, examples, and directions?

  • pkg/protocol/*.go — declarations, validators, and helpers; *_test.go — compatibility and boundary evidence.
  • JSONL API catalog — complete frame fields, examples, directions, and nested schemas.
  • EzAgent CSV — the custom apostrophe-quoted CSV contract; it is not ordinary CSV.

When changing this package, update this ownership page if its boundary, shape, or invariant changes—and always update the JSONL API catalog in the same change.

User-turn context

PendingTurn.steer is an optional boolean carried by every pending-turn container, including plugin inputs/results and queued messages. Omitted means unspecified; explicit false and true survive handoffs. Active assistant/tool admission supplies true only when unspecified. An idle call to steer does not by itself mark a follow-up. Plugins may mark synthetic user turns for downstream consumers. The flag is context, not an admission command, and has no separate stored column. The mode plugin writes its lasting classification in turn text.

The leading <mode ... /> text tag accepts optional mode and turn-type attributes independently. steer denotes input drafted during the preceding response/tool call; the legacy bash value denotes a background command completion for any interpreter. Missing attributes merge into one tag, existing background completion classification takes precedence over steer context, and neither type changes the applicable mode.

User pending turns may carry validated advanced.other_meta JSON object text, but not assistant-only advanced fields or the service-owned exit_message key. The internal background command completion convention uses the legacy key {"background_bash":{"task_id":"<trusted originating tool-call ID>"}}. Producers merge this correlation with existing metadata, preserving unrelated keys and nested extensions. Stored user turns retain it in existing other_meta. The TUI uses the nested marker, not prose or endpoint choice, to render background → command (<id>) with tool-result styling. No new stored kind or additional wire fields are involved.

background_bash is producer-supplied correlation, not independently authenticated provenance. Socket/API peers are trusted callers; this convention creates no separate caller permission or prompt-injection defense. The builtin captures the leaf when the command starts and delivers completion to that same leaf, independently of the TUI's current selection. It does not make command output trusted instructions.

LeafFiles and LeafFilesResult define the generic attach request and reply; LeafFileDescriptor is the nested file_id, key, path record. Both frames carry leaf_id and request_id. The daemon accepts only operation: attach. The JSONL catalog describes required fields, errors, and registration semantics.

Stored attachment byte ranges

GetAttachmentChunk and AttachmentChunk define the get_attachment_chunk → attachment_chunk single-range RPC. Requests require nonempty turn_id and request_id, a zero-based attachment_index integer, an int64 offset >= 0, and an int64 length from 1 through 98304 decoded bytes. The numeric request fields use pointers to reject omission and JSON null while accepting explicit index 0 and offset 0. They are required JSON integers, not strings or fractions.

The response echoes the turn, index, offset, and request ID. size is the actual total decoded file size; length is min(requested length, size - offset). data_b64 uses standard padded base64 for all files, including UTF-8 text. eof is true exactly when offset + length == size. Offset equal to size returns an empty EOF success, including an empty file at offset 0. Offset above size fails with attachment_range_error.

Invalid requests produce parse_error; turn lookup and access match get_turn, with turn_not_found for a missing turn. A nonexistent index produces attachment_not_found; a missing or corrupt blob produces internal_error. The reply is requester-only, never an event or subscriber broadcast. ezagentapi owns request correlation and late-reply dropping.

FileMeta already has size; this RPC adds no metadata fields. Clients can discover the actual size of a legacy attachment whose metadata omits it from the first chunk response. No protocol version bump, SQLite schema change, or PRAGMA user_version change is involved. There is no batch frame or automatic UI download behavior.