workspacesdk

package
v2.39.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 40 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// CoderChatIDHeader is the HTTP header containing the current
	// chat ID. Set by coderd on agentconn requests originating
	// from chatd.
	CoderChatIDHeader = "Coder-Chat-Id"
	// CoderAncestorChatIDsHeader is the HTTP header containing a
	// JSON array of ancestor chat UUIDs.
	CoderAncestorChatIDsHeader = "Coder-Ancestor-Chat-Ids"
)
View Source
const (
	// DefaultMaxFileSize is the default maximum file size (1 MB).
	DefaultMaxFileSize int64 = 1 << 20
	// DefaultMaxLineBytes is the default per-line truncation threshold.
	DefaultMaxLineBytes int64 = 1024
	// DefaultMaxResponseLines is the default max lines per response.
	DefaultMaxResponseLines int64 = 2000
	// DefaultMaxResponseBytes is the default max response size (32 KB).
	DefaultMaxResponseBytes int64 = 32768
)
View Source
const (
	// DesktopNativeWidth is the default native desktop width in pixels used for
	// computer-use desktop sessions.
	DesktopNativeWidth = 1920
	// DesktopNativeHeight is the default native desktop height in pixels used for
	// computer-use desktop sessions.
	DesktopNativeHeight = 1080
)
View Source
const (
	AgentSSHPort             = tailnet.WorkspaceAgentSSHPort
	AgentStandardSSHPort     = tailnet.WorkspaceAgentStandardSSHPort
	AgentReconnectingPTYPort = tailnet.WorkspaceAgentReconnectingPTYPort
	AgentSpeedtestPort       = tailnet.WorkspaceAgentSpeedtestPort
	// AgentHTTPAPIServerPort serves a HTTP server with endpoints for e.g.
	// gathering agent statistics.
	AgentHTTPAPIServerPort = 4

	// AgentMinimumListeningPort is the minimum port that the listening-ports
	// endpoint will return to the client, and the minimum port that is accepted
	// by the proxy applications endpoint. Coder consumes ports 1-4 at the
	// moment, and we reserve some extra ports for future use. Port 9 and up are
	// available for the user.
	//
	// This is not enforced in the CLI intentionally as we don't really care
	// *that* much. The user could bypass this in the CLI by using SSH instead
	// anyways.
	AgentMinimumListeningPort = 9
)
View Source
const (
	AgentAPIMismatchMessage = "Unknown or unsupported API version"

	CoordinateAPIInvalidResumeToken = "Invalid resume token"
)
View Source
const CoderToolCallIDHeader = "Coder-Tool-Call-Id"

CoderToolCallIDHeader carries the chat tool call ID. The agent deduplicates requests by chat and tool call ID, and uses the ID as the process ID of a process it starts.

View Source
const MaxRecordingSize = 100 << 20 // 100 MB

MaxRecordingSize is the largest desktop recording (in bytes) that will be accepted. Used by both the agent-side stop handler and the server-side storage pipeline.

View Source
const MaxSkillMetaBytes = 64 * 1024

MaxSkillMetaBytes is the maximum raw Markdown size accepted for a skill meta file.

View Source
const MaxThumbnailSize = 10 << 20 // 10 MB

MaxThumbnailSize is the largest thumbnail (in bytes) that will be accepted. Applied both agent-side (before streaming) and server-side (when parsing multipart parts).

View Source
const SkillNameRegex = "^[a-z0-9]+(-[a-z0-9]+)*$"

SkillNameRegex is the regular expression used to validate kebab-case skill names.

Variables

View Source
var AgentIgnoredListeningPorts = map[uint16]struct{}{
	0: {},

	1: {},
	2: {},
	3: {},
	4: {},
	5: {},
	6: {},
	7: {},
	8: {},

	20: {},
	21: {},

	22: {},

	23: {},

	25: {},

	53: {},

	110: {},

	143: {},

	179: {},

	389: {},
	636: {},

	465: {},

	587: {},

	989: {},
	990: {},

	993: {},

	995: {},

	3306: {},

	3389: {},

	5432: {},

	27017: {},
	27018: {},
	27019: {},
	28017: {},
}

AgentIgnoredListeningPorts contains a list of ports to ignore when looking for running applications inside a workspace. We want to ignore non-HTTP servers, so we pre-populate this list with common ports that are not HTTP servers.

This is implemented as a map for fast lookup.

View Source
var ErrAgentTCPUpgradeUnsupported = xerrors.New("agent does not support the tcp upgrade endpoint")
View Source
var ErrDialAbandoned = xerrors.New("dial abandoned")

ErrDialAbandoned is a cancel cause for a dial whose result the caller no longer wants, such as a dial to an agent that a rebuild replaced. A dial canceled with it is not counted as an unreachable agent.

View Source
var ErrFrontmatterNameRequired = xerrors.New("frontmatter missing required 'name' field")

ErrFrontmatterNameRequired is returned by ParseSkillFrontmatter when the frontmatter is missing a required name field.

View Source
var ErrReadinessProbeTimeout = xerrors.New("agent readiness probe timed out")

ErrReadinessProbeTimeout is a timeout cause for one attempt in a loop that waits for a starting agent to come online. The agent is expected to be missing until it boots, so a dial that times out with it is not counted as an unreachable agent.

View Source
var ErrSkipClose = xerrors.New("skip tailnet close")
View Source
var SkillNamePattern = regexp.MustCompile(SkillNameRegex)

SkillNamePattern is the compiled pattern used to validate kebab-case skill names.

Functions

func ExistsViaCoderConnect added in v2.22.0

func ExistsViaCoderConnect(ctx context.Context, hostname string) (bool, error)

ExistsViaCoderConnect checks if the given hostname exists via Coder Connect. This doesn't guarantee the workspace is actually reachable, if, for example, its agent is unhealthy, but rather that Coder Connect knows about the workspace and advertises the hostname via DNS.

func ParseSkillFrontmatter added in v2.32.0

func ParseSkillFrontmatter(content string) (name, description, body string, err error)

ParseSkillFrontmatter extracts name, description, and the remaining body from a skill meta file. The expected format is YAML frontmatter delimited by "---" lines:

---
name: my-skill
description: Does a thing
---
Body text here...

func SkillDisablesModelInvocation

func SkillDisablesModelInvocation(content string) bool

SkillDisablesModelInvocation reports whether a skill meta file's frontmatter sets disable-model-invocation to the YAML boolean true. Agents must not discover or load such a skill on their own; only a person can invoke it. Any other value, and content whose frontmatter does not parse, leaves the skill model-invocable.

func ToolCallIDFromContext

func ToolCallIDFromContext(ctx context.Context) (uuid.UUID, bool)

ToolCallIDFromContext returns the tool call ID set by WithToolCallID.

func WithTestOnlyCoderContextResolver added in v2.22.0

func WithTestOnlyCoderContextResolver(ctx context.Context, r Resolver) context.Context

func WithToolCallID

func WithToolCallID(ctx context.Context, id uuid.UUID) context.Context

WithToolCallID returns a context whose tool execution requests send id in CoderToolCallIDHeader. The ID goes on the context because parallel tool calls share one AgentConn.

Types

type ACPConfigOption

type ACPConfigOption struct {
	ID           string           `json:"id"`
	Name         string           `json:"name"`
	Description  string           `json:"description,omitempty"`
	CurrentValue string           `json:"current_value"`
	Category     string           `json:"category,omitempty"`
	Values       []ACPConfigValue `json:"values"`
}

ACPConfigOption describes an ACP session select option.

type ACPConfigValue

type ACPConfigValue struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Group       string `json:"group,omitempty"`
	GroupName   string `json:"group_name,omitempty"`
}

ACPConfigValue is a selectable value advertised by a harness.

type ACPCreateSessionRequest

type ACPCreateSessionRequest struct {
	HarnessSlug      string            `json:"harness_slug"`
	WorkingDirectory string            `json:"working_directory"`
	Config           map[string]string `json:"config,omitempty"`
}

ACPCreateSessionRequest creates an idle session in an explicit directory.

type ACPCursor

type ACPCursor struct {
	GenerationID uuid.UUID `json:"generation_id"`
	Seq          uint64    `json:"seq"`
}

ACPCursor identifies a position in an in-memory transcript.

type ACPEvent

type ACPEvent struct {
	Cursor  ACPCursor       `json:"cursor"`
	Kind    ACPEventKind    `json:"kind"`
	Text    string          `json:"text,omitempty"`
	Update  json.RawMessage `json:"update,omitempty"`
	Session *ACPSession     `json:"session,omitempty"`
}

ACPEvent carries an ACP update, runtime status, or error.

type ACPEventKind

type ACPEventKind string

ACPEventKind identifies the content of an ACP transcript or stream event.

const (
	ACPEventKindUpdate   ACPEventKind = "update"
	ACPEventKindStatus   ACPEventKind = "status"
	ACPEventKindError    ACPEventKind = "error"
	ACPEventKindReset    ACPEventKind = "reset"
	ACPEventKindSnapshot ACPEventKind = "snapshot"
)

type ACPHarness

type ACPHarness struct {
	Slug          string            `json:"slug"`
	DisplayName   string            `json:"display_name"`
	LoadSession   bool              `json:"load_session"`
	ResumeSession bool              `json:"resume_session"`
	ConfigOptions []ACPConfigOption `json:"config_options"`
	Error         string            `json:"error,omitempty"`
}

ACPHarness is the public discovery result. Commands stay on the agent.

type ACPMessageOutcome

type ACPMessageOutcome string

ACPMessageOutcome describes how a prompt was admitted.

const ACPMessageOutcomePrompt ACPMessageOutcome = "prompt"

ACPMessageOutcomePrompt means a prompt request was written to the adapter.

type ACPMessageRequest

type ACPMessageRequest struct {
	Text string `json:"text"`
}

ACPMessageRequest supplies a prompt to an idle session.

type ACPMessageResponse

type ACPMessageResponse struct {
	Outcome ACPMessageOutcome `json:"outcome"`
}

ACPMessageResponse reports message admission, not turn completion.

type ACPReadOptions

type ACPReadOptions struct {
	After *ACPCursor
}

ACPReadOptions optionally selects the portion after a transcript cursor.

type ACPSession

type ACPSession struct {
	Harness            ACPHarness        `json:"harness"`
	ID                 ACPSessionID      `json:"id"`
	HarnessDisplayName string            `json:"harness_display_name"`
	Config             map[string]string `json:"config,omitempty"`
	Status             ACPSessionStatus  `json:"status"`
	StopReason         string            `json:"stop_reason,omitempty"`
	Error              string            `json:"error,omitempty"`
	Cursor             ACPCursor         `json:"cursor"`
}

ACPSession describes a runtime session without its transcript.

type ACPSessionID

type ACPSessionID struct {
	HarnessSlug      string `json:"harness_slug"`
	WorkingDirectory string `json:"working_directory"`
	SessionID        string `json:"session_id"`
}

ACPSessionID identifies a native session and supplies its recovery context. The agent uses it to load or resume sessions without local metadata storage.

type ACPSessionResponse

type ACPSessionResponse struct {
	Session           ACPSession `json:"session"`
	Events            []ACPEvent `json:"events"`
	AssistantResponse string     `json:"assistant_response"`
}

ACPSessionResponse carries rich history and its assistant-text projection.

type ACPSessionStatus

type ACPSessionStatus string

ACPSessionStatus describes the lifecycle state of an ACP runtime session.

const (
	ACPSessionStatusInitializing ACPSessionStatus = "initializing"
	ACPSessionStatusIdle         ACPSessionStatus = "idle"
	ACPSessionStatusRunning      ACPSessionStatus = "running"
	ACPSessionStatusInterrupting ACPSessionStatus = "interrupting"
	ACPSessionStatusError        ACPSessionStatus = "error"
)

type AgentConn

type AgentConn interface {
	AgentID() uuid.UUID
	ListACPHarnesses(ctx context.Context) ([]ACPHarness, error)
	CreateACPSession(ctx context.Context, req ACPCreateSessionRequest) (ACPSession, error)
	ReadACPSession(ctx context.Context, id ACPSessionID, opts ACPReadOptions) (ACPSessionResponse, error)
	SendACPMessage(ctx context.Context, id ACPSessionID, req ACPMessageRequest) (ACPMessageResponse, error)
	InterruptACPSession(ctx context.Context, id ACPSessionID) (ACPSession, error)
	WatchACPSession(ctx context.Context, logger slog.Logger, id ACPSessionID, opts ACPReadOptions) (<-chan ACPEvent, io.Closer, error)
	TailnetConn() *tailnet.Conn
	SetExtraHeaders(h http.Header)

	AwaitReachable(ctx context.Context) bool
	CallMCPTool(ctx context.Context, req CallMCPToolRequest) (CallMCPToolResponse, error)
	Close() error
	ContextConfig(ctx context.Context) (ContextConfigResponse, error)
	DebugLogs(ctx context.Context, opts ...DebugLogsOption) ([]byte, error)
	DebugMagicsock(ctx context.Context) ([]byte, error)
	DebugManifest(ctx context.Context) ([]byte, error)
	DialContext(ctx context.Context, network string, addr string) (net.Conn, error)
	AppHTTPClient() *http.Client
	GetPeerDiagnostics() tailnet.PeerDiagnostics
	ListContainers(ctx context.Context) (codersdk.WorkspaceAgentListContainersResponse, error)
	ListProcesses(ctx context.Context) (ListProcessesResponse, error)
	ListeningPorts(ctx context.Context) (codersdk.WorkspaceAgentListeningPortsResponse, error)
	Netcheck(ctx context.Context) (healthsdk.AgentNetcheckReport, error)
	Ping(ctx context.Context) (time.Duration, bool, *ipnstate.PingResult, error)
	ProcessOutput(ctx context.Context, id string, opts *ProcessOutputOptions) (ProcessOutputResponse, error)
	PrometheusMetrics(ctx context.Context) ([]byte, error)
	ReconnectingPTY(ctx context.Context, id uuid.UUID, height uint16, width uint16, command string, initOpts ...AgentReconnectingPTYInitOption) (net.Conn, error)
	DeleteDevcontainer(ctx context.Context, devcontainerID string) error
	RecreateDevcontainer(ctx context.Context, devcontainerID string) (codersdk.Response, error)
	SignalProcess(ctx context.Context, id string, signal string) error
	StartProcess(ctx context.Context, req StartProcessRequest) (StartProcessResponse, error)
	CancelToolCall(ctx context.Context, id uuid.UUID) (CancelToolCallResponse, error)
	LS(ctx context.Context, path string, req LSRequest) (LSResponse, error)
	ResolvePath(ctx context.Context, path string) (string, error)
	ReadFile(ctx context.Context, path string, offset, limit int64) (io.ReadCloser, string, error)
	ReadFileInRoot(ctx context.Context, root, path string, offset, limit int64) (io.ReadCloser, string, error)
	ReadFileLines(ctx context.Context, path string, offset, limit int64, limits ReadFileLinesLimits) (ReadFileLinesResponse, error)
	WriteFile(ctx context.Context, path string, reader io.Reader) error
	UploadChatFile(ctx context.Context, req UploadChatFileRequest) (AgentUploadChatFileResponse, error)
	EditFiles(ctx context.Context, edits FileEditRequest) (FileEditResponse, error)
	BundleFiles(ctx context.Context, req BundleFilesRequest) ([]byte, error)
	// Deprecated: Use SSHTCPConn instead.
	SSH(ctx context.Context) (*gonet.TCPConn, error)
	SSHTCPConn(ctx context.Context) (TCPConn, error)
	SSHClient(ctx context.Context) (*ssh.Client, error)
	SSHClientOnPort(ctx context.Context, port uint16) (*ssh.Client, error)
	SSHOnPort(ctx context.Context, port uint16) (*gonet.TCPConn, error)
	Speedtest(ctx context.Context, direction speedtest.Direction, duration time.Duration) ([]speedtest.Result, error)
	WatchContainers(ctx context.Context, logger slog.Logger) (<-chan codersdk.WorkspaceAgentListContainersResponse, io.Closer, error)
	WatchGit(ctx context.Context, logger slog.Logger, chatID uuid.UUID) (*wsjson.Stream[codersdk.WorkspaceAgentGitServerMessage, codersdk.WorkspaceAgentGitClientMessage], error)
	ConnectDesktopVNC(ctx context.Context) (net.Conn, error)
	ExecuteDesktopAction(ctx context.Context, action DesktopAction) (DesktopActionResponse, error)
	StartDesktopRecording(ctx context.Context, req StartDesktopRecordingRequest) error
	StopDesktopRecording(ctx context.Context, req StopDesktopRecordingRequest) (StopDesktopRecordingResponse, error)
}

AgentConn represents a connection to a workspace agent. @typescript-ignore AgentConn

func NewAgentConn

func NewAgentConn(conn *tailnet.Conn, opts AgentConnOptions) AgentConn

NewAgentConn creates a new WorkspaceAgentConn. `conn` may be unique to the WorkspaceAgentConn, or it may be shared in the case of coderd. If the conn is shared and closing it is undesirable, you may return ErrNoClose from opts.CloseFunc. This will ensure the underlying conn is not closed.

func WrapAgentConn added in v2.33.0

func WrapAgentConn(conn AgentConn, closeFunc func() error) AgentConn

WrapAgentConn returns an AgentConn that delegates every operation to conn and applies closeFunc exactly once when the logical session is closed.

If conn is nil, any provided closeFunc is invoked immediately so logical session cleanup is not silently dropped.

type AgentConnFunc added in v2.33.0

type AgentConnFunc func(ctx context.Context, agentID uuid.UUID) (conn AgentConn, release func(), err error)

AgentConnFunc returns a new connection to the specified agent. If release is non-nil, callers must invoke it after they are done with the AgentConn.

type AgentConnOptions

type AgentConnOptions struct {
	AgentID   uuid.UUID
	CloseFunc func() error
	Logger    slog.Logger
}

@typescript-ignore AgentConnOptions

type AgentConnectionInfo

type AgentConnectionInfo struct {
	DERPMap                  *tailcfg.DERPMap `json:"derp_map"`
	DERPForceWebSockets      bool             `json:"derp_force_websockets"`
	DisableDirectConnections bool             `json:"disable_direct_connections"`
	HostnameSuffix           string           `json:"hostname_suffix,omitempty"`
}

AgentConnectionInfo returns required information for establishing a connection with a workspace. @typescript-ignore AgentConnectionInfo

type AgentReconnectingPTYInit

type AgentReconnectingPTYInit struct {
	ID      uuid.UUID
	Height  uint16
	Width   uint16
	Command string
	// Container, if set, will attempt to exec into a running container visible to the agent.
	// This should be a unique container ID (implementation-dependent).
	Container string
	// ContainerUser, if set, will set the target user when execing into a container.
	// This can be a username or UID, depending on the underlying implementation.
	// This is ignored if Container is not set.
	ContainerUser string

	BackendType string
}

AgentReconnectingPTYInit initializes a new reconnecting PTY session. @typescript-ignore AgentReconnectingPTYInit

type AgentReconnectingPTYInitOption added in v2.21.0

type AgentReconnectingPTYInitOption func(*AgentReconnectingPTYInit)

AgentReconnectingPTYInitOption is a functional option for AgentReconnectingPTYInit.

func AgentReconnectingPTYInitWithContainer added in v2.21.0

func AgentReconnectingPTYInitWithContainer(container, containerUser string) AgentReconnectingPTYInitOption

AgentReconnectingPTYInitWithContainer sets the container and container user for the reconnecting PTY session.

type AgentUpdate added in v2.34.0

type AgentUpdate struct {
	Lifecycle codersdk.WorkspaceAgentLifecycle `json:"lifecycle"`
	ID        uuid.UUID                        `json:"id" format:"uuid"`
}

type AgentUploadChatFileResponse

type AgentUploadChatFileResponse struct {
	// Path is the absolute path where the file was written on the workspace.
	Path string `json:"path"`
	// Name is the final basename after sanitization and collision suffixing.
	Name string `json:"name"`
	// Size is the number of bytes written to the workspace.
	Size int64 `json:"size"`
}

AgentUploadChatFileResponse is the response from uploading to a workspace agent.

type BuildUpdate added in v2.34.0

type BuildUpdate struct {
	Transition codersdk.WorkspaceTransition  `json:"transition"`
	JobStatus  codersdk.ProvisionerJobStatus `json:"job_status"`
}

type BundleFilesLimits added in v2.36.0

type BundleFilesLimits struct {
	MaxFiles        int   `json:"max_files"`
	MaxBytesPerFile int64 `json:"max_bytes_per_file"`
	MaxTotalBytes   int64 `json:"max_total_bytes"`
}

BundleFilesLimits are the collection limits the agent applied.

type BundleFilesManifest added in v2.36.0

type BundleFilesManifest struct {
	Requested []string                   `json:"requested"`
	Files     []BundleFilesManifestEntry `json:"files"`
	Errors    []BundleFilesManifestError `json:"errors"`
	Truncated bool                       `json:"truncated"`
	Limits    BundleFilesLimits          `json:"limits"`
}

BundleFilesManifest is the manifest.json of the archive returned by BundleFiles.

type BundleFilesManifestEntry added in v2.36.0

type BundleFilesManifestEntry struct {
	Requested    string    `json:"requested"`
	Path         string    `json:"path"`
	ArchivePath  string    `json:"archive_path"`
	Size         int64     `json:"size"`
	ModTime      time.Time `json:"mod_time"`
	BytesWritten int64     `json:"bytes_written"`
	Truncated    bool      `json:"truncated"`
}

BundleFilesManifestEntry describes one file collected into the archive.

type BundleFilesManifestError added in v2.36.0

type BundleFilesManifestError struct {
	Requested string `json:"requested"`
	Path      string `json:"path,omitempty"`
	Reason    string `json:"reason"`
}

BundleFilesManifestError records a path that could not be collected.

type BundleFilesRequest added in v2.36.0

type BundleFilesRequest struct {
	Paths []string `json:"paths"`
}

BundleFilesRequest configures a workspace-side file collection.

type CallMCPToolRequest added in v2.32.0

type CallMCPToolRequest struct {
	// ToolName is the prefixed tool name (e.g. "github__create_issue").
	ToolName string `json:"tool_name"`
	// Arguments is the tool input as key-value pairs.
	Arguments map[string]any `json:"arguments"`
}

CallMCPToolRequest is the request body for proxying an MCP tool call through the workspace agent.

type CallMCPToolResponse added in v2.32.0

type CallMCPToolResponse struct {
	Content []MCPToolContent `json:"content"`
	IsError bool             `json:"is_error"`
}

CallMCPToolResponse is the response from a proxied MCP tool call.

type CancelToolCallResponse

type CancelToolCallResponse struct {
	Received    bool   `json:"received"`               // false if the agent has no record of the tool call
	Status      int    `json:"status,omitempty"`       // saved response status, if Received
	ContentType string `json:"content_type,omitempty"` // saved response Content-Type, if Received
	Body        []byte `json:"body,omitempty"`         // saved response body, if Received
}

CancelToolCallResponse is the response to a tool call cancel. The agent has no record of a tool call it never received, or after it restarted or expired the record.

func (CancelToolCallResponse) EditFilesResult

func (r CancelToolCallResponse) EditFilesResult() (FileEditResponse, error)

EditFilesResult decodes a saved edit response as EditFiles does.

func (CancelToolCallResponse) StartProcessResult

func (r CancelToolCallResponse) StartProcessResult() (StartProcessResponse, error)

StartProcessResult decodes a saved start response as StartProcess does.

func (CancelToolCallResponse) WriteFileResult

func (r CancelToolCallResponse) WriteFileResult() error

WriteFileResult decodes a saved write response as WriteFile does.

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(c *codersdk.Client) *Client

func (*Client) AgentConnectionInfo

func (c *Client) AgentConnectionInfo(ctx context.Context, agentID uuid.UUID) (AgentConnectionInfo, error)

func (*Client) AgentConnectionInfoGeneric

func (c *Client) AgentConnectionInfoGeneric(ctx context.Context) (AgentConnectionInfo, error)

func (*Client) AgentReconnectingPTY

func (c *Client) AgentReconnectingPTY(ctx context.Context, opts WorkspaceAgentReconnectingPTYOpts) (net.Conn, error)

AgentReconnectingPTY spawns a PTY that reconnects using the token provided. It communicates using `agent.ReconnectingPTYRequest` marshaled as JSON. Responses are PTY output that can be rendered.

func (*Client) DialAgent

func (c *Client) DialAgent(dialCtx context.Context, agentID uuid.UUID, options *DialAgentOptions) (agentConn AgentConn, err error)

func (*Client) IsCoderConnectRunning added in v2.22.0

func (c *Client) IsCoderConnectRunning(ctx context.Context, o CoderConnectQueryOptions) (bool, error)

IsCoderConnectRunning checks if Coder Connect (OS level tunnel to workspaces) is running on the system. If you already know the hostname suffix your deployment uses, you can pass it in the CoderConnectQueryOptions to avoid an API call to AgentConnectionInfoGeneric.

func (*Client) RewriteDERPMap added in v2.25.0

func (c *Client) RewriteDERPMap(derpMap *tailcfg.DERPMap)

RewriteDERPMap rewrites the DERP map to use the configured access URL of the client as the "embedded relay" access URL.

See tailnet.RewriteDERPMapDefaultRelay for more details on why this is necessary.

func (*Client) WorkspaceAgentConnectionWatch added in v2.34.0

func (c *Client) WorkspaceAgentConnectionWatch(
	dialCtx context.Context, workspaceID uuid.UUID, agentName string,
) (
	dec *wsjson.Decoder[ConnectionWatchEvent], err error,
)

type CoderConnectQueryOptions added in v2.22.0

type CoderConnectQueryOptions struct {
	HostnameSuffix string
}

type ConnectionWatchEvent added in v2.34.0

type ConnectionWatchEvent struct {
	Error       *WatchError  `json:"error"`
	BuildUpdate *BuildUpdate `json:"build_update,omitempty"`
	AgentUpdate *AgentUpdate `json:"agent_update,omitempty"`
}

type ContextConfigResponse added in v2.32.0

type ContextConfigResponse struct {
	Parts []codersdk.ChatMessagePart `json:"parts"`
}

ContextConfigResponse is the response from the agent's context configuration endpoint. Contains pre-read instruction file contents and discovered skill metadata as chat message parts.

type DebugLogsOption added in v2.35.0

type DebugLogsOption func(*debugLogsConfig)

DebugLogsOption configures a DebugLogs request.

func WithLogsAfter added in v2.35.0

func WithLogsAfter(t time.Time) DebugLogsOption

WithLogsAfter also returns rotated logs modified at or after t, separated by boundary markers (100 MiB combined cap).

type DesktopAction added in v2.32.0

type DesktopAction struct {
	Action          string  `json:"action"`
	Coordinate      *[2]int `json:"coordinate,omitempty"`
	StartCoordinate *[2]int `json:"start_coordinate,omitempty"`
	Text            *string `json:"text,omitempty"`
	Duration        *int    `json:"duration,omitempty"`
	ScrollAmount    *int    `json:"scroll_amount,omitempty"`
	ScrollDirection *string `json:"scroll_direction,omitempty"`
	// ScaledWidth and ScaledHeight carry the declared model-facing desktop
	// geometry used for screenshot sizing and coordinate mapping.
	ScaledWidth  *int `json:"scaled_width,omitempty"`
	ScaledHeight *int `json:"scaled_height,omitempty"`
}

DesktopAction is the request body for the desktop action endpoint.

type DesktopActionResponse added in v2.32.0

type DesktopActionResponse struct {
	Output           string `json:"output,omitempty"`
	ScreenshotData   string `json:"screenshot_data,omitempty"`
	ScreenshotWidth  int    `json:"screenshot_width,omitempty"`
	ScreenshotHeight int    `json:"screenshot_height,omitempty"`
}

DesktopActionResponse is the response from the desktop action endpoint.

type DesktopGeometry added in v2.32.0

type DesktopGeometry struct {
	NativeWidth    int
	NativeHeight   int
	DeclaredWidth  int
	DeclaredHeight int
}

DesktopGeometry describes the native workspace desktop and the declared model-facing geometry used for screenshots and coordinates.

func DefaultDesktopGeometry added in v2.32.0

func DefaultDesktopGeometry() DesktopGeometry

DefaultDesktopGeometry returns the default native desktop geometry together with the declared model-facing geometry derived from it.

func DefaultOpenAIComputerUseDesktopGeometry added in v2.34.0

func DefaultOpenAIComputerUseDesktopGeometry() DesktopGeometry

DefaultOpenAIComputerUseDesktopGeometry returns the default native desktop geometry with OpenAI's recommended computer-use declared dimensions.

func NewDesktopGeometry added in v2.32.0

func NewDesktopGeometry(nativeWidth, nativeHeight int) DesktopGeometry

NewDesktopGeometry derives a declared model-facing geometry from the native desktop size.

func NewDesktopGeometryWithDeclared added in v2.32.0

func NewDesktopGeometryWithDeclared(
	nativeWidth,
	nativeHeight,
	declaredWidth,
	declaredHeight int,
) DesktopGeometry

NewDesktopGeometryWithDeclared returns a geometry that preserves the native desktop size while using the provided declared model-facing dimensions.

func (DesktopGeometry) DeclaredPointToNative added in v2.32.0

func (g DesktopGeometry) DeclaredPointToNative(x, y int) (nativeX, nativeY int)

DeclaredPointToNative maps a point from declared model-facing coordinates to native desktop coordinates using the existing pixel-center truncation rule.

func (DesktopGeometry) NativePointToDeclared added in v2.32.0

func (g DesktopGeometry) NativePointToDeclared(x, y int) (declaredX, declaredY int)

NativePointToDeclared maps a point from native desktop coordinates to the declared model-facing coordinate space using the same truncating transform.

type DialAgentOptions

type DialAgentOptions struct {
	Logger slog.Logger
	// BlockEndpoints forced a direct connection through DERP. The Client may
	// have DisableDirect set which will override this value.
	BlockEndpoints bool
	// CaptureHook is a callback that captures Disco packets and packets sent
	// into the tailnet tunnel.
	CaptureHook capture.Callback
	// Whether the client will send network telemetry events.
	// Enable instead of Disable so it's initialized to false (in tests).
	EnableTelemetry bool
	// ClientSessionID, when set, is attached to network telemetry events as
	// client_session_id so the session can be correlated across the client's
	// logs, requests, and telemetry.
	ClientSessionID string
}

@typescript-ignore DialAgentOptions

type FileEdit added in v2.27.0

type FileEdit struct {
	OldText    string `` /* 140-byte string literal not displayed */
	NewText    string `json:"new_text" description:"Text that replaces old_text."`
	ReplaceAll bool   `` /* 126-byte string literal not displayed */
}

FileEdit is a single old_text -> new_text replacement applied to one file. The fields use old_text/new_text instead of the earlier search/replace because models confused the direction (CODAGT-312); the old keys are not decoded.

type FileEditRequest added in v2.27.0

type FileEditRequest struct {
	Files []FileEdits `json:"files"`
	// IncludeDiff asks the agent to compute a unified diff per file
	// and return it in FileEditResponse.Files[i].Diff. When false
	// (default) the agent skips diff computation and Files is nil.
	IncludeDiff bool `json:"include_diff,omitempty"`
}

type FileEditResponse added in v2.33.0

type FileEditResponse struct {
	Files []FileEditResult `json:"files,omitempty"`
}

FileEditResponse is the success response for the edit-files endpoint. When the request's IncludeDiff flag is set, Files contains one entry per edited file in request order. Each entry's Path matches the caller-supplied path (pre-symlink resolution).

The slice is named Files (rather than Diffs) so future work can hang per-file errors or status off each element without a second wire break.

type FileEditResult added in v2.33.0

type FileEditResult struct {
	Path string `json:"path"`
	Diff string `json:"diff"`
}

FileEditResult carries the outcome of editing one file. Path is the original caller-supplied path, not any symlink-resolved target. Diff is the unified-diff string produced when the caller set FileEditRequest.IncludeDiff; it is empty for no-op edits or when diffs were not requested.

type FileEdits added in v2.27.0

type FileEdits struct {
	Path  string     `json:"path" description:"The absolute path of the file to edit, for example /home/coder/project/main.go."`
	Edits []FileEdit `json:"edits" description:"Edits that replace old text with new text, applied to this file in order."`
}

FileEdits carries the model-facing schema descriptions so the chat tool's generated schema includes per-field guidance.

type LSFile added in v2.27.0

type LSFile struct {
	Name string `json:"name"`
	// e.g. "C:\\Users\\coder\\hello.txt"
	//      "/home/coder/hello.txt"
	AbsolutePathString string `json:"absolute_path_string"`
	IsDir              bool   `json:"is_dir"`
}

type LSRelativity added in v2.27.0

type LSRelativity string
const (
	LSRelativityRoot LSRelativity = "root"
	LSRelativityHome LSRelativity = "home"
)

type LSRequest added in v2.27.0

type LSRequest struct {
	// e.g. [], ["repos", "coder"],
	Path []string `json:"path"`
	// Whether the supplied path is relative to the user's home directory,
	// or the root directory.
	Relativity LSRelativity `json:"relativity"`
}

type LSResponse added in v2.27.0

type LSResponse struct {
	AbsolutePath []string `json:"absolute_path"`
	// Returned so clients can display the full path to the user, and
	// copy it to configure file sync
	// e.g. Windows: "C:\\Users\\coder"
	//      Linux: "/home/coder"
	AbsolutePathString string   `json:"absolute_path_string"`
	Contents           []LSFile `json:"contents"`
}

type ListProcessesResponse added in v2.32.0

type ListProcessesResponse struct {
	Processes []ProcessInfo `json:"processes"`
}

ListProcessesResponse contains information about tracked processes on the workspace agent.

type MCPToolContent added in v2.32.0

type MCPToolContent struct {
	Type      string `json:"type"` // "text", "image", "audio", "resource"
	Text      string `json:"text,omitempty"`
	Data      string `json:"data,omitempty"` // base64 for binary
	MediaType string `json:"media_type,omitempty"`
}

MCPToolContent is a single content block in an MCP tool response.

type MCPToolInfo added in v2.32.0

type MCPToolInfo struct {
	// ServerName is the key from .mcp.json (e.g. "github").
	ServerName string `json:"server_name"`
	// Name is the prefixed tool name: "serverName__toolName".
	Name string `json:"name"`
	// Description is the tool's human-readable description.
	Description string `json:"description"`
	// Schema is the JSON Schema for the tool's input parameters.
	Schema map[string]any `json:"schema"`
	// Required lists required parameter names.
	Required []string `json:"required"`
}

MCPToolInfo describes a single tool discovered from an MCP server configured in the workspace's .mcp.json file.

type ProcessInfo added in v2.32.0

type ProcessInfo struct {
	ID         string `json:"id"`
	Command    string `json:"command"`
	WorkDir    string `json:"workdir,omitempty"`
	Background bool   `json:"background"`
	Running    bool   `json:"running"`
	ExitCode   *int   `json:"exit_code,omitempty"`
	StartedAt  int64  `json:"started_at_unix"`
	ExitedAt   *int64 `json:"exited_at_unix,omitempty"`
}

ProcessInfo describes a tracked process on the agent.

type ProcessOutputOptions added in v2.32.0

type ProcessOutputOptions struct {
	// Wait enables blocking mode. When true, the request
	// blocks until the process exits or the context expires.
	Wait bool
	// TimeoutFromStartProcess also ends a blocking wait at
	// StartProcessRequest.TimeoutMs.
	TimeoutFromStartProcess bool
}

ProcessOutputOptions configures blocking behavior for process output retrieval.

type ProcessOutputResponse added in v2.32.0

type ProcessOutputResponse struct {
	Output    string             `json:"output"`
	Truncated *ProcessTruncation `json:"truncated,omitempty"`
	Running   bool               `json:"running"`
	ExitCode  *int               `json:"exit_code,omitempty"`
	Command   string             `json:"command,omitempty"`
	TimedOut  bool               `json:"timed_out,omitempty"` // running past StartProcessRequest.TimeoutMs
	Canceled  bool               `json:"canceled,omitempty"`  // its tool call was canceled while it ran
}

ProcessOutputResponse contains the output of a process.

type ProcessTruncation added in v2.32.0

type ProcessTruncation struct {
	OriginalBytes int    `json:"original_bytes"`
	RetainedBytes int    `json:"retained_bytes"`
	OmittedBytes  int    `json:"omitted_bytes"`
	Strategy      string `json:"strategy"`
}

ProcessTruncation describes how process output was truncated.

type ReadFileLinesLimits added in v2.32.0

type ReadFileLinesLimits struct {
	// MaxFileSize is the maximum file size (in bytes) that will be opened.
	MaxFileSize int64
	// MaxLineBytes is the per-line byte cap before truncation.
	MaxLineBytes int
	// MaxResponseLines is the maximum number of lines in a single response.
	MaxResponseLines int
	// MaxResponseBytes is the maximum total bytes of formatted output.
	MaxResponseBytes int
}

ReadFileLinesLimits contains configurable safety limits for the line-based file reader. These are sent as query parameters so callers can tune them without requiring an agent redeployment.

func DefaultReadFileLinesLimits added in v2.32.0

func DefaultReadFileLinesLimits() ReadFileLinesLimits

DefaultReadFileLinesLimits returns the default limits.

type ReadFileLinesResponse added in v2.32.0

type ReadFileLinesResponse struct {
	Success    bool   `json:"success"`
	FileSize   int64  `json:"file_size,omitempty"`
	TotalLines int    `json:"total_lines,omitempty"`
	LinesRead  int    `json:"lines_read,omitempty"`
	Content    string `json:"content,omitempty"`
	Error      string `json:"error,omitempty"`
}

ReadFileLinesResponse is the response from the line-based file reader.

type ReconnectingPTYRequest

type ReconnectingPTYRequest struct {
	Data   string `json:"data,omitempty"`
	Height uint16 `json:"height,omitempty"`
	Width  uint16 `json:"width,omitempty"`
}

ReconnectingPTYRequest is sent from the client to the server to pipe data to a PTY. @typescript-ignore ReconnectingPTYRequest

type ResolvePathResponse added in v2.33.0

type ResolvePathResponse struct {
	ResolvedPath string `json:"resolved_path"`
}

ResolvePathResponse is the response from the agent's path-resolution endpoint.

type Resolver added in v2.22.0

type Resolver interface {
	LookupIP(ctx context.Context, network, host string) ([]net.IP, error)
}

type SignalProcessRequest added in v2.32.0

type SignalProcessRequest struct {
	Signal string `json:"signal"`
}

SignalProcessRequest is the request body for signaling a process on the workspace agent.

type StartDesktopRecordingRequest added in v2.32.0

type StartDesktopRecordingRequest struct {
	RecordingID string `json:"recording_id"`
}

StartDesktopRecordingRequest is the request body for starting a desktop recording session.

type StartProcessRequest added in v2.32.0

type StartProcessRequest struct {
	Command    string            `json:"command"`
	WorkDir    string            `json:"workdir,omitempty"`
	Env        map[string]string `json:"env,omitempty"`
	Background bool              `json:"background,omitempty"`
	// TimeoutMs is the wait timeout in milliseconds after the process
	// starts; see ProcessOutputOptions.TimeoutFromStartProcess. Not allowed
	// with Background.
	TimeoutMs int64 `json:"timeout_ms,omitempty"`
}

StartProcessRequest is the request body for starting a process on the workspace agent.

type StartProcessResponse added in v2.32.0

type StartProcessResponse struct {
	ID      string `json:"id"`
	Started bool   `json:"started"`
}

StartProcessResponse is returned when a process is started.

type StopDesktopRecordingRequest added in v2.32.0

type StopDesktopRecordingRequest struct {
	RecordingID string `json:"recording_id"`
}

StopDesktopRecordingRequest is the request body for stopping a desktop recording session.

type StopDesktopRecordingResponse added in v2.33.0

type StopDesktopRecordingResponse struct {
	Body        io.ReadCloser
	ContentType string
}

StopDesktopRecordingResponse wraps the response from stopping a desktop recording. Body contains the recording data as a multipart/mixed stream. ContentType holds the Content-Type header (including boundary) so callers can parse the body.

type TCPConn

type TCPConn interface {
	net.Conn
	CloseWrite() error
}

func DialTCPUpgrade

func DialTCPUpgrade(ctx context.Context, addr string, client *http.Client, headers http.Header, port uint16) (TCPConn, error)

DialTCPUpgrade dials the agent's /tcp HTTP endpoint which allows sending extra data to the agent via headers. These must include the client session ID or the connection will be refused. The agent will then upgrade the connection based on the port. Returns ErrAgentTCPUpgradeUnsupported if the agent does not support the endpoint.

type UploadChatFileRequest

type UploadChatFileRequest struct {
	// ChatID is the full chat UUID used to namespace the upload directory.
	ChatID string
	// Name is the filename. Coderd sanitizes it before the call; the
	// agent sanitizes again as defense in depth for direct tailnet
	// callers.
	Name string
	// Body must remain readable until UploadChatFile returns.
	Body io.Reader
}

UploadChatFileRequest is the streaming request for the agent's chat-file upload endpoint.

type WatchError added in v2.34.0

type WatchError struct {
	Code      WatchErrorCode `json:"code"`
	Retryable bool           `json:"retryable"`
	Message   string         `json:"message"`
	Details   string         `json:"details,omitempty"`
}

func (*WatchError) Error added in v2.34.0

func (e *WatchError) Error() string

type WatchErrorCode added in v2.34.0

type WatchErrorCode int
const (
	WatchErrorTooManyAgents WatchErrorCode
	WatchErrorNameNotFound
	WatchErrorNoAgents
	WatchErrorServerShutdown
	WatchErrorDatabase
	WatchErrorInternal
)

type WebsocketDialer added in v2.18.0

type WebsocketDialer struct {
	// contains filtered or unexported fields
}

func NewWebsocketDialer added in v2.18.0

func NewWebsocketDialer(
	logger slog.Logger, u *url.URL, websocketOptions *websocket.DialOptions,
	dialerOptions ...WebsocketDialerOption,
) *WebsocketDialer

func (*WebsocketDialer) Connected added in v2.18.0

func (w *WebsocketDialer) Connected() <-chan error

func (*WebsocketDialer) Dial added in v2.18.0

type WebsocketDialerOption added in v2.18.0

type WebsocketDialerOption func(*WebsocketDialer)

func WithWorkspaceUpdates added in v2.18.0

func WithWorkspaceUpdates(req *proto.WorkspaceUpdatesRequest) WebsocketDialerOption

type WorkspaceAgentReconnectingPTYOpts

type WorkspaceAgentReconnectingPTYOpts struct {
	AgentID   uuid.UUID
	Reconnect uuid.UUID
	Width     uint16
	Height    uint16
	Command   string

	// SignedToken is an optional signed token from the
	// issue-reconnecting-pty-signed-token endpoint. If set, the session token
	// on the client will not be sent.
	SignedToken string

	// Experimental: Container, if set, will attempt to exec into a running container
	// visible to the agent. This should be a unique container ID
	// (implementation-dependent).
	// ContainerUser is the user as which to exec into the container.
	// NOTE: This feature is currently experimental and is currently "opt-in".
	// In order to use this feature, the agent must have the environment variable
	// CODER_AGENT_DEVCONTAINERS_ENABLE set to "true".
	Container     string
	ContainerUser string

	// BackendType is the type of backend to use for the PTY. If not set, the
	// workspace agent will attempt to determine the preferred backend type.
	// Supported values are "screen" and "buffered".
	BackendType string
}

@typescript-ignore:WorkspaceAgentReconnectingPTYOpts

Directories

Path Synopsis
Package agentconnmock is a generated GoMock package.
Package agentconnmock is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL