Skip to main content

Overview

go-flashduty is the official open-source Go client for Flashduty, covering every REST endpoint of the Flashduty Open API. It follows the design of go-github: service groups, typed requests and responses, and a composable transport layer. It maps 1:1 to the OpenAPI spec. Each method makes exactly one HTTP call, returns (*T, *Response, error), and does no implicit aggregation or enrichment across endpoints.
The SDK is deliberately “thin.” Consumer-side logic such as short-ID resolution and cross-endpoint orchestration belongs in the caller (CLI / MCP), not stuffed into the SDK or shoehorned into an endpoint. This keeps the SDK strictly one-to-one with the API — predictable, generatable, and verifiable.
The module path is github.com/flashcatcloud/go-flashduty, the package name is flashduty, and the source is open-sourced under Apache-2.0 at flashcatcloud/go-flashduty.

Open API reference

Request parameters and response fields for every endpoint.

Command-line tool

The CLI for operating Flashduty directly from your terminal.

Installation

1

Requires Go 1.24+

Make sure your local Go toolchain is at least 1.24.
2

Get the dependency

3

Import the package

Quick start

Here is a minimal runnable example: construct the client, list incidents in the “Triggered” state, and handle the returned triple (data, *Response, error).
Every call returns three values:
app_key is used for authentication, and the SDK injects it as a query parameter on every request automatically. Create one in the Flashduty console under Personal center → APP Key. See Personal settings. You can also authenticate with an OAuth access token instead: build the client with NewClientWithAccessToken (see Create a client).

Create a client

NewClient takes an app_key plus zero or more Options. An empty app_key returns an error directly. The default Base URL is https://api.flashcat.cloud, the default HTTP timeout is 30 seconds, and the default User-Agent is go-flashduty.
Private deployment: point the client at your own Flashduty gateway address with WithBaseURL — everything else stays exactly the same.

OAuth access token

Besides the app_key, the SDK accepts an OAuth access token. A client from NewClientWithAccessToken(accessToken, opts...) sends Authorization: Bearer <token> on JSON, GET, and file-upload requests, and doesn’t add the app_key query parameter. Use one credential or the other, not both. An empty token returns an error directly (flashduty: access token is required); everything else matches NewClient, so every Option still applies and the default Base URL, timeout, and User-Agent are the same.
Access tokens are issued by the Flashduty OAuth authorization server, whose address is the API base URL (default https://api.flashcat.cloud). A client discovers it at /.well-known/oauth-authorization-server and gets a token through an authorization-code + PKCE flow. The token calls the public API as its account, with the same access as that account’s app_key. A token is valid only at the deployment that issued it, so do not point WithBaseURL at another gateway when you authenticate with one.

Services and methods

Endpoints are grouped by service and hang off the client: the call convention is uniformly client.<Service>.<Method>(ctx, req), returning (*T, *Response, error). For example, client.Incidents.List(ctx, req) or client.Sessions.ReadInfo(ctx, req).
All identifiers, service field names, and method names match the generated code. For exactly which methods each service has and their request and response types, rely on services_gen.go and the per-service files, plus the Open API reference. The session write and event stream methods aren’t covered by the Open API reference; they’re documented under AI SRE sessions below.
The following services have behavior that needs extra explanation:

Public and dedicated integrations

Public integrations are account-level (/integration/*), managed in the Integration Center, and attach to channels through subscriptions or routing; call them with client.Integrations. A dedicated integration belongs to one channel (/channel/integration/*); call it with client.DedicatedIntegrations, which has eight methods: ReadInfo, ReadList, WriteCreate, WriteUpdate, WriteDelete, WriteEnable, WriteDisable, and WriteRotateKey. Reading a dedicated integration requires one of Channels Read, Channels Manage, or Integrations Read, and the target channel must be visible to you. Writing requires Channels Manage plus management access to that channel. The shared integration type catalog (/integration/type/list) accepts the same three read permissions; a scoped App Key also needs integration.api:read:typeList to query it. Choose the service by who owns the integration, not by the integration ID: ReadInfo, WriteUpdate, and the rest accept only dedicated integration IDs, and a public integration ID is rejected. Insufficient permissions never switch you to the other group. Both groups authenticate with the management App Key; the integration_key in a response is for ingesting events and can’t act as a management credential, and list and info responses carry the complete integration key, so don’t log the full response. Omitted fields keep their stored value on an update. ChannelIntegrationUpdateRequest.Description is a *string of at most 499 characters: nil keeps the stored description, and a pointer to an empty string clears it. A nil Settings keeps the stored configuration, while a non-nil empty map submits {} as the replacement configuration, in which masked (******) or omitted secret fields keep their stored value.

Status page drafts

client.StatusPages.DraftCreate (POST /status-page/draft/create) stores a status page event draft for a human to review and publish from the console; it is never directly visible to the public: draft is arbitrary JSON stored verbatim, up to 64 KB serialized, with page_id, type (incident or maintenance), name, and message validated; change_id (> 0 appends an update to an existing event), status, and affected_components are optional, and for a new maintenance you can set start_time / end_time (Unix seconds) for the window. The request-level source is an opaque marker of the drafting origin (up to 64 characters); the response returns a draft_id matching draft_[A-Za-z0-9]{22}, which the console review link carries.

Knowledge

client.Knowledge covers the 9 operations under /safari/knowledge/*: on the knowledge side PackReadGet (get the account knowledge), PackReadList (list knowledge), PackWriteEnsure (ensure the knowledge exists), PackWriteUpdate (change its scope), and PackWriteDelete (delete it); on the file side FileReadGet, FileReadList, FileWritePut (upload/overwrite), and FileWriteDelete. Exported types include KnowledgePackItem, KnowledgeFileItem, KnowledgeWarning, and the various Knowledge*Request / Knowledge*Response structs.

AI SRE artifacts

client.Artifacts (AI SRE artifacts) covers the 11 operations under /safari/artifact/*: on the gallery read side ReadGet (get a single published artifact by ID), ReadList (list artifacts visible to the caller, with title substring search and scope (all / personal / team) plus team_ids filtering), and ReadGetFileState (probe up to 50 presented-file IDs in one call for ones that already have a live published artifact); on the file side ReadSign (issue short-lived download/preview URLs for a presented file, valid 5 minutes, expires_in is fixed at 300) and ReadStream (download or preview the file’s bytes with a signed token — the success body is a file, not a JSON envelope, with the raw bytes on Response.Raw); on the write side WritePublish (publish a session-produced file to the gallery), WriteUpdate (rename the artifact or transfer it between personal and team scope), and WriteDelete (detach it from the gallery; the source file stays with its session); public sharing WriteShareEnable (turn on anonymous public sharing and return the public link — anyone with the link can view it, no login required), WriteShareRevoke (turn sharing off; the link stops resolving immediately), and WriteShareSync (refresh the public snapshot with the latest content — when share_enabled is true and share_file_id differs from file_id, the snapshot is stale and calling this refreshes it). Exported types include PublishedArtifactItem, ArtifactShareState, SignedUrLs, and the various Artifact*Request / Artifact*Response structs.

Automation rules

client.Automations covers /safari/automation/*. A rule’s execution destination (scope and where it runs) is fixed at creation time:
  • AutomationRuleCreateRequest.RunIn (run_in) is current-chat (binds the rule to the authenticated live IM conversation) or web (runs in the web console). Omitted, the server decides: current-chat for an authenticated IM invocation, web otherwise. Sending current-chat outside a live IM conversation is rejected.
  • AutomationRuleCreateRequest.TeamID (team_id) is a *int64: an explicit 0 means personal scope and a value greater than 0 picks a team in the account. Omitted, it inherits the authenticated IM conversation’s scope when one is present; otherwise the server applies its normal default. A current-chat rule’s scope must match that conversation’s scope.
  • AutomationRuleUpdateRequest no longer has TeamID (nor RunIn): scope and execution destination are immutable after creation. Old code that set TeamID on an update request should drop the line — otherwise it will not compile.
The war room creation trigger’s fields behave differently on the two request types:
  • On the create request they are plain values: AutomationRuleCreateRequest.WarRoomTriggerEnabled (bool), WarRoomChannelIDs ([]int64), WarRoomSeverities ([]string). On the update request all three are pointers (*bool / *[]int64 / *[]string): nil leaves the field unchanged, a non-nil value is sent.
  • The server creates the trigger when it is given one: WarRoomTriggerEnabled is true, or WarRoomChannelIDs is non-empty. In that case both the channel list and the severity list (Critical / Warning / Info) must be non-empty, and a missing one is rejected as an invalid parameter; severities alone do not create a trigger.
  • Passing an empty slice on update is the same as omitting it: the server treats an empty list as not provided and keeps the stored value, so filters can only be replaced wholesale with non-empty lists — an empty array does not clear them.
  • On the way back, AutomationRuleItem.WarRoomTriggerEnabled always has a value (false when there is no such trigger), while WarRoomTriggerID, WarRoomChannelIDs, and WarRoomSeverities are empty ("" / empty slices).
For what the fields mean and when the trigger fires, see Automations · War room created.

Rule folders

client.RuleFolders covers the six operations under /monit/folder/*. ReadList (POST /monit/folder/list) and ReadHealth (POST /monit/folder/health) take no request body. The first returns a flat []FolderItem that you rebuild into a tree in the client from ParentID / ParentPath (dashboards and alert rules share that same tree); the second returns a FolderHealthOutput, whose FolderHealthItem.HasIssue marks a folder that — or whose visible descendant — has active alerts or rule runtime issues. On the write side WriteCreate (/monit/folder/create) and WriteUpdate (/monit/folder/update) return the FolderItem, while WriteMove (/monit/folder/move) and WriteDelete (/monit/folder/delete) return only a *Response. Further exported types are FolderCreateRequest, FolderUpdateRequest, FolderMoveRequest, and FolderDeleteRequest. Request fields: FolderCreateRequest.Name is required and may not contain a period, slash, or comma, and a ParentID of 0 or omitted creates a root folder. FolderUpdateRequest requires both ID and Name and replaces the editable fields — omitting Note clears the note and omitting TeamID resets it to 0 (account-wide). FolderMoveRequest requires DestParentID even when moving back to the root (pass 0), and a folder cannot be moved under itself or one of its descendants. FolderDeleteRequest carries only ID; only an empty folder can be deleted, so child folders, alert rules, or dashboards inside it make the call fail with HTTP 409 and FolderNotEmpty.

Diagnostic queries

client.Diagnostics.QueryData runs a synchronous query through POST /monit/query/data and returns a stable query_result.v1 structured result (result.kind is one of frames, records, or samples). This API requires monit-edge v0.65.0 or later. For log-pattern and metric-trend analysis, use client.DataSources.ToolsInvoke with prometheus.metric_trends, loki.log_patterns, or victorialogs.log_patterns. client.Diagnostics.QueryExplore (POST /monit/query/explore, monit-read-query-explore) runs an explore query against a configured data source and returns the data source’s native explore_result.v1 shape: ExploreData.format is always explore_result.v1; result.kind is frames (columnar tables or time series, see ExploreFrame / ExploreField), samples (instant values with labels, ExploreSample), or logs (log entries as ExploreLogEntry, at most 1,000, with has_more set when truncated and applied_limit reporting the effective cap); and execution.effective_step_seconds echoes the step actually used after applying max_data_points and min_step_seconds. Request fields: datasource_id (from /monit/datasource/list, and it must belong to the authenticated account), expr (a query expression in the data source’s native language — PromQL, LogsQL, SQL, and so on), args (macro substitutions keyed by variable name, used for Grafana-style variables; required in the request, so pass an empty map[string]string{} when you have none — a nil Go map serializes to null, which does not satisfy the schema), and execution (QueryExploreExecution: kind is instant, range, or window; to_ms is required for all three; range additionally requires from_ms and max_data_points, window additionally requires from_ms; min_step_seconds is accepted only for range). How it differs from QueryData: reach for QueryExplore when you need the data source’s native result shape (raw logs included) and QueryData when you need the stable query_result.v1 contract. This API requires the data source view (monit) permission and monit-edge v0.68.0 or later in supported deployments.

RUM remote config and repositories

Beyond application management, client.Applications (RUM applications) covers the five RUM remote configuration methods: RemoteConfigReadGet (POST /rum/application/remote-config/get, read the live configuration and its version), RemoteConfigReadHistoryList (/rum/application/remote-config/history/list, page through published history versions), RemoteConfigReadPreview (/rum/application/remote-config/preview, evaluate a draft configuration against a simulated client’s env / app_version / sdk and return the matching rule index hit_rule_index plus the values finally delivered, without publishing), RemoteConfigWriteUpdate (/rum/application/remote-config/update, publish a complete new configuration), and RemoteConfigWriteHistoryRevert (/rum/application/remote-config/history/revert, republish a history version’s content as a new version). Main types: RemoteConfig (enabled, activation, default, rules, custom, refresh_on_foreground), RemoteConfigValues (the four SDK knobs a configuration can set), RemoteConfigRule (match conditions plus the set values), RemoteConfigHistoryItem (with version, reason, content_hash, and updated_by), and the GetRemoteConfigRequest / ListRemoteConfigHistoryRequest / PreviewRemoteConfigRequest / UpdateRemoteConfigRequest / RevertRemoteConfigRequest structs with their matching *Response types. The application’s own WriteCreate / WriteUpdate / ReadInfo / ReadInfos / ReadList also carry repositories ([]RUMApplicationRepository, a body-only field rather than a top-level flag): it links the application to the source code repositories that build it — ordered, first entry is the primary repository, at most 10 entries, each one a Repo (GitHub repository in owner/name form, required) plus an optional Subdir (the directory holding the application inside the repository, relative to the repository root — . is the repository root, an empty value is saved as .). Passing it on create establishes the links; on update the field is presence-based — passing it replaces the whole list, an empty array clears the links, and omitting it leaves them unchanged; ReadInfo / ReadInfos / ReadList echo it back on RUMApplicationItem. Linking grants no access by itself: AI sessions can only read repositories granted to the account’s GitHub App installations. This field is currently available through the API and SDK only; the console’s application management page does not expose repository links.

Data source tool invocation

client.DataSources.ToolsInvoke (POST /monit/datasource/tools/invoke, monit-datasource-tools-invoke) executes one deterministic tool against a configured datasource: tool is a single tool name prefixed by the datasource type (for example, mysql.overview), and params is the tool-specific JSON parameters (omitted means {}; an explicit null is invalid). Alongside diagnostic tools, the entry supports <type>.query query tools (prometheus, mysql, postgres, oracle, clickhouse, elasticsearch, loki, victorialogs, sls, tencent_cls); the /monit/query/data entry stays unchanged. It requires monit-edge v0.71.0 or later. Limits: 128 KiB request body, 10 MiB success response, and a tool timeout of at most 25 seconds. The response is a DatasourceToolResult: data is tool-specific JSON and never null, summary is optional, and a truncated object with reason signals truncation. To call a <type>.query tool, build the request with NewDatasourceQueryInvokeRequest(datasourceID, tool, params) and pass the matching typed struct for that tool: PrometheusQueryParams, MySQLQueryParams, PostgresQueryParams, OracleQueryParams, ClickHouseQueryParams, ElasticsearchQueryParams, LokiQueryParams, VictoriaLogsQueryParams, SLSQueryParams, or TencentCLSQueryParams. All of them pair expr with an execution (DatasourceQueryExecution: kind is instant, range, or window, and from_ms / to_ms are Unix-millisecond *int64 values; range additionally requires max_data_points and accepts min_step_seconds to raise the computed step). Optional fields are pointers — a nil pointer omits the key and lets the server apply its default. Query-tool params may not be empty: NewDatasourceQueryInvokeRequest(..., nil) returns an error, unlike the general “omitted means {}” rule. The execution mode is constrained by datasource type: Prometheus and Loki use instant or range (instant carries only to_ms); the SQL types (MySQL, Postgres, Oracle, ClickHouse, and the SQL-flavored Elasticsearch) plus SLS and Tencent CLS use window; VictoriaLogs uses window for raw logs and instant / range for stats queries. limit and direction on Loki, VictoriaLogs, SLS, and Tencent CLS bound raw-log retrieval only, and SLSQueryParams also requires project / logstore while TencentCLSQueryParams requires region / topic_id / syntax.

Prometheus label values

client.DataSources.ReadPrometheusLabelValues(ctx, dataSourceID, labelName) (GET /monit/prometheus/api/v1/label/{label_name}/values, monit-prometheus-read-label-values) lists every value of one label on a Prometheus-compatible data source through the monitoring proxy: the label name goes in the URL path (the SDK escapes it), and the target data source is selected by the X-DSID request header — the SDK sets it from the dataSourceID argument (a 0 ID or an empty labelName errors immediately), with the ID taken from /monit/datasource/list and required to be a Prometheus-compatible data source of the current account. It is the only method whose success body is not the Flashduty {request_id, data} envelope: the response decodes straight into PrometheusLabelValuesResponse (data carries the label-value strings when status is success; errorType and error are present when it is error). Failures before the data source is reached (invalid X-DSID, no such data source, or not a Prometheus type) return text/plain. The data source’s own failures use its JSON error shape. The SDK treats both the same and puts the raw body in *ErrorResponse.Message. Two cases return no error: a request that carries no X-DSID, and a data source whose monit-edge cluster has an instance older than v0.35.0 (one that does not support the resource proxy) — both answer 200 with an empty Prometheus-compatible body, where data is an empty array for /api/v1/labels, /api/v1/series, and /api/v1/label/{label_name}/values, and an empty object for /api/v1/metadata. So when you read an empty result, do not take it to mean the label has no values — first check that X-DSID was sent and whether the edge needs an upgrade. Supported deployments require monit-edge v0.35.0 or later.

Data source configuration

For client.DataSources, the payload selects a type-specific configuration block by type_ident. Fifteen type_ident values are allowed: prometheus, loki, mysql, oracle, postgres, clickhouse, elasticsearch, sls, tencent_cls, victorialogs, plus the diagnostic-only types redis_node, redis_sentinel, mongodb_mongod, mongodb_mongos, and kafka — diagnostic-only types always have alerting_enabled false (which does not block non-alerting queries or tools) and reject true. Connection address rules: Redis/MongoDB diagnostic types take a single host:port (bracket IPv6), with no URI, userinfo, or query; kafka takes 1–32 unique comma-separated host:port bootstrap addresses (at most 4096 characters after normalization); for mongodb_mongod / mongodb_mongos the configuration block’s auth_source defaults to admin, username and password must be configured together, and client certificates are unsupported; the Redis node configuration’s database defaults to 0. Sensitive fields, such as the diagnostic types’ password and Kafka’s tls_key, support ${env:NAME} references. Responses omit literal values and echo only ${env:...} references. On update, omitting a field keeps the stored value, and an empty string clears it. enabled and alerting_enabled are independent: enabled (whether business execution is enabled) defaults to true on create; alerting_enabled (whether alert evaluation is allowed; alerting also requires enabled true and an alerting-capable type) defaults to true for alerting types and false for diagnostic-only types on create. On update, omitting either preserves the current value and an explicit null is invalid; disabling (enabled false) is rejected with a conflict when enabled rules reference the datasource. Also note that payload is always null in /monit/datasource/list responses (the list query does not read the payload column); it is populated in create/update/info responses.

Service calendar events

client.Calendars covers /calendar/*. CalEventIDRequest (CalEventDelete, POST /calendar/event/delete) supports two usages: pass EventID to delete a single event, or omit it and pass both StartAt and EndAt (YYYY-MM-DD, EndAt exclusive) to clear the calendar’s own events off those days, with the cleared days falling back to the linked holiday calendars and the weekly workdays. Pass one or the other; CalID is always required. CalEventUpsert (POST /calendar/event/upsert) creates or updates an event the calendar owns over [StartAt, EndAt) (IsOff true marks a day off, false a working-day override): omit EventID to create a new event, and a given EventID must be an existing event of that calendar. The write first takes the calendar’s other own events off the same days — an event fully inside the range is deleted, one partly inside is shortened, and one spanning the range is split in two — so the latest write decides those days. EndAt must be later than StartAt, and Summary is optional. CalEventList (POST /calendar/event/list) scopes the range with Year / Month / Day on CalEventListRequest (with Month and Day both 0 it returns the whole year). Alongside Items (events sorted by StartAt) and Total, CalEventListResponse carries a required Days: a map[string]CalDay keyed by YYYY-MM-DD that gives the resolved state of every day in that scope. Each CalDay reports IsOff, EventID (the event that decided the day, absent when no event covers it), and Layer (custom / holiday / weekly). Days resolve by layer precedence: the calendar’s own events (custom) outrank the linked holiday calendars (holiday), which outrank the weekly workdays (weekly). Inside one layer a working-day event beats a day off, so a make-up workday from a holiday calendar wins over holiday rest days. A day no event covers is a working day.

Incident work items

The WorkItem* methods on client.Incidents (/incident/work-item/*) manage an incident’s action items and post-mortem follow-ups. Work-item status is a closed enum: Status on CreateWorkItemRequest / UpdateWorkItemRequest and TargetStatus on ConvertWorkItemRequest accept only open, in_progress, done, or cancelled, with creation taking open when the field is omitted or blank and TargetStatus being optional. WorkItemComplete’s CompleteWorkItemRequest.TargetStatus accepts only done; any other value is rejected.

Response timestamps

Time fields in responses are self-describing Timestamp (Unix seconds) or TimestampMilli (milliseconds) types. Types shared by requests and responses are the exception (see the warning below). They serialize to RFC3339 strings in the local time zone, so JSON, logs, and LLM-facing output are directly readable; the raw epoch is still one method call away.
  • Serialization (outbound): a non-zero value serializes to a quoted RFC3339 string (TimestampMilli uses RFC3339Nano to preserve millisecond precision). A zero value serializes to the bare integer 0 — an “unset” sentinel rather than a 1970 date, and dropped by json:",omitempty".
  • Deserialization (inbound): it accepts both numeric epoch (the raw wire form) and RFC3339 strings (so a serialized value round-trips losslessly), and also accepts null (→ 0).
Request-side time fields are still int64 — the API expects a numeric epoch on the wire. Note: most endpoints take seconds, but RUM and webhook history-related endpoints take milliseconds.Types shared by requests and responses are the same. AlertRuleV2 (the return type of AlertRules.ReadInfoV2 / WriteCreateV2 / WriteUpdateV2, that is, POST /monit/rule/v2/info, /v2/create, and /v2/update) keeps created_at / updated_at as bare int64 Unix seconds with omitempty, not Timestamp. Such fields have no Unix() / String() / IsZero() methods, so convert the seconds yourself — writing rule.UpdatedAt.Unix() as in the Timestamp examples will not compile.
AlertRuleV2’s investigation_targets (the same return type of AlertRules.ReadInfoV2 / WriteCreateV2 / WriteUpdateV2) has this shape:
  • The field itself is []InvestigationTarget, at most 20 entries with no duplicates, and the serialized list must not exceed 32 KiB (32768 bytes); exceeding it returns investigation_targets must not exceed 32768 bytes. On the update endpoint it is presence-based — omitting it keeps the saved configuration, sending [] clears it. Each entry may carry an optional purpose: one-sentence plain text saying what the entry helps confirm (do not put line breaks in it; the server validates ≤512 bytes and requires valid UTF-8 with no control characters, while the console caps the input at 200 characters, so the API accepts somewhat more than the console, but 200 CJK characters can already exceed 512 bytes). purpose is literal text, not a template, and is not part of alert identity or de-duplication.
  • Each entry is a closed tagged union, and Kind decides which sub-object you supply. dashboard (opens a dashboard panel) requires Dashboard, and query (opens an Explore query) requires Query. Supplying the other one, or an unknown field, is rejected.
  • TimeRange (InvestigationTimeRange: BeforeSeconds and AfterSeconds) is required on every saved entry — both directions are non-negative and at least one is greater than zero.
  • The Dashboard entry (DashboardInvestigationTarget) takes its variables in Variables: a map[string]string keyed by variable name whose values are literal, and may reference event labels through {{ }} templates. DashboardID and Variables are required and TargetID is optional; DashboardID and TargetID must both be canonical UUIDv7 values.
  • The Query entry uses QueryInvestigationTarget: Query is required and is a DashboardQuery — Mode is instant, range, or window, Expr is an expression in the target data source’s own language that may use {{ }} templates, Args are named parameters passed through verbatim and must not contain templates, and MinStepSeconds is only accepted when Mode is range. DatasourceID may be omitted (or set to 0), which runs the query on the alert event’s own datasource.

Pagination

All list endpoints share ListOptions, which you embed in the request struct. Zero values are omitted and never override server defaults (the backend defaults to p=1, limit=20). On the response side, *Response carries Total, HasNextPage, and SearchAfterCtx. We recommend walking page by page with the search-after cursor:

Error handling

An unsuccessful call returned by the Flashduty API — whether the envelope carries an error or the HTTP status is non-2xx — returns *ErrorResponse. It has Code, Message, an optional Reason, and RequestID fields; when troubleshooting, give RequestID to the support team to pinpoint the request. Reason carries the server-supplied optional cause (the envelope’s DutyError has the same field, JSON reason,omitempty); when non-empty it is also appended to the end of the error string, as , reason X. When the API returns 429, the error is promoted to *RateLimitError: it embeds *ErrorResponse (so errors.As for *ErrorResponse still matches) and additionally carries a RetryAfter hint. Code values match the Open API error code list.
For generated endpoints, if you receive a non-2xx response with a non-JSON body, the SDK returns a plain error, not *ErrorResponse. This indicates that a gateway, load balancer, proxy, or other intermediary produced the response, usually because the request exceeded an intermediary timeout. Retry the request or split a long-running batch into smaller batches, and do not assume that errors.As(err, &apiErr) matches this error.The hand-written client.DataSources.ReadPrometheusLabelValues method is the exception: it parses no envelope and instead puts a non-2xx response’s raw body verbatim into *ErrorResponse.Message, treating the platform’s text/plain 4xx/5xx bodies and the data source’s own JSON error shape alike (429 is still promoted to *RateLimitError). errors.As(err, &apiErr) therefore does match there — Code is usually empty, so read Message and Response.StatusCode to identify the cause.
Typed predicate functions save string comparisons and see through wrapped errors (using errors.As internally):

Retry

The core client has no built-in automatic retry. Compose the optional retry subpackage through the transport layer — a safe-by-default retrying http.RoundTripper. Features of github.com/flashcatcloud/go-flashduty/retry:
  • Retry conditions: HTTP 429, any 5xx (status ≥ 500), and transport errors. Other 4xx and all 2xx/3xx return immediately.
  • Backoff policy: deterministic exponential backoff (MinWait * 2^attempt, capped at MaxWait each time); no random jitter. When a valid integer Retry-After header is present, it takes precedence (also capped at MaxWait).
  • Safe replay: retries only when the body is replayable (req.Body is nil or req.GetBody is non-nil). Each retry rebuilds the body on a clone, and the caller’s *http.Request is never modified. All requests the SDK builds set GetBody, so POST bodies are safely replayable.
  • Respects cancellation: if the request context is canceled while waiting out a backoff, it returns the context error immediately.
The retry subpackage is pure net/http and deliberately does not import the parent flashduty package, so it never introduces a circular dependency. Both retry.New() and &retry.Transport{} (zero value) work out of the box.

AI SRE sessions

Driving an AI SRE session from Go takes three steps: write a user turn, subscribe to the event stream to read the replies, and export the whole transcript when you need a record. The first two use client.Sessions.WriteMessage and client.Sessions.Subscribe; the third uses client.Sessions.Export in Streaming export.

Session writes (create a session, send a message, upload attachments)

Send one user turn with client.Sessions.WriteMessage (POST /safari/session/message). Omit SessionID to start a new session, in which case AppName (such as ai-sre) and EntryKind are required, and EntryKind is web, im, or api. Query is the message text, at most 32000 characters. Every other field is optional:
  • Parts: extra message parts, each a SessionMessagePart whose Type is text or file. A text part uses Text; a file part uses File (a SessionFilePart with Mime, Filename, ObjectKey, and Size) pointing at a file already uploaded to that session.
  • Surface: tags where the turn originated, for example cli.
  • DeliveryMode: negotiates how replies are delivered. With reply_only, the agent answers only through its reply tool; SessionMessageAck.DeliveryMode in the response is the mode the server actually accepted, and it’s empty when the requested mode was not granted.
  • Steering: marks this message as sent while a turn was already running. With true, that running turn takes the message in at its next step and answers it, so the answer comes from that turn’s event stream rather than only from this message’s own invocation; with no turn running the field is ignored and the message is queued as usual.
  • EnvironmentKind: the execution environment, cloud or byoc; EnvironmentID picks a specific environment of that kind.
  • TeamID: binds a new session to a team, 0 for account scope.
WriteMessage returns as soon as the server has durably queued the turn (HTTP 202), and the response holds only SessionID, InvocationID, RootInvocationID, and the granted DeliveryMode. The turn runs asynchronously, so replies are not in that response; read them from the session event stream (see Session event stream below). An attachment must belong to an existing session. To upload before the first message, create an empty session first with WriteCreate (POST /safari/session/create): AppName is required, EntryKind is web, im, api, or automation, and TeamID is immutable once the session exists. UploadAttachment (POST /safari/attachment/upload) stores a file under a session. SessionID, File, and Filename on SessionAttachmentUploadRequest are all required, and one file can be at most 50 MB. FilePart() on the returned SessionAttachment turns it into a SessionMessagePart for the next message’s Parts:
When Parts is set, the server ignores Query, so put the text in a text part.

Session event stream (Subscribe, SSE)

client.Sessions.Subscribe (POST /safari/session/subscribe, Accept: text/event-stream) opens the session’s event stream and returns an io.ReadCloser. The stream first replays persisted events strictly newer than your cursor, then keeps tailing live frames; Export instead reads the whole transcript once as NDJSON, so the two serve different jobs. Read frames with NewSessionFrameReader and Next():
  • Cursor: SessionSubscribeRequest.LastEventAt is Unix milliseconds, and 0 replays from the start of the session; LastEventID only breaks ties between events that share the same millisecond. Put the previous frame’s CreatedAt and EventID back into those two fields to resume after it, so a reconnect doesn’t repeat events you already handled.
  • Lifetime: the stream has no time limit, and the server closes it after an idle period. ctx bounds the stream, so cancel ctx to stop it. The returned io.ReadCloser belongs to the caller and you must Close it.
  • End and errors: Next() returns io.EOF on the [DONE] sentinel or a clean close, a *SessionStreamError for an in-band error record, and the transport error (including context cancellation) otherwise. A non-2xx status is still the regular JSON error envelope: Subscribe reads and closes it and returns a typed error with a nil io.ReadCloser, matching the generated endpoints.
  • Frame fields: SessionEventFrame carries EventID, CreatedAt, Type, AgentPath, Payload (raw JSON), InvocationID, RootInvocationID, DeliveryMode, IsError, and ErrorCode. A persisted event has EventID and CreatedAt, and its Type is the author (user, assistant, and so on); an ephemeral frame (turn_complete, assistant_token, and so on) has no EventID, and its Type is the frame type.
  • Relation to reply_only: for a turn sent with DeliveryMode: "reply_only", the replies appear only on this stream, never in the WriteMessage response.

Streaming export

client.Sessions.Export exports the full event transcript of an AI SRE session, returning an io.ReadCloser (an NDJSON stream, application/x-ndjson) rather than a JSON envelope. The first line is always a session_meta envelope, and each later line is a session event. When req.IncludeSubagents is true, each subagent_dispatch line is followed by the subagent’s full event stream. Because the response body can be large, read it line by line and write directly to a file — do not buffer the whole transcript into memory. The returned io.ReadCloser is the live HTTP response body, held by the caller and which you must Close (a defer close is correct). Pair it with NewExportScanner to scan line by line and DecodeExportLine to decode a line into an ExportLine:
NewExportScanner uses a per-line buffer large enough for wide event lines, such as tool output or LLM calls. It isn’t bound by the default 64KB token limit. On any non-2xx status, the body is a regular JSON error envelope. Like other generated endpoints, Export reads and closes it and returns a typed error (*ErrorResponse, or *RateLimitError on 429) with a nil io.ReadCloser.