1f75e4797e
Add an opt-in way to broker chat from an operator-supplied OpenCode service instead of the instance the server spawns for itself, and a way to adopt a session that already exists on that endpoint so it appears in chat_sessions and can be continued from the app. - Endpoint selection: the `-opencode-endpoint` server flag (defaulting to `PIPELINES_OPENCODE_ENDPOINT`) opts in; precedence is explicit flag > explicit environment > the endpoint recorded on a previous run, with the spawned instance as the default. opencode.OpenEndpoint validates the reference once (http(s), host, no userinfo/query/fragment/path), detects the backend from its own /api/info (v2) or /global/health (v1) contract, and requires a streamable text/event-stream event path. It owns no process (Close is a no-op) and never calls startServe; every failure names the endpoint and disables chat rather than silently falling back. An authenticated endpoint takes an optional password only through the private file PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE, with PIPELINES_OPENCODE_ENDPOINT_USERNAME overriding the detected default. - Persistence: the validated choice is recorded in an additive single-row server_settings table so a restart with no flag/environment reuses it; an unreachable recorded endpoint disables chat with a clear message and no fallback. - chat_adopt: a new protocol request (ChatAdoptRequest) with handleChatAdopt in internal/server/chat.go. It refuses a nil broker/registry/payload and a blank or foreign-shaped id before any endpoint call, reads the endpoint via the shared Chat.Session (which reuses Sessions/decodeChatSessions), records through the existing RecordOperatorSession with the endpoint's directory and title verbatim, and echoes the adopted session plus its registry row like chat_create. A missing id is refused naming the id and records nothing; an endpoint record with an empty directory is refused rather than substituting the server's working directory or home. - CLI: `pipelines chat-adopt <session-id> [--json]` (usage, notes, help inventory, dispatch) with docs/cli.md updated under Chat sessions. - Autostart preserves the endpoint variables (and the password-file reference, never an inline secret) via serviceEnvironmentKeys. Checks before committing: - Package location: the change is user-facing chat behaviour, so the packaged authoring skill reference internal/author/skill/references/operations.md is updated in the same change (Brokered OpenCode chat section) with a dated verification-evidence entry and the not-deployed state. No new reference file is added, so internal/author/install.go's managed inventory is unchanged. - Packaged templates: this repository packages no template set for this behaviour and none references the chat endpoint, so no template needs updating. - Verification: `go build ./...`, `go vet` on the touched packages, `gofmt -l` clean and `go test ./...` all pass. The unit tests cover the endpoint validation/precedence, the adopt happy path and refusals, the recorded endpoint round-trip, the protocol round-trip and the CLI dispatch. The live scratch-server check against the operator's real endpoint was not run in this change. Nothing unrelated is staged; docs left stale (README and other shared documents) are not edited here and are for a single folding writer.
281 lines
11 KiB
Go
281 lines
11 KiB
Go
package protocol
|
|
|
|
import "encoding/json"
|
|
|
|
// 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: <opaque>} 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"
|
|
// 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"
|
|
// ChatEvent and ChatPermission are the server-pushed frames; they are the
|
|
// only types the server sends without a matching request.
|
|
ChatEvent = "chat_event"
|
|
// ChatPermission carries one pending OpenCode approval request the phone
|
|
// answers with chat_reply.
|
|
ChatPermission = "chat_permission"
|
|
)
|
|
|
|
// Content part types carried by ChatPart.Type and ChatEvent.Kind.
|
|
const (
|
|
ChatPartText = "text"
|
|
ChatPartReasoning = "reasoning"
|
|
ChatPartTool = "tool"
|
|
)
|
|
|
|
// ChatEvent.Kind values pushed on the chat_event stream. Step and usage carry
|
|
// no ChatPart; they report turn progress and the turn's totals.
|
|
const (
|
|
ChatEventText = ChatPartText
|
|
ChatEventReasoning = ChatPartReasoning
|
|
ChatEventTool = ChatPartTool
|
|
ChatEventStep = "step"
|
|
ChatEventUsage = "usage"
|
|
)
|
|
|
|
// 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"
|
|
)
|
|
|
|
// 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"`
|
|
Title string `json:"title,omitempty"`
|
|
Agent string `json:"agent,omitempty"`
|
|
Model string `json:"model,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 marks a session another client currently holds (or one the server
|
|
// itself owns as an active run), so the phone can show it read-only instead
|
|
// of letting two clients silently write the same conversation. It is
|
|
// additive and optional: older peers ignore it.
|
|
Busy bool `json:"busy,omitempty"`
|
|
}
|
|
|
|
// ChatCreateRequest is the chat_create request body: a title and an optional
|
|
// working directory (the server's configured location when empty). The response
|
|
// carries the created session in Message.ChatSession.
|
|
type ChatCreateRequest struct {
|
|
Title string `json:"title,omitempty"`
|
|
Directory string `json:"directory,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"`
|
|
}
|
|
|
|
// 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"`
|
|
Limit int `json:"limit,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.
|
|
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"`
|
|
}
|
|
|
|
// 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"`
|
|
Parts []ChatPart `json:"parts"`
|
|
}
|
|
|
|
// 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.
|
|
type ChatPart struct {
|
|
Type string `json:"type"`
|
|
ID string `json:"id,omitempty"`
|
|
Text string `json:"text,omitempty"`
|
|
Name string `json:"name,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.
|
|
// 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"`
|
|
}
|
|
|
|
// 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 {
|
|
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"`
|
|
Step *ChatStep `json:"step,omitempty"`
|
|
Usage *ChatUsage `json:"usage,omitempty"`
|
|
}
|
|
|
|
// ChatStep is a progress marker for the current step of a turn.
|
|
type ChatStep struct {
|
|
Status string `json:"status"`
|
|
Index int `json:"index,omitempty"`
|
|
}
|
|
|
|
// ChatUsage is the token and cost total of a turn.
|
|
type ChatUsage struct {
|
|
InputTokens int `json:"input_tokens,omitempty"`
|
|
OutputTokens int `json:"output_tokens,omitempty"`
|
|
Cost float64 `json:"cost,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"`
|
|
}
|
|
|
|
// 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.
|
|
type ChatReplyRequest struct {
|
|
SessionID string `json:"session_id"`
|
|
RequestID string `json:"request_id"`
|
|
Decision string `json:"decision"`
|
|
Message string `json:"message,omitempty"`
|
|
}
|