package protocol import ( "encoding/json" "fmt" ) // Chat requests and responses are brokered by the Pipelines server (route B in // the OpenCode chat research): the phone keeps talking only to /connect and the // server holds the OpenCode credentials, translating each type below to the // native service. Like every other exchange, a client sends // Message{Type: ChatXxx, ID: } and the server echoes the ID on the // response. // // The payloads mirror the verified OpenCode shapes: an assistant turn is a list // of parts (text | reasoning | tool), and a tool part carries name, state.status, // state.input, state.content, state.metadata, state.error and epoch-millisecond // timings. Timings stay integer milliseconds rather than RFC3339 strings so the // brokered values match the service exactly; all list fields are optional so // older peers ignore them. const ( ChatSessions = "chat_sessions" ChatCreate = "chat_create" // ChatAdopt records a session that already exists on the configured OpenCode // endpoint in the operator-session registry, using the endpoint's own // directory and title, so it appears in chat_sessions and can be continued. ChatAdopt = "chat_adopt" ChatPrompt = "chat_prompt" ChatMessages = "chat_messages" ChatInterrupt = "chat_interrupt" ChatReply = "chat_reply" // ChatClose finishes an operator session and records it as closed on the // server: any in-flight turn is interrupted through the existing interrupt, // nothing is deleted (the session, its transcript and its history survive) and // the closed state is shared by every client because it lives in the // operator-session registry. ChatReopen clears the closed state again, so a // finished chat can be resumed. Both take a ChatQuery (the session id) and // echo the updated session like chat_create/chat_adopt. Neither ever touches // the pipeline-owned run sessions, and a closed session stays watchable: close // only records the finished state, it never detaches a client. ChatClose = "chat_close" ChatReopen = "chat_reopen" // ChatRename records the operator's shared chat title on the server. Unlike // a local override, every browser and device then lists the same name. ChatRename = "chat_rename" // ChatNewSession is the composer's /new: the same chat (list row, title, // colour, star, directory, model and mode) continues on a fresh native // harness session with an empty context, as /new or /clear do inside the // harness's own TUI. The body is ChatNewSessionRequest. The registry row is // re-keyed to the new native id; the reply and the chat_session_changed push // carry the new row with PreviousID naming the id it replaced, so every // client swaps the row in place and an open conversation follows it. The // previous native session is untouched and stays resumable in a terminal. ChatNewSession = "chat_new_session" // ChatExport returns one operator chat as a file the client saves or // shares. The body is ChatExportRequest and the reply carries // ChatExportFile: a Markdown or JSON transcript built from the same history // chat_messages serves, or the harness's own session file where one exists // (ChatSession.NativeExport). ChatExport = "chat_export" // ChatBackends lists the installed chat harnesses the server can create a // session on. The reply is a bounded array of backend names. ChatBackends = "chat_backends" // ChatModels lists the models the chat's harness can switch to; its request // body is ChatQuery (the session id). ChatModels = "chat_models" // ChatModelSelect switches one session's model for subsequent turns. ChatModelSelect = "chat_model" // ChatModes lists the permission modes the chat's harness offers (Claude // Code's permission modes, Codex approval/sandbox presets, OpenCode agents); // its request body is ChatQuery and the reply also carries the current mode. ChatModes = "chat_modes" // ChatModeSelect switches one session's mode. The choice is stored with the // operator session and applied now and before every later turn. ChatModeSelect = "chat_mode" // ChatStar records the operator's star on the server, so every browser and // device shows the same starred group. It takes a ChatQuery with SessionID // and Starred, and echoes the updated session like close/reopen. ChatStar = "chat_star" // ChatColor records the operator's shared highlight colour for one chat. It // takes a ChatQuery with SessionID and Color (a ChatColors name; null or "" // clears it) and echoes the updated session like chat_star. ChatColor = "chat_color" // ChatSessionChanged is pushed to every other open connection when a chat's // shared list metadata (colour, star, title) changes, carrying the updated // registry row in ChatSession, so each device's list updates live. ChatSessionChanged = "chat_session_changed" // ChatActivityChanged is pushed to every open connection (not only the // session's room subscribers) when a chat's live activity changes: its turn // starts or ends, or its count of running background tasks changes. The // body is ChatActivity. It is sent on those transitions only, never per // output chunk; a client applies a push only when its Seq is newer than the // activity it already holds for that session. ChatActivityChanged = "chat_activity" // ChatSubscribe attaches a connection to one session's shared live stream so // it receives every frame any client's turn produces (its own and the other // devices'), not only the frames of a turn it prompted itself. Any number of // clients may watch one session; the session is never read-only. The request // body is a ChatQuery naming the session and the response echoes the request // id once the subscription is attached. ChatSubscribe = "chat_subscribe" // ChatQueue is pushed to every client watching a session whenever its // server-side prompt queue changes (a prompt queued, delivered, removed or // refused by the harness). The chat_subscribe reply carries the same body so // a reloaded client draws the queued prompts the server still holds. ChatQueue = "chat_queue" // ChatUnqueue removes one prompt the server still holds in a session's // queue, named by its operation id. Its body is ChatUnqueueRequest and the // reply carries the updated queue in ChatQueue. A prompt already delivered // to the harness is no longer removable and is refused. ChatUnqueue = "chat_unqueue" // ChatDirectories is the request/response type for the operator's directory // choices: the home directory plus the directories of previous operator // sessions, most recently used first, deduplicated and bounded. It is a // dedicated request (not a field on chat_sessions) so the create dialog can // load the choices without first listing sessions and chat_sessions stays a // pure, fail-closed operator-session list. ChatDirectories = "chat_directories" // ChatShells lists current, verified shells belonging to one operator chat // session. ChatShellOutput reads a bounded page from one such shell. ChatShells = "chat_shells" ChatShellOutput = "chat_shell_output" // ChatAttachmentImage reads back one image the operator attached earlier, // so a transcript can draw it after a reload. The request body is // ChatAttachmentImageRequest (the history part's file:// URI) and the reply // carries ChatAttachmentImageContent. Only regular image files inside the // server's private chat attachment store are served. ChatAttachmentImage = "chat_attachment_image" // ChatAutomations reads provider-owned scheduled work for one operator chat. // It is deliberately read-only; providers that cannot authoritatively expose // this information return an unavailable status instead of an empty count. ChatAutomations = "chat_automations" // ChatEvent and ChatPermission are the server-pushed frames; they are the // only types the server sends without a matching request. ChatEvent = "chat_event" // ChatEventForm carries an OpenCode form (the agent's question tool uses a // form with kind=question). It is a ChatEvent kind, not a separate request: // the same frame stream that carries text and tools carries the question. ChatEventForm = "form" // ChatAnswer is the client's answer to a ChatEventForm. Answers is keyed by // field key and mirrors OpenCode's form.reply answer object. ChatAnswer = "chat_answer" // ChatPermission carries one pending OpenCode approval request the phone // answers with chat_reply. ChatPermission = "chat_permission" ) const ( ChatAutomationSupported = "supported" ChatAutomationUnavailable = "unavailable" ) // ChatAutomationInfo is the bounded, per-session scheduled-work snapshot. A // nil ActiveCount means the provider could not authoritatively report a count; // zero is reserved for a supported provider with no active schedules. type ChatAutomationInfo struct { SessionID string `json:"session_id"` Provider string `json:"provider"` Status string `json:"status"` ActiveCount *int `json:"active_count,omitempty"` // ObservedAtMS is when the provider reported its last native snapshot. It // is not the time this read was performed and therefore never implies a // live query. ObservedAtMS int64 `json:"observed_at_ms,omitempty"` Reason string `json:"reason,omitempty"` } // Content part types carried by ChatPart.Type and ChatEvent.Kind. const ( ChatPartText = "text" ChatPartReasoning = "reasoning" ChatPartTool = "tool" ChatPartFile = "file" ) // ChatEvent.Kind values pushed on the chat_event stream. Step and usage carry // no ChatPart; they report turn progress and the turn's totals. User carries the // text of a prompt another client sent, so a transcript can show it live; it is // never sent back to the client that sent the prompt. const ( ChatEventText = ChatPartText ChatEventReasoning = ChatPartReasoning ChatEventTool = ChatPartTool ChatEventStep = "step" ChatEventResync = "resync" ChatEventUsage = "usage" ChatEventUser = "user" ChatEventCompaction = "compaction" // ChatEventShell reports the lifecycle of one shell the agent started. It // carries no ChatPart and no message id: a shell can outlive the tool call // that started it, so it is a frame of its own rather than a tool part. ChatEventShell = "shell" ) // ChatShell.Status values, mirroring the OpenCode shell events. A running shell // is one whose command has started and not yet exited; exited is final. const ( ChatShellRunning = "running" ChatShellExited = "exited" ChatShellOutputLimit = 64 << 10 ChatShellOutputMaxCursor = int64(1 << 62) ) // ChatStep.Status values, mirroring the OpenCode session.step events. const ( ChatStepStarted = "started" ChatStepStreamed = "streamed" ChatStepEnded = "ended" ) // ChatToolState.Status values, mirroring OpenCode's ToolState union. const ( ChatToolStreaming = "streaming" ChatToolRunning = "running" ChatToolCompleted = "completed" ChatToolError = "error" ) // ChatReplyRequest.Decision values, mirroring the OpenCode permission reply body. const ( ChatDecisionOnce = "once" ChatDecisionAlways = "always" ChatDecisionReject = "reject" ) // ChatSession.Tag values. The stored tag vocabulary is exactly // ChatSessionTagOperator; the display label the app shows is // ChatSessionTagOperatorDisplay, derived from the wire tag rather than carried // as a second field so there is no duplicate mapping to drift. const ( ChatSessionTagOperator = "operator" ChatSessionTagOperatorDisplay = "Operator" ) // ChatMessage.Role values. const ( ChatRoleUser = "user" ChatRoleAssistant = "assistant" ) // ChatMessage.Kind (and ChatEventFrame.MessageKind) values. A message with a // kind is content the harness delivered into the session, never a turn the // operator sent: it carries role assistant so an older client that ignores the // kind still draws it on the agent's side, never as the operator's bubble. // // ChatMessageKindAgentReport is a report another agent (a delegated subagent or // a peer session) delivered; its one text part is the report, and the part's // Name carries the sender's label when the harness recorded one. // ChatMessageKindNotice is a one-line harness notice, such as a background task // finishing; its one text part is the line. const ( ChatMessageKindAgentReport = "agent_report" ChatMessageKindNotice = "notice" ) // ChatModel is one model the current chat harness can switch to. ID is the // provider's model id, Provider its provider id, Name the harness's display name. type ChatModel struct { ID string `json:"id"` Provider string `json:"provider"` Name string `json:"name,omitempty"` // Efforts are the thinking levels this model accepts and DefaultEffort the // one its harness uses when none is chosen; both empty when it has none. Efforts []ChatEffort `json:"efforts,omitempty"` DefaultEffort string `json:"default_effort,omitempty"` // Resolved is the concrete model an alias names (Claude Code's "opus"), // so a model a reply reports can be matched to its entry. Never sent. Resolved string `json:"-"` } // ChatMode is one permission mode a chat harness offers. type ChatMode struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description,omitempty"` } // ChatModeRequest switches one session's mode; the reply echoes the stored mode. type ChatModeRequest struct { SessionID string `json:"session_id"` Mode string `json:"mode"` } // ChatModelRequest switches the model for one session's subsequent turns. type ChatModelRequest struct { // Selection is reply-only: next_turn means a durable local override was saved. Selection string `json:"selection,omitempty"` SessionID string `json:"session_id"` Provider string `json:"provider"` Model string `json:"model"` } // ChatSession is one createable/listed OpenCode session, flattened for the // phone: the nested location.directory and time{created,updated} fields are // lifted to Directory, CreatedAt and UpdatedAt. type ChatSession struct { ID string `json:"id"` // ModelSelection == next_turn denotes a durable Pipelines override, not an // acknowledgement that a remote thread's current configuration changed. ModelSelection string `json:"model_selection,omitempty"` // Mode is the stored permission mode (a ChatMode id); empty is the // harness's own default. Mode string `json:"mode,omitempty"` // ModeName is Mode's display name. With no stored mode both name the // harness default, so a client can show the mode without a chat_modes read. ModeName string `json:"mode_name,omitempty"` // Effort is the stored thinking level ("" for the harness default), and // Efforts/DefaultEffort the levels the row's model accepts, when the // server knows them without starting the harness. No Efforts: no control. Effort string `json:"effort,omitempty"` Efforts []ChatEffort `json:"efforts,omitempty"` DefaultEffort string `json:"default_effort,omitempty"` // InstructionStatus is the observed create-time preload outcome: applied, // unsupported, failed, or not_requested. Ordinary list rows omit it. InstructionStatus string `json:"instruction_status,omitempty"` InstructionError string `json:"instruction_error,omitempty"` // Backend names the harness that owns this session: opencode, codex or // claude. Empty on older peers and for legacy OpenCode rows. Backend string `json:"backend,omitempty"` Title string `json:"title,omitempty"` Agent string `json:"agent,omitempty"` Model string `json:"model,omitempty"` ModelProvider string `json:"model_provider,omitempty"` Directory string `json:"directory,omitempty"` ParentID string `json:"parent_id,omitempty"` // Tag marks the session kind. The only stored value is "operator" (a chat // the person created); pipeline stage sessions are never tagged and are never // listed by chat_sessions. Additive/omitempty so older peers ignore it. Tag string `json:"tag,omitempty"` CreatedAt int64 `json:"created_at,omitempty"` UpdatedAt int64 `json:"updated_at,omitempty"` // Busy is retained for wire compatibility only: it is never set by this // server. A session is never read-only, any number of clients may watch and // write it, and only a turn is serialised (a waiting prompt is acknowledged // as queued on its own client instead of marking the session Busy). Older // peers still parse the field; newer ones ignore it. Busy bool `json:"busy,omitempty"` // Closed records that the operator finished with this session: the server // keeps the session, its transcript and its history, but the closed state is // shared by every client (it lives in the operator-session registry, not on // one device). ClosedAt is the epoch-millisecond close time, 0 while open. // Additive/omitempty so older peers ignore them. Closed bool `json:"closed,omitempty"` ClosedAt int64 `json:"closed_at,omitempty"` // Starred is the operator's shared star, stored in the operator-session // registry so every client sees the same Starred group. StarredAt is the // epoch-millisecond time it was set, 0 while unstarred. Starred bool `json:"starred,omitempty"` StarredAt int64 `json:"starred_at,omitempty"` // ResumeCommand is the shell command that continues this session in a // terminal on the server machine with the harness's own CLI, run in the // session's directory. ID is the harness's native session id (Claude Code // session UUID, Codex thread id, OpenCode ses_ id). Empty when the harness // has no verified resume option. ResumeCommand string `json:"resume_command,omitempty"` // NativeExport says chat_export with format "native" can return the // harness's own session file (today: Claude Code's JSONL transcript). NativeExport bool `json:"native_export,omitempty"` // Color is the operator's shared highlight, a ChatColors name; omitted when // none is set. Clients map the name to their own theme-tuned shade. Color string `json:"color,omitempty"` // PreviousID is set only on a chat_new_session reply and its // chat_session_changed push: the native session id this chat ran on until // the operator started a fresh session. Clients replace the row with that // id by this one; it is never part of a listed row. PreviousID string `json:"previous_id,omitempty"` // Activity is the server's live view of the session. A server that tracks // it sets it on every chat_sessions row (its presence, even as an empty // object, tells a client the server also pushes chat_activity). Older // servers omit it. Activity *ChatActivity `json:"activity,omitempty"` } // ChatActivity is one session's live activity as the server observes it: a // turn in flight, and how many background tasks (shells, background commands, // subagents) the harness reports still running. It rides on chat_sessions rows // and is pushed as chat_activity. Seq orders one session's snapshots across // the list reply and the pushes (a later snapshot has a larger Seq, also // across a server restart); a client keeps the snapshot with the largest Seq. // Background tasks are counted only while the server observes the session's // stream, so an unobserved session reports none rather than a stale count. type ChatActivity struct { SessionID string `json:"session_id,omitempty"` TurnRunning bool `json:"turn_running,omitempty"` BackgroundTasks int `json:"background_tasks,omitempty"` Seq int64 `json:"seq,omitempty"` } // Chat export formats accepted by chat_export. const ( ChatExportMarkdown = "markdown" ChatExportJSON = "json" ChatExportNative = "native" ) // ChatExportRequest is the chat_export body. type ChatExportRequest struct { SessionID string `json:"session_id"` Format string `json:"format"` } // ChatExportFile is the chat_export reply: one named, typed text file. Messages // counts the transcript messages included (0 for a native file). Truncated says // older history was left out to keep the file within the server's bound. type ChatExportFile struct { SessionID string `json:"session_id"` Format string `json:"format"` Name string `json:"name"` Mime string `json:"mime"` Content string `json:"content"` Messages int `json:"messages,omitempty"` Truncated bool `json:"truncated,omitempty"` } // ChatColors is the fixed palette of chat highlight names, in picker order. var ChatColors = []string{"red", "orange", "amber", "green", "teal", "blue", "purple", "pink"} // ValidChatColor reports whether name is one of ChatColors. func ValidChatColor(name string) bool { for _, color := range ChatColors { if color == name { return true } } return false } // ChatCloseResult reports the outcome of a chat_close: the session id, the // epoch-millisecond time the closed state was recorded, and whether an // in-flight turn was interrupted to stop it. It is the record that a running // turn was stopped, so a stream is never left running into nothing. type ChatCloseResult struct { SessionID string `json:"session_id"` ClosedAt int64 `json:"closed_at"` Interrupted bool `json:"interrupted,omitempty"` } // ChatCreateRequest is the chat_create request body: a title and an optional // working directory (the server's configured location when empty). OperationID // is the durable idempotency key for this create intent; it is deliberately // separate from Message.ID, which remains connection-local response // correlation. Clients retrying a create across reconnects must retain it. The // response carries the created session in Message.ChatSession. type ChatCreateRequest struct { Title string `json:"title,omitempty"` Directory string `json:"directory,omitempty"` // Backend selects the chat harness for a new session. Empty means opencode, // preserving older clients and the default. Backend string `json:"backend,omitempty"` OperationID string `json:"operation_id,omitempty"` // Instructions preloads the session's durable behavior instruction, when the // harness supports session instruction entries (OpenCode does). The reply's // instruction_status explicitly reports applied, unsupported or failed. Instructions string `json:"instructions,omitempty"` // Ephemeral creates a chat for automated verification: the session is created, // bootstrapped and usable exactly like a normal one, but no operator-registry // row is written, so it can never appear in chat_sessions. It exists because a // verification client drives the real UI and would otherwise leave a permanent // "New chat" in the operator's list for every run. The flag is client-supplied // and only ever *removes* a chat from the shared list, so a buggy or hostile // client can hide its own chat but cannot reveal or alter another one. Ephemeral bool `json:"ephemeral,omitempty"` } // ChatAdoptRequest is the chat_adopt request body: the id of a session that // already exists on the configured endpoint. The server records it in the // operator-session registry with the endpoint's own directory and title and // echoes the adopted session (and the registry list row) like chat_create. type ChatAdoptRequest struct { SessionID string `json:"session_id"` // Backend names the harness that owns the session (opencode, claude, // codex). Blank tries each available harness in that order. Backend string `json:"backend,omitempty"` // Title names the adopted chat when its harness records none. Title string `json:"title,omitempty"` } // ChatQuery is the session-scoped request body for chat_messages and // chat_interrupt, which name their target session through it; Limit caps the // returned history (server default when zero). type ChatQuery struct { SessionID string `json:"session_id"` // Starred is set by chat_star; nil means the command did not name a state. Starred *bool `json:"starred,omitempty"` // Color is set by chat_color: a ChatColors name, or nil/"" to clear. Color *string `json:"color,omitempty"` Limit int `json:"limit,omitempty"` // Cursor is the opaque continuation returned by OpenCode's descending // message listing. It is deliberately not interpreted by the broker. Cursor string `json:"cursor,omitempty"` } // ChatHistoryPage describes the bounded slice returned by chat_messages. The // newest page has an empty Cursor request; NextCursor remains opaque and is // supplied unchanged to fetch older turns. type ChatHistoryPage struct { Messages []ChatMessage `json:"messages"` NextCursor string `json:"next_cursor,omitempty"` HasMore bool `json:"has_more,omitempty"` } // ChatPromptRequest is the chat_prompt request body: the text to send, with an // optional model/agent override and attached file URIs. The matching response is // the inbox envelope, which the server folds into a ChatMessage. Client is the // sending device's human-readable label so every other client can attribute the // message; the server sanitises it and falls back to a generic label when it is // blank. type ChatPromptRequest struct { SessionID string `json:"session_id"` Text string `json:"text"` Model string `json:"model,omitempty"` Agent string `json:"agent,omitempty"` Files []string `json:"files,omitempty"` Client string `json:"client,omitempty"` OperationID string `json:"operation_id,omitempty"` // NativeMessageID is the caller-supplied OpenCode message identity. It is // sent with the prompt so history can be reconciled without guessing from // text, time, order or page boundaries. NativeMessageID string `json:"native_message_id,omitempty"` // Attachments carries the bytes of files picked or pasted in the browser. // Files are local to the browser, so a reference string alone is not enough // for a server on another machine; Data is standard base64 and the server // writes it to a private temporary file before prompting the agent. Attachments []ChatAttachment `json:"attachments,omitempty"` } // ChatQueuedPrompt is one prompt the server holds for a session until its // harness finishes the turn in flight. It is durable: it survives the sending // client disconnecting and a server restart, and is delivered in order. type ChatQueuedPrompt struct { OperationID string `json:"operation_id"` MessageID string `json:"message_id"` NativeMessageID string `json:"native_message_id,omitempty"` Text string `json:"text"` Client string `json:"client,omitempty"` Attachments []ChatPart `json:"attachments,omitempty"` QueuedAt int64 `json:"queued_at,omitempty"` } // ChatQueueFrame is a session's current server-side prompt queue, in delivery // order. Delivered, Removed or Failed name the operation whose change produced // the frame; Error carries the harness refusal for Failed. type ChatQueueFrame struct { SessionID string `json:"session_id"` Prompts []ChatQueuedPrompt `json:"prompts"` Delivered string `json:"delivered,omitempty"` Removed string `json:"removed,omitempty"` Failed string `json:"failed,omitempty"` Error string `json:"error,omitempty"` } // ChatUnqueueRequest names one queued prompt to remove. type ChatUnqueueRequest struct { SessionID string `json:"session_id"` OperationID string `json:"operation_id"` } // ChatAttachment is one browser attachment carried by a chat prompt. Data is // standard base64 (no data: prefix); Name is a display name and Mime is the // browser's content type. The server derives the on-disk name and never trusts // either for path construction. type ChatAttachment struct { Name string `json:"name"` Mime string `json:"mime,omitempty"` Data string `json:"data"` // Upload names a file already sent through POST /chat-uploads; Data is // then empty. Large files take this route instead of the websocket. Upload string `json:"upload,omitempty"` } // ChatAttachmentImageRequest names one stored attachment by the file:// URI a // history file part carries. type ChatAttachmentImageRequest struct { URI string `json:"uri"` } // ChatAttachmentImageContent is the chat_attachment_image reply: the file's // bytes as standard base64 and the image MIME type sniffed from those bytes. type ChatAttachmentImageContent struct { URI string `json:"uri"` Mime string `json:"mime"` Size int64 `json:"size"` Data string `json:"data"` } // ChatMessage is one stored turn returned by chat_messages. A user turn is a // single text part; an assistant turn holds the text, reasoning and tool parts // the phone renders. Parts corresponds to the OpenCode content array. type ChatMessage struct { ID string `json:"id"` SessionID string `json:"session_id"` Role string `json:"role"` Model string `json:"model,omitempty"` Agent string `json:"agent,omitempty"` CreatedAt int64 `json:"created_at,omitempty"` // Client is the sending device's label on a user turn the server echoed, so a // resumed transcript still says who sent the message. It is empty on an // assistant turn. Client string `json:"client,omitempty"` OperationID string `json:"operation_id,omitempty"` // Kind is empty for an ordinary user or assistant turn, or one of the // ChatMessageKind values for content the harness injected. Kind string `json:"kind,omitempty"` Parts []ChatPart `json:"parts"` } // ChatDeltaPartID is the stable part id an incremental text or reasoning delta // stream addresses. OpenCode numbers one message's text and reasoning parts // independently from 0, so the kind is part of the id: for a single message its // first text delta and its first reasoning delta are distinct ids and a delta can // never be appended into the other kind's part. The derivation is deterministic, // so a reconnect or a resume re-addresses the same part, and it is mirrored in // the client's ChatProtocol.deltaPartId (data/protocol/Chat.kt). func ChatDeltaPartID(messageID, kind string, ordinal int) string { return fmt.Sprintf("%s#%s#%d", messageID, kind, ordinal) } // ChatPart is one element of a ChatMessage. Type selects the meaning: text and // reasoning use Text and ID, tool uses ID, Name, Executed, State and Time. A text // or reasoning part's ID is ChatDeltaPartID(message id, kind, ordinal), so the two // kinds never share an id within a message. type ChatPart struct { Type string `json:"type"` ID string `json:"id,omitempty"` Text string `json:"text,omitempty"` Name string `json:"name,omitempty"` URI string `json:"uri,omitempty"` Mime string `json:"mime,omitempty"` Executed bool `json:"executed,omitempty"` State *ChatToolState `json:"state,omitempty"` Time *ChatTime `json:"time,omitempty"` } // ChatToolState is the lifecycle of a tool call. Input is a raw JSON value: a // partial-JSON string while streaming, an object once running or completed. // OpenCode spreads one call across several frames (name in input.started, the // arguments in input.ended's text or called's input, then progress/success // carrying neither), so Input is absent on the frames that do not carry it and // every consumer retains the value it already learned instead of blanking it. // Content is the tool's textual/file result, Metadata its provider stats, // Error the structured failure for status "error". type ChatToolState struct { Status string `json:"status"` Input json.RawMessage `json:"input,omitempty"` Content []ChatToolContent `json:"content,omitempty"` Metadata map[string]any `json:"metadata,omitempty"` Error *ChatError `json:"error,omitempty"` // Truncated says Content is a bounded preview of a larger stored result. // The turn remains usable; callers must not present the preview as complete. Truncated bool `json:"truncated,omitempty"` } // ChatToolContent is one returned tool result: either text or a file/uri pair // (so a tool can return an image the phone renders). type ChatToolContent struct { Type string `json:"type"` Text string `json:"text,omitempty"` URI string `json:"uri,omitempty"` Mime string `json:"mime,omitempty"` Name string `json:"name,omitempty"` } // ChatError is the structured error attached to a failed tool call. type ChatError struct { Type string `json:"type,omitempty"` Message string `json:"message,omitempty"` } // ChatTime is the epoch-millisecond timing envelope of a tool call. type ChatTime struct { Created int64 `json:"created,omitempty"` Ran int64 `json:"ran,omitempty"` Completed int64 `json:"completed,omitempty"` } // ChatEventFrame is the server-pushed chat_event frame. Kind selects the // payload: text and reasoning carry an incremental Delta plus the target Part, // tool carries a full Part with its state, step marks turn progress and usage // reports the turn's totals. type ChatEventFrame struct { // NativeTurnID scopes session activity to a harness turn when available. NativeTurnID string `json:"native_turn_id,omitempty"` Compaction *ChatCompaction `json:"compaction,omitempty"` SessionID string `json:"session_id"` MessageID string `json:"message_id,omitempty"` Kind string `json:"kind"` Delta string `json:"delta,omitempty"` Part *ChatPart `json:"part,omitempty"` // Attachments carries the file parts of a user turn another client sent. // A frame has one Part, so the prompt's files travel alongside its text. Attachments []ChatPart `json:"attachments,omitempty"` Step *ChatStep `json:"step,omitempty"` Usage *ChatUsage `json:"usage,omitempty"` // Shell is the payload of a ChatEventShell frame: the shell's id, its // status, the command it is running and (once it has exited) its exit code. // It is nil on every other kind. Shell *ChatShell `json:"shell,omitempty"` // Form is the payload of a ChatEventForm frame: the agent's pending question // (or another OpenCode form), and the resolved/cancelled terminal state. Form *ChatForm `json:"form,omitempty"` // Client is the sending device's label on a user frame (ChatEventUser), so a // transcript can say who sent the message. It is empty on assistant frames. Client string `json:"client,omitempty"` OperationID string `json:"operation_id,omitempty"` // MessageKind is the ChatMessage.Kind of the message a text frame starts, // so a live agent report or notice is never drawn as an answer or a prompt. MessageKind string `json:"message_kind,omitempty"` } // ChatCompaction is session activity, never a transcript message or tool. // ID is optional: OpenCode V2 compaction events have no shared lifecycle id. type ChatCompaction struct { Status string `json:"status"` // running | completed | failed ID string `json:"id,omitempty"` } // ChatStep is a progress marker for the current step of a turn. type ChatStep struct { Status string `json:"status"` TurnID string `json:"turn_id,omitempty"` Index int `json:"index,omitempty"` // Intermediate distinguishes a provider step from authoritative turn completion. Intermediate bool `json:"intermediate,omitempty"` } // ChatUsage carries native usage snapshots. Rich metrics are pointers so zero // reported by a harness remains distinguishable from an unavailable value. // Session snapshots replace previous values; consumers must not sum updates. type ChatUsage struct { InputTokens int `json:"input_tokens,omitempty"` OutputTokens int `json:"output_tokens,omitempty"` Cost float64 `json:"cost,omitempty"` Scope string `json:"scope,omitempty"` TotalTokens *int64 `json:"total_tokens,omitempty"` ContextTokens *int64 `json:"context_tokens,omitempty"` ContextWindow *int64 `json:"context_window,omitempty"` CostUSD *float64 `json:"cost_usd,omitempty"` OutputTokensPerSecond *float64 `json:"output_tokens_per_second,omitempty"` // RateBasis distinguishes a generation interval from a whole turn (which // can include tools/waits). Never estimate tokens from text/character counts. RateBasis string `json:"rate_basis,omitempty"` // Account is the latest account quota the harness reported (or a note that // it has no quota API). It is account state, not session state: a snapshot // carries the latest value known when it was sent. Nil means unknown. Account *ChatAccountUsage `json:"account,omitempty"` } // ChatAccountUsage is a harness account's subscription quota as the harness // itself reported it. Nothing is estimated: windows are only those the // harness named, and Unsupported says the harness exposes no quota at all. type ChatAccountUsage struct { // Harness is the display name ("Claude Code", "Codex", "OpenCode"). Harness string `json:"harness"` // Source names the native report, e.g. "rate_limit_event". Source string `json:"source,omitempty"` // Plan is the harness's plan identifier when it reports one ("max", "plus"). Plan string `json:"plan,omitempty"` // AsOf is when the server received the report (epoch milliseconds). AsOf int64 `json:"as_of,omitempty"` Windows []ChatQuotaWindow `json:"windows,omitempty"` Unsupported bool `json:"unsupported,omitempty"` } // ChatQuotaWindow is one rolling quota window. UsedPercent is 0-100 (it can // exceed 100 when the harness says usage ran past the cap); ResetsAt is epoch // milliseconds, 0 when the harness did not say. type ChatQuotaWindow struct { ID string `json:"id"` Label string `json:"label"` UsedPercent float64 `json:"used_percent"` ResetsAt int64 `json:"resets_at,omitempty"` } // Clone returns a deep copy (nil stays nil). func (a *ChatAccountUsage) Clone() *ChatAccountUsage { if a == nil { return nil } copy := *a copy.Windows = append([]ChatQuotaWindow(nil), a.Windows...) return © } // ChatShell is the state of one shell command the agent started, carried by a // ChatEventShell frame. ID is the OpenCode shell id and is stable across its // created and exited events, so a client keys a running process by it. Status is // ChatShellRunning or ChatShellExited; Command is the command line the shell was // given (present on the created event); Exit is the process exit code and is // present only once the shell has exited — it is a pointer so an exit of 0 is // distinguishable from "not exited yet". No credential, environment or output is // carried: the command line is the only text, and only so the operator can name // what is running. // ChatForm is the agent's structured question/form. OpenCode emits these as // form.created / form.replied / form.cancelled; the question tool uses // Kind=="question". A client answers with ChatAnswerRequest. Answers is kept as // JSON values because a field may be a string, a list (multiselect), a number or // a boolean. type ChatForm struct { ID string `json:"id"` SessionID string `json:"session_id,omitempty"` Title string `json:"title,omitempty"` Kind string `json:"kind,omitempty"` Fields []ChatFormField `json:"fields,omitempty"` Resolved bool `json:"resolved,omitempty"` Cancelled bool `json:"cancelled,omitempty"` Answers map[string]any `json:"answers,omitempty"` Actions []string `json:"actions,omitempty"` } // ChatFormField is one question/input in a form. Type is OpenCode's field type // (string, multiselect, number, integer, boolean, external); Options is present // when the question offers choices. type ChatFormField struct { Key string `json:"key"` Title string `json:"title,omitempty"` Description string `json:"description,omitempty"` Type string `json:"type,omitempty"` Options []ChatFormOption `json:"options,omitempty"` Custom bool `json:"custom,omitempty"` Required bool `json:"required,omitempty"` Secret bool `json:"secret,omitempty"` URL string `json:"url,omitempty"` Default any `json:"default,omitempty"` Minimum any `json:"minimum,omitempty"` Maximum any `json:"maximum,omitempty"` MinLength *int `json:"min_length,omitempty"` MaxLength *int `json:"max_length,omitempty"` MinItems *int `json:"min_items,omitempty"` MaxItems *int `json:"max_items,omitempty"` Format string `json:"format,omitempty"` Pattern string `json:"pattern,omitempty"` Placeholder string `json:"placeholder,omitempty"` Hidden bool `json:"hidden,omitempty"` When []ChatFormWhen `json:"when,omitempty"` } type ChatFormWhen struct { Key string `json:"key"` Op string `json:"op"` Value any `json:"value"` } // ChatFormOption is one selectable choice in a ChatFormField. type ChatFormOption struct { Value string `json:"value"` Label string `json:"label"` Description string `json:"description,omitempty"` } // ChatRenameRequest is the chat_rename body: the session id and the trimmed // shared title. An empty title is refused rather than clearing the name. type ChatRenameRequest struct { SessionID string `json:"session_id"` Title string `json:"title"` } // ChatNewSessionRequest is the chat_new_session body: the chat whose context // is replaced, and an optional behaviour instruction preloaded on the fresh // session where the harness supports one (like chat_create's Instructions). type ChatNewSessionRequest struct { SessionID string `json:"session_id"` Instructions string `json:"instructions,omitempty"` } // ChatAnswerRequest is the chat_answer body: the form id and a field-keyed // answer object. It is deliberately separate from ChatQuery because its payload // is structured answers, not a session-scoped read. type ChatAnswerRequest struct { Action string `json:"action,omitempty"` SessionID string `json:"session_id"` FormID string `json:"form_id"` Answers map[string]any `json:"answers"` } // ChatShell carries only backend-recorded facts. Timing is epoch milliseconds; // absent optional values mean unknown, never the time the list was read. type ChatShell struct { ID string `json:"id"` Status string `json:"status,omitempty"` Command string `json:"command,omitempty"` Exit *int `json:"exit,omitempty"` StartedAt int64 `json:"started_at,omitempty"` UpdatedAt int64 `json:"updated_at,omitempty"` TaskType string `json:"task_type,omitempty"` Description string `json:"description,omitempty"` Progress string `json:"progress,omitempty"` LastTool string `json:"last_tool,omitempty"` DurationMS *int64 `json:"duration_ms,omitempty"` ToolCount *int64 `json:"tool_count,omitempty"` TokenCount *int64 `json:"token_count,omitempty"` } // ChatShellOutputQuery names one selected shell and a bounded absolute-byte // output page. Cursor is decimal so it can be passed directly to OpenCode. type ChatShellOutputQuery struct { SessionID string `json:"session_id"` ShellID string `json:"shell_id"` Cursor int64 `json:"cursor,omitempty"` Limit int `json:"limit,omitempty"` } // ChatShellOutputPage is a bounded, lazy output read. Unavailable is explicit when // an exited shell is no longer directly verifiable upstream. type ChatShellOutputPage struct { Shell ChatShell `json:"shell"` Output string `json:"output,omitempty"` Cursor int64 `json:"cursor,omitempty"` Size int64 `json:"size,omitempty"` Truncated bool `json:"truncated,omitempty"` Unavailable bool `json:"unavailable,omitempty"` } // ChatPermissionFrame is the server-pushed chat_permission payload: one pending // OpenCode permission request the phone must approve or reject. It is a distinct // Message field (like ChatEvent) rather than a ChatEvent.Kind, so it does not // overload the turn-progress kinds. Its field names match the service's // Permission.Request schema, verified against the installed service's // /openapi.json (id, sessionID, action and resources required; save, metadata, // source and message optional), with id -> RequestID and sessionID -> SessionID. // The wire shape is spec-verified; a live pending request has not been observed. // Every optional field is omitempty so older peers ignore it. type ChatPermissionFrame struct { SessionID string `json:"session_id"` RequestID string `json:"request_id"` Action string `json:"action,omitempty"` Resources []string `json:"resources,omitempty"` Save []string `json:"save,omitempty"` Metadata map[string]any `json:"metadata,omitempty"` Source *ChatPermissionSource `json:"source,omitempty"` Message string `json:"message,omitempty"` AlwaysLabel string `json:"always_label,omitempty"` // Resolved, Decision and ResolvedBy report the shared, exactly-once outcome // of a request any client may answer: once the first answer is recorded the // server pushes the same frame back to every watching client with Resolved // set, the Decision it recorded and the label of the client that gave it, so // their cards clear and show the outcome instead of offering a stale choice. // They are empty on a still-pending request. Resolved bool `json:"resolved,omitempty"` Decision string `json:"decision,omitempty"` ResolvedBy string `json:"resolved_by,omitempty"` } // ChatPermissionSource identifies what raised a permission request, matching the // Permission.Source union (currently only a tool call: type "tool" plus the // message and call id) verified against the service's /openapi.json. type ChatPermissionSource struct { Type string `json:"type,omitempty"` MessageID string `json:"message_id,omitempty"` ID string `json:"id,omitempty"` } // ChatReplyRequest is the chat_reply request body: the phone's decision on a // pending permission request, mirroring // POST /api/session/{id}/permission/{requestID}/reply. Client is the answering // device's label, recorded with the resolution so every other client can see // which device answered. type ChatReplyRequest struct { SessionID string `json:"session_id"` RequestID string `json:"request_id"` Decision string `json:"decision"` Message string `json:"message,omitempty"` Client string `json:"client,omitempty"` }