streaming

package
v0.193.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 15 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 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 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.

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 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 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