Documentation
¶
Overview ¶
Package background owns the process-local registry of background tasks that outlive the Tool call that started them. A watch's stdout runs through the line pipeline that turns it into bounded, model-visible events; a backgrounded command writes both streams to its log and reports once, when it completes.
Registry state is runtime state, never persisted: a running task does not survive a restart, and nothing about it rides the subagent execution plan.
Index ¶
- Constants
- Variables
- func BoundTaskOutputText(text string) (string, bool, int64)
- func MonitorBatchText(events []Event, toolHint string) string
- func MonitorCompletionText(completion Completion) string
- func MonitorRunningWarning(running []Snapshot, now time.Time, killToolName string) string
- func RenderMultiTaskOutputBody(mode string, records []TaskOutput, summary string) string
- func RenderTaskOutputBody(record TaskOutput) string
- func ShellCompletionText(completion Completion) string
- func TotalTruncationHint(total int64) string
- type Completion
- type Event
- type KillSource
- type Kind
- type LineProcessor
- type Observer
- type Options
- type Outcome
- type Registry
- func (r *Registry) CancelOwned(owner string, source KillSource) int
- func (r *Registry) Kill(id string, source KillSource) Outcome
- func (r *Registry) Launch(parent context.Context, request Request) (Snapshot, error)
- func (r *Registry) List() []Snapshot
- func (r *Registry) OutputPath(id string) (string, bool)
- func (r *Registry) Reap(ctx context.Context) error
- func (r *Registry) Result(id string) (execution.Result, bool, error)
- func (r *Registry) ResultTaken(id string) bool
- func (r *Registry) Snapshot(id string) (Snapshot, bool)
- func (r *Registry) Tail(id string, limit int64) (string, bool)
- func (r *Registry) TaskOutput(id string) TaskOutput
- func (r *Registry) TaskOutputs(ids []string) []TaskOutput
- func (r *Registry) Wait(ctx context.Context, ids []string, waitAny bool, budget time.Duration) ([]TaskOutput, WaitOutcome)
- type Request
- type Snapshot
- type Start
- type Subject
- type TaskOutput
- type WaitHint
- type WaitOutcome
Constants ¶
const ( // LineLimit bounds the text of one event line. LineLimit = 500 // BatchLimit bounds one debounced batch: the lines one tick collected, // joined by newlines. BatchLimit = 3_000 // BufferLimit bounds the unterminated line buffer. The buffer keeps its // tail, so a script that never emits a newline cannot grow memory. BufferLimit = 1 << 20 // ReadLimit bounds how many bytes one tick consumes from the output file. ReadLimit = 1 << 20 // PollInterval is the pipeline's debounce tick. It is a poll interval, not // a coalescing window: lines read inside one tick share a batch, and a line // read in the next tick is a separate event. PollInterval = 200 * time.Millisecond )
Pipeline bounds. Each is an independent limit, and each is byte-based: a limit is a byte budget, and a truncation never splits a rune. They are additional to the execution limits, not a replacement for them.
const ( // RateLimitCapacity is the token bucket's size. RateLimitCapacity = 10 // RateLimitRefill is the interval that refills one token. RateLimitRefill = 2 * time.Second // AutoKillThreshold is how long suppression must last before the pipeline // stops itself. AutoKillThreshold = 30 * time.Second )
Rate limiting constants. The bucket refills one token per interval and starts full, so a short burst is free and a sustained one is not.
const ( StatusInitializing = "initializing" StatusRunning = "running" StatusCompleted = "completed" StatusFailed = "failed" StatusCancelled = "cancelled" StatusTimedOut = "timed_out" StatusNotFound = "not_found" )
Task-output status words. They are the reference's closed vocabulary, chosen in this order: a kill, then the task's own deadline, then a clean exit, then anything else. `initializing` and `cancelled` are the two words a delegated child adds: a child that has a durable lifecycle but no live run is initializing, and a cancelled or interrupted child is cancelled.
const KillTaskToolName = "kill_background_task"
KillTaskToolName is the model-visible name of the Tool that stops one background task. The monitor description, the start receipt, the running-task warning, and the catch-up notice all name it, so it has one definition.
const TaskOutputToolName = "get_task_output"
TaskOutputToolName is the model-visible name of the Tool that reads one background task's output by id. The completion text points at it, so it has one definition beside the stop Tool's.
Variables ¶
var ( // ErrInvalid means a registry request cannot be represented safely. ErrInvalid = errors.New("coding background: invalid registry request") // ErrClosed means the owning Runtime has already been reaped. ErrClosed = errors.New("coding background: registry closed") )
Errors reported by the background registry.
Functions ¶
func BoundTaskOutputText ¶
BoundTaskOutputText bounds an in-memory body at the same taskOutputBytes a task log is bounded at, so a delegated child's result can never grow a Tool result without limit. Past the bound the dump is the first previewBytes cut at a rune boundary plus the path-free footer: a child's result has no file to point at, and a hint that promised one would be a dead pointer. The returned count is the body's real length, before the bound applied.
func MonitorBatchText ¶
MonitorBatchText renders drained monitor events as one model-visible batch. A single event uses the single-event shape; more than one uses the counted, per-monitor shape. It returns "" when there is nothing to deliver.
func MonitorCompletionText ¶
func MonitorCompletionText(completion Completion) string
MonitorCompletionText renders one monitor's single model-visible completion. The identity line prefers the description over the raw command, so the command is never echoed. The text points at the task-output Tool instead of inlining the log: the log is read by id, bounded, and the pane keeps its own tail for the watch page.
func MonitorRunningWarning ¶
MonitorRunningWarning renders the note a monitor start carries while other background tasks are still running. A running task's elapsed time is measured against now.
func RenderMultiTaskOutputBody ¶
func RenderMultiTaskOutputBody(mode string, records []TaskOutput, summary string) string
RenderMultiTaskOutputBody renders several records as the reference's multi shape: one `=== Multi-wait (<mode>) ===` header, one entry per record, and the completed-count summary.
func RenderTaskOutputBody ¶
func RenderTaskOutputBody(record TaskOutput) string
RenderTaskOutputBody renders one record's model-facing body: the reference's `=== Task ===` block, then its output, then the truncation hint.
func ShellCompletionText ¶
func ShellCompletionText(completion Completion) string
ShellCompletionText renders one shell task's single model-visible completion: the status, the identity line, and the pointer at the task-output Tool. A shell call carries no description, and the command is never echoed.
func TotalTruncationHint ¶
TotalTruncationHint is the short marker a truncated record without a file behind it carries, so its structured hint reports the real length instead of naming a Tool and a path that do not exist.
Types ¶
type Completion ¶
type Completion struct {
Snapshot Snapshot
// Killed reports that a kill stopped the task rather than its own exit.
Killed bool
// Source names who stopped the task. It is meaningful only when Killed is
// set, and it decides whether the terminal report still wakes the model.
Source KillSource
// KillResultDelivered reports that a Tool result already told the model the
// kill outcome, so the terminal completion must not wake the model again.
KillResultDelivered bool
}
Completion is one task's single terminal report.
type Event ¶
type Event struct {
TaskID string
Description string
// Text is the event body: the script's own output, a catch-up notice, or
// the auto-kill message.
Text string
// Wrapped is the wire text carried into the conversation.
Wrapped string
}
Event is one model-visible background event.
type KillSource ¶
type KillSource uint8
KillSource identifies who stopped a task, and therefore whether its terminal completion may wake the model.
const ( // KillModel is the model's own stop Tool. It already produced a Tool // result, so its completion is delivered only when no result reached the // model. KillModel KillSource = iota // KillUser is the tasks-pane control or Runtime teardown. No Tool result // carries the outcome, so the completion still wakes the model. KillUser // KillPromptEnd is the cancel of the interaction that spawned the task. No // turn remains to report it and the user just interrupted, so its // completion produces no queue record at all. KillPromptEnd )
type Kind ¶
type Kind string
Kind identifies what one registered background task runs.
const ( // KindMonitor watches a long-running script and reports its stdout lines. KindMonitor Kind = "monitor" // KindShell runs one command that outlived the Tool call that started it. // It writes both streams into its log and emits no events: a command has no // event contract, and its completion is the single model-visible report. KindShell Kind = "shell" )
Supported background task kinds.
type LineProcessor ¶
type LineProcessor struct {
// contains filtered or unexported fields
}
LineProcessor assembles raw output chunks into complete lines and bounds the text of each one. It retains only the tail of an unterminated line.
func (*LineProcessor) Flush ¶
func (p *LineProcessor) Flush() (string, bool)
Flush returns the remaining unterminated line once, at task completion. A buffer that is empty, or holds only space, produces nothing.
func (*LineProcessor) Push ¶
func (p *LineProcessor) Push(chunk []byte) []string
Push appends one raw chunk and returns the complete lines it closed, in order, each already truncated. An empty line produces nothing.
type Observer ¶
type Observer interface {
// BackgroundStarted reports one task registration, so a frontend can list
// the task while it runs.
BackgroundStarted(Snapshot)
// BackgroundEvent delivers one streamed event.
BackgroundEvent(Event)
// BackgroundCompleted delivers one task's single terminal report.
BackgroundCompleted(Completion)
}
Observer receives one Registry's model-visible output.
type Options ¶
type Options struct {
// OutputDir is the directory each task's raw output file is written to: the
// session's own terminal directory, never the workspace.
OutputDir string
// Observer receives events and completions. A nil Observer drops them.
Observer Observer
// KillToolName is the model-visible name of the Tool that stops a task,
// substituted into the catch-up notice.
KillToolName string
// OutputBytes bounds one task's output file. It is the default for every
// kind.
OutputBytes int64
// ShellOutputBytes bounds a shell task's output file. A command's log is
// the command's whole output, so it takes the shell operation's own ceiling
// rather than the narrower monitor cap. Zero uses OutputBytes.
ShellOutputBytes int64
// TailBytes bounds the output tail the pane's inspect read shows. A
// completion inlines no output: it points at the task-output Tool.
TailBytes int64
// Now returns the current time; nil uses time.Now.
Now func() time.Time
}
Options configure one background registry.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry owns every background task of one Runtime.
func NewRegistry ¶
NewRegistry constructs one Runtime's background registry.
func (*Registry) CancelOwned ¶
func (r *Registry) CancelOwned(owner string, source KillSource) int
CancelOwned stops every live task whose owner is the given interaction id and reports how many it stopped. An empty owner matches nothing, so a task registered without an owner is never cancelled by an interaction boundary.
func (*Registry) Kill ¶
func (r *Registry) Kill(id string, source KillSource) Outcome
Kill stops one task. A running task is killed, a task that already ended is reported as already_exited, and an unknown id as not_found.
func (*Registry) Launch ¶
Launch registers one task and starts its process. It returns the task's snapshot as soon as a goroutine owns the run, so a Tool call returns a receipt without waiting for the process to end.
func (*Registry) OutputPath ¶
OutputPath returns the task's own log path, `<dir>/<id>.log`. It is the path the task-output record reports as output_file and the only path the read Tool admits from outside the workspace.
func (*Registry) Reap ¶
Reap stops every live task and waits for their pipelines to end. Runtime teardown calls it, so no task outlives its session.
func (*Registry) Result ¶
Result returns one finished task's own executor result and its run error, which is what a positive block renders a command that ended inside the wait from. A task that is still running, or an unknown id, reports false.
func (*Registry) ResultTaken ¶
ResultTaken reports whether a task's result is already the model's: a read is standing by for it, or a read already returned its terminal record. The delivery path consults it live, so a result is carried by exactly one surface however the two order.
func (*Registry) Snapshot ¶
Snapshot returns one task's current view. A task that is still running has a zero End and a zero ExitCode.
func (*Registry) Tail ¶
Tail returns a bounded, sanitized tail of one task's own output. It is what the tasks pane's inspect action shows; the model's delivery stays the events.
func (*Registry) TaskOutput ¶
func (r *Registry) TaskOutput(id string) TaskOutput
TaskOutput returns one task's record. An unknown id yields a record with Found == false rather than an error, so a multi read can render the unknown entry beside the known ones. A terminal record is marked taken: the read is now the surface that carries it.
func (*Registry) TaskOutputs ¶
func (r *Registry) TaskOutputs(ids []string) []TaskOutput
TaskOutputs returns one record per id, ordered as the ids were asked.
func (*Registry) Wait ¶
func (r *Registry) Wait( ctx context.Context, ids []string, waitAny bool, budget time.Duration, ) ([]TaskOutput, WaitOutcome)
Wait resolves every id immediately, then blocks on the still-running ones until they all end, until any one ends when waitAny is set, or until the budget or ctx elapses. It is event-driven: each still-running task's own ended channel is a select case, so nothing polls.
A waiter registers on a still-running task under the registry lock before it blocks, so the delivery path sees ResultTaken while the wait is inside its call. On return the registration is released and every terminal record is marked taken by TaskOutputs, so the delivery path sees ResultTaken after the wait as well. Exactly one surface therefore carries the outcome, whichever of the two the delivery reaches first.
type Request ¶
type Request struct {
Kind Kind
Command string
Description string
CWD string
Owner string
// Timeout is the task's own deadline. It is ignored when NoDeadline is set.
Timeout time.Duration
// NoDeadline marks a task that runs until it exits, is killed, or the
// Runtime closes.
NoDeadline bool
Start Start
}
Request describes one background task to register and start.
type Snapshot ¶
type Snapshot struct {
ID string
Command string
Description string
CWD string
Start time.Time
End time.Time
ExitCode int
Signal string
Completed bool
// Killed reports that a kill stopped the task, whatever the source.
Killed bool
// TimedOut reports that the task's own deadline ended it. A kill wins over
// the deadline, so a killed task is never reported as timed out.
TimedOut bool
Kind Kind
Owner string
}
Snapshot is one immutable view of a registered background task. It is the single per-task record every surface reads: the kill Tool, the task-output Tool, the tasks pane, the Stop hook, and telemetry.
type Start ¶
Start launches one registered task's process and streams its output into the sink. It returns when the process ends, when ctx is canceled, or when the sink fails.
type Subject ¶
type Subject string
Subject names what one output record describes. A background task and a delegated child share the record shape, so one renderer serves both; the subject is what lets the wait hint address the right thing, because only a child can be told to stop. The zero value reads as a task.
type TaskOutput ¶
type TaskOutput struct {
// Found is false for an id the registry does not know.
Found bool
// Subject is what the record describes, so the wait hint addresses a task
// or a child in its own words. The zero value reads as a task.
Subject Subject
TaskID string
Command string
Status string
ExitCode *int
Started time.Time
Ended time.Time
DurationSecs float64
Output string
OutputFile string
Truncated bool
TruncationHint string
RawOutputBytes int64
}
TaskOutput is one task's model-visible output record. Its fields are the reference's, split the way every coding Tool splits its output: the record rides the result header, and its body is the reference's own rendering.
func ApplyWaitHint ¶
func ApplyWaitHint( record TaskOutput, hint WaitHint, requested, waited time.Duration, ) TaskOutput
ApplyWaitHint appends the reference's wait words to a still-working record. A terminal record is returned unchanged: its output is the whole answer.
func NotFoundTaskOutput ¶
func NotFoundTaskOutput(id string) TaskOutput
NotFoundTaskOutput is the record an unknown id yields. It carries the reference's `not_found` status and sentence, so a multi read renders the unknown entry beside the known ones instead of an empty one.
func (TaskOutput) Live ¶
func (r TaskOutput) Live() bool
Live reports whether the record's subject is still working, so a wait hint belongs on its body and a terminal status word does not.
type WaitHint ¶
type WaitHint uint8
WaitHint classifies why a running record's wait returned, so the record can carry the reference's own wait words.
type WaitOutcome ¶
type WaitOutcome string
WaitOutcome classifies how a blocking read ended.
const ( // WaitOutcomeCompleted means the wait condition was met. WaitOutcomeCompleted WaitOutcome = "completed" // WaitOutcomeDeadline means the budget elapsed first. WaitOutcomeDeadline WaitOutcome = "deadline" // WaitOutcomeCanceled means the caller's context ended first. WaitOutcomeCanceled WaitOutcome = "canceled" )
Supported wait outcomes.