task

package
v1.6.12 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package task is a unified registry for background tasks. Tools (shell commands, sub-agent dispatch, etc.) register their long-running work via a shared Runtime so callers can list and cancel them through one surface.

Index

Constants

View Source
const CompletedTag = "background-task-completed"

CompletedTag is the XML-style wrapper tag used in the AgentMessage emitted by ToAgentMessage().

View Source
const MaxAgentDepth = 5

MaxAgentDepth caps how deep sub-agents may nest. The main agent is depth 0; a sub-agent it spawns is depth 1; a sub-agent inside that would be depth 2. Today the subagent tool is filtered out of every sub-agent's pool, so depth is structurally capped at 1 — this constant is defense in depth for when team support lands and peer agents gain a spawn channel.

5 is high enough to permit legitimate fan-out but low enough to catch runaway recursion before it burns through tokens.

Variables

This section is empty.

Functions

func DepthFromContext added in v1.6.10

func DepthFromContext(ctx context.Context) int

DepthFromContext returns the current agent's depth — 0 for the main agent, n+1 inside a depth-n sub-agent. Unset (top-level) ctx returns 0.

func WithDepth added in v1.6.10

func WithDepth(ctx context.Context, depth int) context.Context

WithDepth threads `depth` into ctx so a sub-agent spawned via this ctx can read its caller's depth and reject overly deep nesting.

Types

type AppendStatus added in v1.6.10

type AppendStatus int

AppendStatus enumerates the outcomes of AppendPending. We return a status instead of (bool, error) because the caller (a tool) needs to format three distinct user-visible messages: "queued", "not found", and "task already finished" — each implies a different follow-up.

const (
	AppendOK       AppendStatus = iota // message queued
	AppendNotFound                     // no entry with that ID
	AppendTerminal                     // entry exists but already in terminal state
)

type Entry

type Entry struct {
	ID          string
	Type        Type
	Description string
	Status      Status
	StartedAt   time.Time
	EndedAt     time.Time
	OutputFile  string // path to output file on disk
	Error       string
	ExitCode    int // shell: process exit code
	ToolCount   int // number of tool calls executed
	Depth       int // nesting depth: 1 for tasks spawned by the main agent; n+1 inside a depth-n task. See MaxAgentDepth.

	// Shell-specific
	PID     int
	Command string

	// SubAgent-specific (also used by teammate, which shares the underlying runAgent loop)
	Agent     string
	Prompt    string // original task prompt
	Result    string // final assistant text from the sub-agent
	TokensIn  int
	TokensOut int

	// Teammate-specific. Identity is non-nil iff Type == TypeTeammate.
	// IsIdle flips true between turns when the teammate is waiting in its mailbox
	// channel for the next message.
	Identity *Identity
	IsIdle   bool
	// contains filtered or unexported fields
}

Entry is the unified representation of any background task. Both shell tools and sub-agent tools register entries through a shared Runtime.

func (*Entry) SetCancel

func (e *Entry) SetCancel(fn func())

SetCancel sets the cancellation function for this task entry. Called during registration; only Stop()/StopAll() invoke it.

type Identity added in v1.6.10

type Identity struct {
	AgentID         string // "researcher@my-team"
	AgentName       string // "researcher"
	TeamName        string
	Color           string
	ParentSessionID string
}

Identity is the team-aware identity carried by a teammate Entry. nil for non-teammate entries (shell, subagent). Lives in this package rather than agentcore/team to avoid a task↔team import cycle: team needs to read/store Entry.Identity, and task needs to recognise teammate-typed entries for lifecycle handling.

type Notification

type Notification struct {
	TaskID      string
	Type        Type
	Status      Status
	Description string

	// SubAgent
	Agent  string
	Result string // final assistant text — lets parent continue without IO
	Usage  *Usage

	// Shell
	Command  string
	ExitCode *int

	// Common
	OutputFile string // disk path to the full transcript / log
	Error      string
}

Notification is the payload delivered to the calling agent when a background task finishes. The parent agent receives this wrapped as XML so it can both react immediately to <result> and read <output-file> on demand.

func NotificationFromEntry

func NotificationFromEntry(e *Entry) Notification

NotificationFromEntry converts a task entry into a notification payload.

func (Notification) ToAgentMessage

func (n Notification) ToAgentMessage() agentcore.AgentMessage

ToAgentMessage wraps the notification as a user-role AgentMessage that the parent agent can consume as a follow-up. The XML is hand-formatted with nested elements (instead of JSON-in-XML) because LLMs parse structured XML reliably and the format mirrors patterns Claude already recognises.

type Runtime

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

Runtime is a unified registry for background tasks.

func NewRuntime

func NewRuntime() *Runtime

NewRuntime creates an empty runtime.

func (*Runtime) AppendPending added in v1.6.10

func (r *Runtime) AppendPending(id, msg string) AppendStatus

AppendPending queues a message for delivery to a sub-agent's next steering tick. Returns the outcome so the caller can choose its error wording.

Terminal tasks are NOT auto-resumed here — resuming from disk transcripts is a later capability. Today the parent agent gets AppendTerminal back and reports the failure to the user.

func (*Runtime) DrainPending added in v1.6.10

func (r *Runtime) DrainPending(id string) []string

DrainPending returns and clears the queued messages for the given task. Returns nil when there is nothing queued so callers can short-circuit. Called from the sub-agent loop's steering hook — see subagent.runAgent.

func (*Runtime) Get

func (r *Runtime) Get(id string) *Entry

Get returns a snapshot of a single task, or nil if not found.

func (*Runtime) List

func (r *Runtime) List() []Entry

List returns snapshots of all tasks, sorted by creation time.

func (*Runtime) NextID

func (r *Runtime) NextID(prefix string) string

NextID generates a sequential task ID with the given prefix (e.g. "shell", "bg").

func (*Runtime) Register

func (r *Runtime) Register(entry *Entry)

Register adds a task entry. The caller is responsible for populating all fields.

func (*Runtime) Stop

func (r *Runtime) Stop(id string) bool

Stop cancels a running task by ID. Returns true if a running task was found and its cancel function was invoked. The background goroutine is responsible for writing the terminal status and EndedAt after observing the cancellation.

func (*Runtime) StopAll

func (r *Runtime) StopAll() int

StopAll cancels all running tasks. Returns the number cancelled.

func (*Runtime) Update

func (r *Runtime) Update(id string, fn func(e *Entry)) bool

Update applies a mutation function to a task entry under the lock. Returns false if the task is not found.

type Status

type Status string

Status represents the lifecycle state of a background task.

const (
	Running   Status = "running"
	Completed Status = "completed"
	Failed    Status = "failed"
	Killed    Status = "killed"
)

func (Status) IsTerminal added in v1.6.10

func (s Status) IsTerminal() bool

IsTerminal reports whether a task has reached a terminal state.

type Type

type Type string

Type distinguishes the origin of a background task.

const (
	TypeShell    Type = "shell"
	TypeSubAgent Type = "subagent"
	TypeTeammate Type = "teammate"
)

type Usage added in v1.6.10

type Usage struct {
	TotalTokens int
	ToolUses    int
	DurationMs  int64
}

Usage summarises a sub-agent's resource consumption for the notification.

Jump to

Keyboard shortcuts

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