{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package wire\n\nPackage common is the memcode PROTOCOL contract: the wire types shared by the CLI (the client) and the api gateway (the server), the sdk/agent ↔ CLI stream-json envelope, the abstract Intent, shared error sentinels, and the model/pricing metadata both ledgers price against.\n\nIt is the single source of truth for everything that crosses a memcode wire. Both the cli and api modules redeclared these types independently once, and the drift caused real outages (tool input\\_schema, lane bypass) — this package exists so that can never happen again.\n\nInvariant: common holds the PROTOCOL only and is stdlib-only (zero third-party dependencies). It contains no prompt doctrine, no provider keys, no routing logic, and no capability interfaces — those live at their consuming boundary (the cli and api each declare the structural interface they need; a client implementation merely satisfies them). A guard test enforces the stdlib-only rule.\n\n## Constants\n\n```go\nconst (\n\t// client → CLI (control)\n\tMsgInitialize         = \"initialize\"          // first message; configure the session\n\tMsgUserTurn           = \"user_turn\"           // submit a user prompt (starts a turn)\n\tMsgPermissionResponse = \"permission_response\" // answer a permission_request\n\tMsgAskResponse        = \"ask_response\"        // answer an ask_request\n\tMsgCancel             = \"cancel\"              // interrupt the running turn\n\n\t// CLI → client (events)\n\tMsgInitialized       = \"initialized\"        // session ready; carries session id\n\tMsgAssistantDelta    = \"assistant_delta\"    // SEMANTIC assistant text — what the model said\n\tMsgDisplay           = \"display\"            // rendered terminal output (ANSI, tool chrome) — presentation only\n\tMsgToolCall          = \"tool_call\"          // a tool is running\n\tMsgToolResult        = \"tool_result\"        // a tool finished (summary)\n\tMsgPermissionRequest = \"permission_request\" // the turn is blocked awaiting approval\n\tMsgAskRequest        = \"ask_request\"        // the turn is blocked awaiting a user choice\n\tMsgSessionState      = \"session_state\"      // busy/idle + room/mode telemetry\n\tMsgUsage             = \"usage\"              // running token counts\n\tMsgResult            = \"result\"             // a turn finished\n\tMsgError             = \"error\"              // a turn errored\n)\n```\nMessage families. The direction comments are from the wrapper's point of view.\n\n```go\nconst CodeAccountLocked = \"account_locked\"\n```\nCodeAccountLocked is the gateway's machine-readable error code for an org locked by a negative balance (HTTP 402), mapped to ErrAccountLocked.\n\n```go\nconst CodeByokKeyFailed = \"byok_key_failed\"\n```\nCodeByokKeyFailed is the gateway's machine-readable error code for a turn killed by the user's own provider key (HTTP 422 body and the SSE error event), mapped to ErrByokKeyFailed.\n\n```go\nconst CodeContextOverflow = \"context_overflow\"\n```\nCodeContextOverflow is the gateway's machine-readable error code for a context-window overflow — carried on the HTTP 413 body and the SSE error event, mapped to ErrContextOverflow by the client.\n\n```go\nconst CodeInsufficientCredit = \"insufficient_credits\"\n```\nCodeInsufficientCredit is the gateway's machine-readable error code for an exhausted credit wallet — carried on the HTTP 402 body and the SSE error event, mapped to ErrInsufficientCredit by the client.\n\n```go\nconst CodeSubscriptionRequired = \"subscription_required\"\n```\nCodeSubscriptionRequired is the gateway's machine-readable error code for an org with no active subscription (HTTP 402), mapped to ErrSubscriptionRequired.\n\n```go\nconst StreamJSONVersion = \"1\"\n```\nStreamJSONVersion is the protocol version stamped on every Envelope. Bump on a breaking change to the message families or payloads.\n\n## Variables\n\n```go\nvar ErrAccountLocked = errors.New(\"your balance is negative — hosted models are paused; settle it at memcode.ai/account/billing (your own API keys keep working via /apikeys)\")\n```\nErrAccountLocked is returned when the org's balance went negative from a post-hoc debit overrun — the gateway returns 402 with code \"account\\_locked\". Everything is refused, BYOK included, until credits are added. Never retried.\n\n```go\nvar ErrByokKeyFailed = errors.New(\"your API key was rejected — fix or remove it with /apikeys\")\n```\nErrByokKeyFailed is returned when the turn died on the USER's own provider key (fail-the-turn doctrine: a failing BYOK key is never absorbed onto memcode's keys) — the gateway returns 422 with code \"byok\\_key\\_failed\". Never retried: the fix is /apikeys, not another attempt.\n\n```go\nvar ErrContextOverflow = errors.New(\"context window overflow\")\n```\nErrContextOverflow is returned when a turn's prompt exceeds the served context window on EVERY available backend (the gateway already absorbs vLLM overflow up to Anthropic; this fires only when even Anthropic's window is exceeded). The CLI runtime watches for it with errors.Is and compacts-then-retries the turn rather than surfacing a raw error — the reactive end of the routing ladder. On the wire it is signalled by HTTP 413 with code \"context\\_overflow\" and by an SSE error event carrying the same code.\n\n```go\nvar ErrInsufficientCredit = errors.New(\"credits exhausted — add your own API keys with /apikeys, or manage your plan and credits at memcode.ai/account/billing\")\n```\nErrInsufficientCredit is returned when the org's prepaid credit balance is exhausted — the gateway returns 402 with code \"insufficient\\_credits\". The CLI surfaces a friendly message and stops the turn (no retry: it's a user action, not a transient failure). Keys lead the message: they're the fix on every plan, while \"add credits\" doesn't exist on the BYOK-only Free plan.\n\n```go\nvar ErrStreamIncomplete = errors.New(\"gateway stream ended without a response\")\n```\nErrStreamIncomplete is returned when an SSE stream ends WITHOUT a terminal response event (a mid-stream read error, or the connection closing early — e.g. a Cloud Run request-timeout cutting off a long model call). It is a transient TRANSPORT failure, not a model/logic error: the failed call appended nothing, so the runtime can retry it from the same history. Watched with errors.Is and retried (bounded) rather than dying mid-turn with work half-done.\n\n```go\nvar ErrSubscriptionRequired = errors.New(\"subscription required — choose a plan at memcode.ai/account/billing\")\n```\nErrSubscriptionRequired is returned when the org has no active subscription — the gateway returns 402 with code \"subscription\\_required\". Subscription is mandatory for every LLM call, BYOK included (2026-07-26). Never retried: choosing a plan is a user action.\n\n```go\nvar ErrUnauthorized = errors.New(\"not signed in — your session expired or the token was revoked; run /login to reconnect\")\n```\nErrUnauthorized is returned when the gateway rejects the bearer token (HTTP 401): expired, revoked, or the retired legacy static token. It means the SESSION is signed out, not that the turn transiently failed — hosts watch with errors.Is, flip to their signed-out state, and prompt for /login instead of surfacing a raw HTTP error. Never retried.\n\n## Types\n\n```go\ntype AskRequestData struct {\n\tQuestion string   `json:\"question\"`\n\tOptions  []string `json:\"options,omitempty\"`\n}\n```\nAskRequestData / AskResponseData are the ask\\_user human-in-the-loop round-trip.\n\n```go\ntype AskResponseData struct {\n\tAnswer string `json:\"answer\"`\n}\n```\n\n```go\ntype AssistantDeltaData struct {\n\tText string `json:\"text\"`\n}\n```\nAssistantDeltaData is assistant-generated text: what the MODEL said, and nothing else (CLI → client).\n\nNever rendering. A consumer must not have to strip ANSI, tool chrome, routing lines or spinners to discover the assistant's words — that is what DisplayData is for. These were one channel until 2026-09-12, and the reviewer that consumed it silently received a styled terminal transcript in place of the model's answer whenever a turn ended on a tool call.\n\n```go\ntype Block struct {\n\tType string `json:\"type\"` // \"text\" | \"image\" | \"document\" | \"tool_use\" | \"tool_result\"\n\tText string `json:\"text,omitempty\"`\n\n\t// image / document\n\tSource *MediaSource `json:\"source,omitempty\"`\n\n\t// tool_use\n\tID    string          `json:\"id,omitempty\"`\n\tName  string          `json:\"name,omitempty\"`\n\tInput json.RawMessage `json:\"input,omitempty\"`\n\n\t// tool_result\n\tToolUseID string `json:\"tool_use_id,omitempty\"`\n\tContent   string `json:\"content,omitempty\"`\n\tIsError   bool   `json:\"is_error,omitempty\"`\n\n\t// ContentBlocks carries STRUCTURED content for a tool_result — one or more\n\t// content blocks (text and/or image) instead of the flat Content string. This\n\t// is the path for tool results that include vision (e.g. a browser screenshot\n\t// returned to the model as an image block). When non-empty, providers emit the\n\t// structured content union (Anthropic: text+image parts in the tool_result;\n\t// OpenAI: multi-part tool message). When empty, Content (flat string) is used\n\t// — backwards compatible with every text-only tool result.\n\tContentBlocks []Block `json:\"content_blocks,omitempty\"`\n\n\t// thinking (extended/adaptive reasoning). These MUST round-trip UNMODIFIED: the\n\t// API requires the assistant's thinking blocks to be passed back verbatim on the\n\t// next tool-use turn (it verifies them via Signature) or it rejects the request.\n\t// So we parse them off responses and re-send them; we just don't display them.\n\t// Data carries a redacted_thinking block's opaque payload, if one ever appears.\n\tThinking  string `json:\"thinking,omitempty\"`\n\tSignature string `json:\"signature,omitempty\"`\n\tData      string `json:\"data,omitempty\"`\n\n\t// prompt caching (set on the wire only, never on shared history — see the gateway)\n\tCacheControl *CacheControl `json:\"cache_control,omitempty\"`\n}\n```\nBlock is one content block in a message (text, image/document, a tool call, or a tool result, or a thinking block).\n\n```go\nfunc DocumentBlock(mediaType string, data []byte) Block\n```\nDocumentBlock builds a document block from raw file bytes (application/pdf is the interoperable case: Anthropic document source, OpenAI Responses input\\_file, Gemini inline blob). Models without native document input absorb the turn to a capable tier — the catalog's pdf flag gates that in the router.\n\n```go\nfunc ImageBlock(mediaType string, data []byte) Block\n```\nImageBlock builds a vision block from raw image bytes.\n\n```go\nfunc TextBlock(text string) Block\n```\nTextBlock builds a text block.\n\n```go\nfunc ToolResultBlocks(toolUseID string, blocks []Block, isError bool) Block\n```\nToolResultBlocks builds a tool\\_result block carrying structured content blocks (text and/or image) instead of a flat string. This is the path for tool results that include vision — e.g. a browser screenshot returned as an image block. When blocks is empty, falls back to an empty text result.\n\n```go\nfunc (b Block) MarshalJSON() ([]byte, error)\n```\nMarshalJSON serializes a Block for the wire. Thinking blocks MUST carry the \"thinking\" field even when its text is EMPTY: adaptive thinking frequently returns a block that is just a signature (the reasoning text omitted), and on the next tool-use turn Anthropic rejects a thinking block without the field — \"thinking.thinking: Field required\". The struct tag is \\`omitempty\\` (correct for every OTHER block type, which must NOT carry a stray empty \"thinking\"), so we special-case thinking / redacted\\_ thinking here and let the alias handle the rest with default tags.\n\n```go\ntype CacheControl struct {\n\tType string `json:\"type\"` // \"ephemeral\"\n\t// TTL is the cache lifetime: \"\" (default 5m) or \"1h\". The long TTL is used for the\n\t// STABLE doctrine+tools prefix, which is byte-identical across turns even as the\n\t// volatile facts (room/personality) change — so it survives interactive gaps \u003e5min.\n\tTTL string `json:\"ttl,omitempty\"`\n}\n```\nCacheControl marks a prompt-cache breakpoint. Everything from the start of the prompt up to and including the marked block is cached (5-min ephemeral TTL); later requests sharing that prefix read it instead of re-paying input tokens, and cache reads are excluded from the input-tokens/min rate limit.\n\n```go\ntype DisplayData struct {\n\tText string `json:\"text\"`\n}\n```\nDisplayData is rendered terminal output: ANSI styling, tool-call chrome, routing lines, banners (CLI → client).\n\nFor clients that want to SHOW what the terminal would show. Anything deciding what the model actually said wants AssistantDeltaData, or the final text on ResultData.\n\n```go\ntype Effort string\n```\nEffort is an abstract reasoning-depth setting. It exists so call sites express INTENT (\"this is a judgment call, think harder\") without hardcoding a provider shape that differs by model — e.g. Opus 5 rejects manual budget\\_tokens and requires adaptive thinking + an effort hint, while Opus 4.5 wants budget\\_tokens.\n\n```go\nconst (\n\tEffortOff    Effort = \"\"       // no extended thinking (helper calls; cheap paths)\n\tEffortLow    Effort = \"low\"    // light reasoning\n\tEffortMedium Effort = \"medium\" // memcode's default for real work\n\tEffortHigh   Effort = \"high\"   // deep reasoning\n\tEffortXhigh  Effort = \"xhigh\"  // deeper than high where the model offers it\n\tEffortMax    Effort = \"max\"    // the model's deepest setting\n\t// EffortDefault thinks but sends no effort, so the vendor's own default\n\t// applies. Distinct from EffortOff, which turns thinking off.\n\tEffortDefault Effort = \"default\"\n)\n```\n\n```go\nfunc (e Effort) Thinks() bool\n```\nThinks reports whether the effort asks for extended thinking at all.\n\n```go\ntype Envelope struct {\n\tVersion string          `json:\"version\"`\n\tType    string          `json:\"type\"`\n\tID      string          `json:\"id,omitempty\"`      // correlation id (e.g. a permission/ask request↔response)\n\tTurnID  string          `json:\"turn_id,omitempty\"` // the turn this message belongs to\n\tData    json.RawMessage `json:\"data,omitempty\"`\n}\n```\nEnvelope is the single wire frame. Data is a type-specific payload (below).\n\n```go\ntype ErrorData struct {\n\tMessage string `json:\"message\"`\n}\n```\nErrorData reports a turn-level error (CLI → client).\n\n```go\ntype InitializeData struct {\n\tCwd  string `json:\"cwd,omitempty\"`  // working directory / repo root\n\tMode string `json:\"mode,omitempty\"` // permission mode: ask | auto | allow-all\n\tPin  string `json:\"pin,omitempty\"`  // the session's model label\n}\n```\nInitializeData configures the session (client → CLI).\n\n```go\ntype InitializedData struct {\n\tSessionID string `json:\"session_id\"`\n\tProtocol  string `json:\"protocol\"` // echoes the version for handshake validation\n}\n```\nInitializedData announces a ready session (CLI → client).\n\n```go\ntype Intent struct {\n\t// Purpose is what this turn is FOR (ledger attribution + the utility split):\n\t// \"main_loop\" | \"explore\" | \"classify\" | \"compact\" | …\n\tPurpose string `json:\"purpose,omitempty\"`\n\n\t// Mode names the doctrine the turn runs under (\"chat\" | \"exec\" | \"plan\" | …).\n\tMode string `json:\"mode,omitempty\"`\n\n\t// Reasoning is the abstract reasoning depth the turn warrants (maps to\n\t// Effort). Effort is a genuinely separate axis from model choice and\n\t// survives the ladder: a tricky single-file bug can want deep thinking on\n\t// the same model an easy one uses.\n\tReasoning Effort `json:\"reasoning,omitempty\"`\n\n\t// Interactive is true when a live user is present (vs a batch/background\n\t// job) — available to the policy for latency-vs-cost trade-offs.\n\tInteractive bool `json:\"interactive,omitempty\"`\n\n\t// Pin is the session's model: a catalog LABEL (\"sol\", \"sonnet\", \"glm-5p2\",\n\t// …), never a raw provider id — raw ids stay at the serving edge. The pin\n\t// resolver settles it once at session start from the\n\t// session -\u003e workspace -\u003e user -\u003e default_model chain, so it is always set\n\t// for a real session; selection refuses rather than inventing one if it\n\t// isn't.\n\t//\n\t// Every real request serves this model. Internal plumbing\n\t// (classify/compact/shrinkwrap) rides the catalog's utility_model instead,\n\t// and capability gaps fail the turn visibly rather than rerouting it.\n\tPin string `json:\"pin,omitempty\"`\n}\n```\nIntent is the abstract selection contract: the session layer expresses WHAT a turn is, and the CLI's selection policy (internal/llm/resolve.go) maps it to a concrete catalog label. It is a client-internal type — it never rides a wire.\n\nIt used to carry the Automatic ladder's inputs (Difficulty, Risk, Vendor), and resolving them into a model was a per-turn decision. That is gone: there is exactly one model per session, the user's pin, and Intent now only says what KIND of turn this is so that internal plumbing can be told apart from the user's own work.\n\n```go\ntype MediaSource struct {\n\tType      string `json:\"type\"`       // \"base64\"\n\tMediaType string `json:\"media_type\"` // e.g. image/png, application/pdf\n\tData      string `json:\"data\"`\n}\n```\nMediaSource carries base64 image/document data for vision blocks.\n\n```go\ntype Message struct {\n\tRole   string  `json:\"role\"` // \"user\" | \"assistant\"\n\tBlocks []Block `json:\"content\"`\n}\n```\nMessage is one turn (a role plus its content blocks).\n\n```go\ntype PermissionRequestData struct {\n\tTitle    string `json:\"title\"`\n\tLabel    string `json:\"label,omitempty\"`\n\tDetail   string `json:\"detail,omitempty\"`\n\tCommand  string `json:\"command,omitempty\"`\n\tCwd      string `json:\"cwd,omitempty\"`\n\tRisk     string `json:\"risk,omitempty\"`\n\tEditable bool   `json:\"editable,omitempty\"`\n}\n```\nPermissionRequestData asks the client to approve an action (CLI → client). The client answers with a PermissionResponseData carrying the same Envelope.ID.\n\n```go\ntype PermissionResponseData struct {\n\tAllow     bool   `json:\"allow\"`\n\tCommand   string `json:\"command,omitempty\"`   // run this edited command instead\n\tReason    string `json:\"reason,omitempty\"`    // when !allow: fed back to the model\n\tInterrupt bool   `json:\"interrupt,omitempty\"` // stop the whole turn\n}\n```\n\n```go\ntype Request struct {\n\tModel    string    `json:\"model,omitempty\"` // resolved id at the serving edge; clients carry their choice in Pin\n\tSystem   string    `json:\"system,omitempty\"`\n\tMessages []Message `json:\"messages\"`\n\n\t// SystemVolatile is the per-turn-variable doctrine suffix (room/personality/\n\t// extra-mile/nudge + the turn-scoped extra) split OUT of System so it sits\n\t// OUTSIDE the cached prefix. The CLI's doctrine composer fills it (directly,\n\t// or via the transport's compose hook from Mode+Facts); adapters place it\n\t// cache-safely — Anthropic as a second, uncached system block, chat/\n\t// completions as a trailing system message, so the stable prefix still\n\t// auto-caches.\n\tSystemVolatile string    `json:\"system_volatile,omitempty\"`\n\tTools          []ToolDef `json:\"tools,omitempty\"`\n\tMaxTokens      int       `json:\"max_tokens,omitempty\"`\n\n\t// ToolChoice, when set to a tool name, FORCES the model to call that tool — the\n\t// reliable cross-provider path to structured output (Anthropic tool_choice / OpenAI\n\t// tool_choice). Used by the plan reviewer's verdict so the JSON comes back in a tool_use\n\t// block instead of best-effort prose-JSON. \"\" = the model chooses (the common case).\n\tToolChoice string `json:\"tool_choice,omitempty\"`\n\n\t// Mode + Facts select a doctrine prompt: the transport's compose hook\n\t// (cli/internal/doctrine) renders the mode's doctrine with these gathered\n\t// facts (root, platform, shell, overview/pack, room, nudge) into System/\n\t// SystemVolatile just before encoding. Mode \"\" = raw transport (no\n\t// composition; System passes through as-is).\n\tMode  string            `json:\"mode,omitempty\"`\n\tFacts map[string]string `json:\"facts,omitempty\"`\n\n\t// Effort is the ABSTRACT reasoning-depth knob. The provider maps it to whatever\n\t// thinking control the target model actually supports (adaptive+effort, manual\n\t// budget_tokens, or nothing). Zero value (EffortOff) means no extended thinking.\n\tEffort Effort `json:\"effort,omitempty\"`\n\n\t// Purpose + Session are transport-local labels (json:\"-\": never marshaled on\n\t// this type). Purpose labels the call for the client ledger and the lane\n\t// leak-log. Session rides the compat wire as the standard `user` field for\n\t// serving affinity (prefix-cache locality) and gateway telemetry. Stamped by\n\t// the CLI's llm.Runner; never set by hand.\n\tPurpose string `json:\"-\"`\n\tSession string `json:\"-\"`\n\n\t// Pin is the CLI-side carrier for the session's model choice: the resolved\n\t// catalog LABEL the transport puts in the wire `model` field. Under\n\t// all-policy-client-side the CLI's selection policy stamps it on EVERY\n\t// call (Automatic is client behavior); \"\" is only ever seen by test fakes.\n\tPin string `json:\"-\"`\n\n\t// BillingLane is the requested billing lane: \"\" / \"byok_preferred\" |\n\t// \"byok_only\" | \"credits\". Client-side it is set by policy (the consented\n\t// credits retry after a BYOK key failure) and rides the wire as the\n\t// memcode_billing extension; server-side the compat handler re-stamps it\n\t// from that extension and the gateway ENFORCES it — it never silently\n\t// reroutes between the user's keys and credits. NOT marshaled on this type.\n\tBillingLane string `json:\"-\"`\n\t// LaneBypass forces a turn OFF its family lane after an explicit,\n\t// consented exhaustion choice: \"gateway\" serves it on the hosted base.\n\t// Client-side routing state only — never serialized to any wire.\n\tLaneBypass string `json:\"-\"`\n}\n```\nRequest is a model completion request — the provider-neutral shape every adapter encodes from. Model selection is the CLI's job (llm/lane.go + llm/resolve.go): the Runner's policy resolves a catalog label into Pin, and the transport writes it into the wire \\`model\\` field. Server-side, Model carries the gateway's raw provider id after the label gate resolves it.\n\n```go\ntype Response struct {\n\tStopReason   string  `json:\"stop_reason\"` // \"end_turn\" | \"tool_use\" | \"max_tokens\"\n\tBlocks       []Block `json:\"blocks\"`      // assistant content (text and/or tool_use)\n\tInputTokens  int     `json:\"input_tokens\"`\n\tOutputTokens int     `json:\"output_tokens\"`\n\n\t// prompt-cache telemetry (tokens written to / read from the cache this call)\n\tCacheWriteTokens int `json:\"cache_write_tokens,omitempty\"`\n\tCacheReadTokens  int `json:\"cache_read_tokens,omitempty\"`\n\n\t// SearchCount is the number of native server-side web searches the serving\n\t// vendor billed on this call (Anthropic usage.server_tool_use.web_search_requests;\n\t// OpenAI/Grok Responses web_search_call output items). Searches carry a\n\t// PER-REQUEST fee on top of tokens — the gateway prices it via\n\t// common.SearchFeeUSD(Backend, SearchCount) when it emits cost_usd.\n\tSearchCount int `json:\"search_count,omitempty\"`\n\n\t// ToolOrigin records how a tool call was obtained: \"structured\" (the model's native\n\t// tool_calls — the intended path) or \"salvaged_*\" (the gateway recovered it from\n\t// text a brittle parser missed). Surfaced so salvage stays OBSERVABLE, never silently\n\t// the main contract.\n\tToolOrigin string `json:\"tool_origin,omitempty\"`\n\n\t// Serving telemetry — the ledger's ground truth for WHO served this call.\n\t// Model is the model that actually ran (a fallback-chain hop can differ from\n\t// the requested label). Backend is the serving vendor: \"cheap\" (the hosted\n\t// cheap lane, vendor-neutral — the inference vendor never rides the wire) |\n\t// \"anthropic\" | \"openai\" | \"gemini\" | \"grok\" | \"unknown\" (label missing from\n\t// the client catalog); \"vllm\" is the legacy cheap-lane tag an un-redeployed\n\t// gateway sends (clients accept both). FallbackReason names why the served\n\t// model differs from the primary choice: a client-side absorb (\"vision\" |\n\t// \"pdf\" | \"window\") or a recovery hop (\"model_error: …\").\n\tModel          string `json:\"model,omitempty\"`\n\tBackend        string `json:\"backend,omitempty\"`\n\tFallbackReason string `json:\"fallback_reason,omitempty\"`\n\n\t// RequestedModel is the label the selection policy chose BEFORE any absorb/\n\t// fallback — the basis for the ledger's counterfactual \"what the primary\n\t// would have cost\". The CLI's finalize stamps it (the gateway echoes the\n\t// requested id on hosted turns); it equals Model when nothing intervened.\n\tRequestedModel string `json:\"requested_model,omitempty\"`\n\n\t// ContextWindow is the serving backend's real input window in tokens, when\n\t// the backend reports one (0 when the client's catalog already knows it).\n\tContextWindow int `json:\"context_window,omitempty\"`\n\n\t// InputBudget is the serving lane's usable INPUT budget (window − output reserve −\n\t// safety margin) — the size a prompt must fit under to land on THIS lane. The CLI\n\t// learns the cheap lane's budget from this and aims compaction at it. 0 when not\n\t// lane-served.\n\tInputBudget int `json:\"input_budget,omitempty\"`\n\n\t// Pool is the cheap lane's served-model short label (\"glm-5p2\" | \"kimi-k3\"),\n\t// the CLI's ⇄ ServedBy tag for lane serves. EstimatedPromptTokens is the\n\t// server's pre-call size estimate (stamped per serve so the usage log's\n\t// EstimateRatio can calibrate the estimator against real InputTokens).\n\tPool                  string `json:\"pool,omitempty\"`\n\tEstimatedPromptTokens int    `json:\"estimated_prompt_tokens,omitempty\"`\n\n\t// BYOK telemetry. BYOK (whether this call ran on the user's OWN provider\n\t// key) rides the wire — it is the key owner's own information, shown by the\n\t// CLI footer strictly per-turn. BYOKVendor stays SERVER-INTERNAL (json:\"-\"):\n\t// the cheap lane's inference vendor never leaves the server (SanitizeResponse\n\t// zeroes it defensively). The gateway reads both for metering (usage line +\n\t// zero-debit policy) before sanitizing.\n\tBYOK       bool   `json:\"byok,omitempty\"`\n\tBYOKVendor string `json:\"-\"`\n}\n```\nResponse is a model completion result, plus the serving telemetry the footer/ ledger read. On the hosted backend the gateway stamps the serving facts (via the memcode response extension); in direct-endpoint mode the CLI's recovery policy stamps them itself (finalize) — same fields, one reader.\n\n```go\nfunc (r Response) CacheUtilization() float64\n```\nCacheUtilization returns the percentage (0-100) of TotalInput served from cache.\n\n```go\nfunc (r Response) Text() string\n```\nText returns the concatenated text blocks of a response.\n\n```go\nfunc (r Response) ToolUses() []Block\n```\nToolUses returns the tool\\_use blocks of a response.\n\n```go\nfunc (r Response) TotalInput() int\n```\nTotalInput returns the full prompt size seen by the model: uncached input plus cache reads and cache writes (disjoint across all providers).\n\n```go\ntype ResultData struct {\n\tText      string `json:\"text,omitempty\"`\n\tCompleted bool   `json:\"completed\"`\n\t// Spoke reports whether the model produced any text at all this turn. It\n\t// distinguishes \"finished with nothing to say\" from \"finished and the text\n\t// went missing\", which an empty string alone cannot.\n\tSpoke bool `json:\"spoke\"`\n}\n```\nResultData ends a turn (CLI → client).\n\nText is the turn's final SEMANTIC assistant text, derived from what the model said and never from rendered output. It is legitimately empty when a turn ended without the model saying anything — every iteration was a tool call, or it hit its cap. An empty Text means exactly that, and a consumer must treat it as \"no answer\" rather than falling back to whatever else it captured.\n\n```go\ntype SessionStateData struct {\n\tBusy bool   `json:\"busy\"`\n\tMode string `json:\"mode,omitempty\"` // room mode (normal/repair/replan), when known\n}\n```\nSessionStateData reports busy/idle + light room telemetry (CLI → client).\n\n```go\ntype StreamHandler struct {\n\tText func(delta string)\n\t// Reasoning receives the model's reasoning SUMMARY text as it streams,\n\t// where the vendor offers one (Claude summarized thinking, OpenAI reasoning\n\t// summaries, Gemini thought summaries, reasoning_content on OpenAI-compatible\n\t// lanes). Display only: it never enters the transcript or history.\n\tReasoning func(delta string)\n\tUsage     func(input, output int)\n}\n```\nStreamHandler receives incremental events during a streamed completion. Both callbacks are optional. Text fires for each chunk of assistant text as it arrives; Usage fires when the API reports token counts (input at the start, authoritative output near the end — NOT per delta, so a live \"tokens so far\" display must estimate from streamed text between Usage calls and reconcile when Usage fires).\n\nThis is a data type (a struct of callbacks), part of the wire contract's shape. The capability INTERFACES (ModelProvider, Streamer, WebSearcher, WebFetcher, Advisor) are intentionally NOT declared here — each consumer declares the structural interface it needs, referencing these common types; an implementation merely satisfies it.\n\n```go\ntype ToolCallData struct {\n\tName   string `json:\"name\"`\n\tTarget string `json:\"target,omitempty\"`\n\tDetail string `json:\"detail,omitempty\"`\n}\n```\nToolCallData / ToolResultData report tool activity (CLI → client).\n\n```go\ntype ToolDef struct {\n\tName        string         `json:\"name\"`\n\tDescription string         `json:\"description\"`\n\tInputSchema map[string]any `json:\"input_schema\"`\n\n\t// prompt caching — set on the LAST tool only, on the wire (see the gateway)\n\tCacheControl *CacheControl `json:\"cache_control,omitempty\"`\n}\n```\nToolDef describes a tool the model may call.\n\n```go\ntype ToolResultData struct {\n\tName   string `json:\"name\"`\n\tStatus string `json:\"status,omitempty\"` // \"ok\" | \"failed\" | …\n}\n```\n\n```go\ntype UsageData struct {\n\tOutputTokens int `json:\"output_tokens\"`\n}\n```\nUsageData reports running token counts (CLI → client).\n\n```go\ntype UserTurnData struct {\n\tText string `json:\"text\"`\n}\n```\nUserTurnData submits a prompt (client → CLI).\n\n","path":"github.com/memcode-ai/memcode/internal/wire","name":"wire","synopsis":"Package common is the memcode PROTOCOL contract: the wire types shared by the CLI (the client) and the api gateway (the server), the sdk/agent ↔ CLI stream-json envelope, the abstract Intent, shared error sentinels, and the model/pricing metadata both ledgers price against.","isRedistributable":true}
