streaming

package
v0.214.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 21 Imported by: 0 modules, 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

Overview

Package streaming holds the job log/event/interaction SSE streaming orchestration. It is a neutral layer between the HTTP handler (which owns request parsing, response headers and the flushable writer) and the job service (which owns log files, interactions and lifecycle events). It depends only on job/store + the standard library and must never import httpapi (avoiding a streaming->httpapi import cycle).

Index

Constants

View Source
const (
	// TranscriptPageBytes caps the text one response carries.
	TranscriptPageBytes = 64 << 10
	// TranscriptMaxSearch is the longest search term (a literal substring).
	TranscriptMaxSearch = 200
)
View Source
const (
	TranscriptOutline = "outline"
	TranscriptTurns   = "turns"
	TranscriptHead    = "head"
	TranscriptTail    = "tail"
	TranscriptSearch  = "search"
)

Read modes.

View Source
const (
	TranscriptSourceTurns  = "turns"
	TranscriptSourceACP    = "acp"
	TranscriptSourceStdout = "stdout"
)

Sources of a transcript.

View Source
const StreamPollInterval = 250 * time.Millisecond

StreamPollInterval is how often the SSE loop polls the job's log FILES for appended bytes (web-T3). Logs are read incrementally from a byte offset. Status, lifecycle events and interactions are NOT polled: they are pushed by the job service (StreamSource.WatchJob) and only re-read when a change signal arrives.

Variables

View Source
var (
	// MaxSSEFrameBytes caps the Text payload of a single `log` frame. A larger
	// incremental chunk is split into multiple contiguous-seq frames (no bytes
	// dropped, no truncation) which the frontend reassembles in seq order.
	MaxSSEFrameBytes = 256 << 10 // 256 KiB

	// StreamThrottleBytes is the per-poll new-byte volume above which the loop
	// lengthens the next tick interval to StreamThrottledInterval, spacing out
	// reads under a high-volume producer. It never drops bytes.
	StreamThrottleBytes int64 = 10 << 20 // 10 MiB

	// StreamThrottledInterval is the slower poll cadence used after a high-volume
	// poll; the loop returns to StreamPollInterval once volume calms.
	StreamThrottledInterval = 500 * time.Millisecond
)

SSE log-flow-control tunables (C4). All are package vars (not consts) so tests can set tiny values without producing megabytes of data.

View Source
var ErrInvalidTranscript = errors.New("invalid transcript request")

ErrInvalidTranscript marks a bad parameter combination (an HTTP 400).

View Source
var ErrTranscriptPath = errors.New("transcript path escapes the job's result directory")

ErrTranscriptPath marks a result-dir file that resolves outside the job's directory.

View Source
var StreamSafetyInterval = 5 * time.Second

StreamSafetyInterval is the slow in-memory-only safety net: if a status change ever happens without a change signal, the stream still notices within this interval. It consults only the job's in-memory snapshot (no DB query) for live jobs.

Functions

func StreamACP

func StreamACP(ctx context.Context, w io.Writer, flusher http.Flusher, jobs *job.Service, id string, res job.JobResult, live bool, opts ACPStreamOpts)

StreamACP normalizes one job's ACP JSONL artifact into connection-local ordered events. Historical jobs replay once; a live job follows file growth until its job status is finished. HTTP owns authentication, headers and request parsing.

func StreamJob

func StreamJob(ctx context.Context, w io.Writer, flusher http.Flusher, jobs StreamSource, id string, res job.JobResult, live bool, opts StreamOpts)

StreamJob serves the Server-Sent Events body for a single job: incremental stdout/stderr (`log` events) plus `status` events on every status change, and a final `end` event once the job reaches a terminal state (web-T3).

The caller (HTTP handler) owns parsing the request, resolving the job (res + live), checking flushability and writing the SSE response headers + opening comment; StreamJob then writes SSE frames straight to w (flushing via flusher) until the job is terminal or the client disconnects (ctx done / write error).

Status/event/interaction frames are event-driven (no DB polling): the initial replay reads them once, then they are re-read only when the job service signals a change. Only the log files are tailed on a short timer.

It works for both live jobs (in-memory, status re-read on change) and historical jobs surviving a restart (status static — logs are replayed and the stream closed immediately).

func TailChunk

func TailChunk(path string, offset int64, limit int) (chunk []byte, next int64, rotated bool)

TailChunk is TailFrom bounded to at most limit bytes (limit <= 0 means unbounded). When the read stops short of EOF the cut is moved back to a UTF-8 rune boundary, so a multi-byte character is never split across two frames.

func TailFrom

func TailFrom(path string, offset int64) (chunk []byte, next int64, rotated bool)

TailFrom reads the bytes of path starting at byte offset, returning the new chunk, the next offset (offset+len(chunk)) and a rotated flag. A missing file (job not yet started, or stream never produced) yields an empty chunk and the unchanged offset, so callers can keep polling without erroring.

rotated is true when the file is now smaller than offset — i.e. the live log was rotated/truncated under us (C4). In that case the caller should emit a rotation marker and re-read from offset 0; the returned chunk is empty.

func TailLinesOffset

func TailLinesOffset(path string, n int) int64

TailLinesOffset returns the byte offset where the last n lines of path begin (a trailing newline does not count as an extra line). It never looks back more than tailScanLimit bytes; a missing file or n <= 0 yields 0.

func TurnCount added in v0.214.0

func TurnCount(res job.JobResult) int

TurnCount is the number of turns a job's transcript has, 0 when it has none. It only counts lines (bounded scan), so it is cheap enough for the job detail response.

Types

type ACPStreamOpts

type ACPStreamOpts struct {
	TailEvents int
	// WorkerProtocol reports the wire protocol of a worker's LIVE connection
	// (ok=false when offline). Nil when this server runs no hub. It decides whether
	// a live worker job's structured record can arrive at all (gofer-e2x7).
	WorkerProtocol func(workerID string) (int, bool)
	// PromptAttachments, when set, returns the attachments the n-th prompt (1-based, in
	// the order the record holds them) was sent with; the value (non-nil) rides on that
	// prompt event as `attachments`.
	PromptAttachments func(n int) any
}

ACPStreamOpts carries request parameters already validated by the HTTP layer.

type EventFrame

type EventFrame struct {
	Seq    int64  `json:"seq"`
	Type   string `json:"type"`
	Detail string `json:"detail,omitempty"`
	At     int64  `json:"at"`
}

EventFrame is the JSON payload of an `event` SSE event (E13): one append-only lifecycle event (job.submitted / job.running / job.terminal / interaction.* / …). detail is the raw detail_json string (may be empty); the frontend parses it. seq is the cursor the frontend dedups/orders on.

type InteractionFrame

type InteractionFrame struct {
	Action      string          `json:"action"`
	Interaction job.Interaction `json:"interaction"`
}

InteractionFrame is the JSON payload of an `interaction` SSE event (web-P2 W1): the action derived from the interaction's current status (open/answered/ cancelled) plus the full interaction snapshot.

type JobTranscriptPage added in v0.214.0

type JobTranscriptPage struct {
	Source    string              `json:"source"`
	Mode      string              `json:"mode"`
	Total     int                 `json:"total"`
	Turns     []JobTranscriptTurn `json:"turns"`
	Truncated bool                `json:"truncated,omitempty"`
	Next      *TranscriptCursor   `json:"next,omitempty"`
}

JobTranscriptPage is one response. Next, when set, is the cursor of the rest.

func JobTranscript added in v0.214.0

func JobTranscript(res job.JobResult, opts TranscriptOpts) (JobTranscriptPage, error)

JobTranscript reads one page of the job's transcript. The job's location comes from its stored result (never from the caller).

type JobTranscriptTurn added in v0.214.0

type JobTranscriptTurn struct {
	Turn   int    `json:"turn"`
	Role   string `json:"role,omitempty"`
	Prompt string `json:"prompt,omitempty"`
	Text   string `json:"text,omitempty"`
	// Offset is where Text starts inside the turn's text (non-zero on a continued page).
	Offset int `json:"offset,omitempty"`
	// Chars is the turn text's total size in bytes (after secret redaction; in the
	// outline, the stored size, since only the previewed head is redacted there).
	Chars   int            `json:"chars"`
	Preview string         `json:"preview,omitempty"`
	Tools   map[string]int `json:"tools,omitempty"`
	Tokens  int64          `json:"tokens,omitempty"`
	Error   string         `json:"error,omitempty"`
	// Truncated reports that the capture itself cut this turn's text.
	Truncated  bool     `json:"truncated,omitempty"`
	Matches    []string `json:"matches,omitempty"`
	MatchCount int      `json:"match_count,omitempty"`
}

JobTranscriptTurn is one turn of a page. Which fields are set depends on the mode: outline sets Chars / Preview / Prompt (a preview), turns / head / tail set Text (and Prompt for an ACP turn), search sets Matches.

type LogFrame

type LogFrame struct {
	Stream string `json:"stream"`
	Seq    int    `json:"seq"`
	Text   string `json:"text"`
	// Off is the byte offset in the log file right after this frame's text. A
	// client that started from ?tail uses it (not a running byte count) as the
	// resume offset (?from / ?stderr_from) when it reconnects.
	Off int64 `json:"off"`
}

LogFrame is the JSON payload of a `log` SSE event: which stream the bytes came from, a monotonic sequence number and the newly appended text.

type RotatedFrame

type RotatedFrame struct {
	Stream string `json:"stream"`
	Seq    int    `json:"seq"`
}

RotatedFrame is the JSON payload of a `log-rotated` SSE event (C4): the underlying log file rotated (shrank / our offset now points past EOF), so the frontend must clear its buffered text for that stream and continue from the fresh file. The read offset is reset to 0 server-side; seq keeps advancing.

type StreamOpts

type StreamOpts struct {
	// StdoutFrom is the byte offset to resume stdout from (?from);  A zero/negative value starts from the beginning.
	StdoutFrom int64
	// StderrFrom is the byte offset to resume stderr from (?stderr_from); a
	// zero/negative value starts from the beginning (or ?tail).
	StderrFrom int64
	// TailLines, when > 0, starts each stream at the beginning of its last
	// TailLines lines instead of byte 0 (?tail), so a viewer does not have to
	// replay a multi-megabyte log to see where the job is now. StdoutFrom wins
	// for stdout when both are set.
	TailLines int
}

StreamOpts carries the per-request stream parameters resolved by the HTTP handler before delegating the SSE loop to StreamJob.

type StreamSource

type StreamSource interface {
	Get(id string) (job.JobResult, bool)
	GetPersistedInteractions(base, jobID string) ([]job.Interaction, error)
	ListJobEvents(jobID string, sinceSeq int64) ([]jobstore.JobEvent, error)
	WatchJob(id string) (<-chan struct{}, func())
}

StreamSource is the slice of *job.Service the SSE loop needs. It is an interface so tests can count reads (proving an idle stream issues no DB queries).

type TranscriptCursor added in v0.214.0

type TranscriptCursor struct {
	Turn   int `json:"turn"`
	Offset int `json:"offset"`
}

TranscriptCursor continues a read: the turn to resume at and the byte offset inside that turn's text.

func (TranscriptCursor) String added in v0.214.0

func (c TranscriptCursor) String() string

type TranscriptOpts added in v0.214.0

type TranscriptOpts struct {
	Mode     string
	From, To int // turns (From..To, 1-based, inclusive)
	N        int // head / tail
	Search   string
	Cursor   TranscriptCursor
}

TranscriptOpts is a validated TranscriptQuery.

func ParseTranscriptQuery added in v0.214.0

func ParseTranscriptQuery(q TranscriptQuery) (TranscriptOpts, error)

ParseTranscriptQuery validates q: the modes are mutually exclusive, ranges and counts are bounded, the search term is a non-empty literal of at most TranscriptMaxSearch runes.

type TranscriptQuery added in v0.214.0

type TranscriptQuery struct {
	Outline bool
	Turns   string // "A-B" (or "A" for one turn)
	Head    string
	Tail    string
	Search  string
	// Cursor is "turn:offset" from a previous page's Next.
	Cursor string
}

TranscriptQuery is the raw, string-typed request (what the HTTP query / MCP input carries). Exactly one of Outline / Turns / Head / Tail / Search may be set; none means outline.

type TranscriptTurn added in v0.162.0

type TranscriptTurn struct {
	// User is the turn's prompt, empty when the read window began in the middle of a
	// reply (the prompt is behind the cut).
	User string
	// UserTruncated reports that the runner itself cut the prompt (acp.jsonl keeps
	// the first 8000 runes of one prompt).
	UserTruncated bool
	// Reply is the turn's assistant text, message blocks joined by a blank line.
	Reply string
}

TranscriptTurn is one prompt turn of a job's ACP structured record (artifacts/acp.jsonl): the prompt the agent was sent and the assistant text that followed it before the next prompt. It is the same projection the workbench conversation reads over the ACP stream (gofer-chd9): one normalizer keeps the two views from drifting apart.

type TranscriptWindow added in v0.162.0

type TranscriptWindow struct {
	// Turns are the prompt turns inside the window, in file order.
	Turns []TranscriptTurn
	// Omitted reports that the read did not start at the file's beginning: whatever
	// came before the first turn here was not read, so the window opens
	// mid-conversation.
	Omitted bool
	// Bytes is how much of the file the read consumed, so a caller budgeting its
	// reads over a whole session can subtract it.
	Bytes int64
}

TranscriptWindow is one bounded read of a job's transcript.

func ReadTranscript added in v0.162.0

func ReadTranscript(res job.JobResult, maxBytes int) TranscriptWindow

ReadTranscript reads at most maxBytes of one job's acp.jsonl and projects it into prompt turns. maxBytes <= 0 reads the whole file; otherwise the read keeps the file's TAIL, because the recent turns are the ones a reader wants, and reports Omitted.

A missing file, an unreadable one, or a job that writes no structured record (an exec or plain-CLI agent) yields an empty window — never an error: the caller falls back to the job's stored request.

Jump to

Keyboard shortcuts

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