pool

package
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package pool manages the global agent subprocess slot count + FIFO queue. Files:

  • buffer.go — per-session message buffer (drain on slot grant)
  • pool.go — slot allocation, FIFO queue, factory hookup

Buffer rationale: when a session is queued (no slot), incoming user messages must not vanish — they're appended to the on-disk PendingInput list (so a wick restart preserves them) AND held in a transient buffer here. When the slot is granted, the entire buffer is drained as one combined input to the spawned agent. See agents-design.md §5.1.1.

Index

Constants

View Source
const DefaultTurnIdleTimeout = 20 * time.Minute

DefaultTurnIdleTimeout is the mid-turn idle ceiling wick runs with (PoolConfig.TurnIdleTimeout): long enough for a model thinking over a long context or a slow background job, short enough that a hung CLI still gives its slot back.

View Source
const ListenDocName = "LISTEN.md"

ListenDocName is the file that shapes how an agent listens: one wick-wide default at the agents root, one per agent in its project folder.

View Source
const ResumeDroppedNotice = "" /* 185-byte string literal not displayed */

ResumeDroppedNotice is what the user reads when healStaleResume drops a resume id the provider could no longer find.

Variables

View Source
var ErrAgentNotActive = errors.New("agent not active in pool")

ErrAgentNotActive means the requested sessionID+agentName had no live entry in the pool. Callers MUST treat this as a distinct outcome, not a failure: it covers "already finished", "never spawned", and "still queued". A queued sub-agent is cancelled by dropping it from the queue, not by killing a process that does not exist yet.

View Source
var ErrHandedOver = errors.New("wick is handing over to a new build: this process takes no new turns; the message goes to the new process")

ErrHandedOver refuses a message wick itself sends (a teammate's task, a sub-agent's result, a schedule, a CLI report…) to a process that has handed over to a new build and is only draining: the successor runs that session, so a turn here would run it twice.

Functions

func AgentListenDocPath added in v1.18.0

func AgentListenDocPath(layout agentconfig.Layout, projectID string) string

AgentListenDocPath is projectID's LISTEN.md, "" when the project has no folder.

func MachineSource added in v1.18.0

func MachineSource(source string) bool

MachineSource reports whether a Send source is one no person typed and no teammate asked for (StopAfterMachineTurn). "failover" re-sends a turn whatever started it, so send leaves the turn's mark as it was for it.

func ReadListenDoc added in v1.18.0

func ReadListenDoc(path string) string

ReadListenDoc reads up to listenDocMax bytes of path; "" when it is missing or path is empty.

func ShouldRespawn added in v0.39.2

func ShouldRespawn(reason provider.ExitReason, attempts int) bool

ShouldRespawn reports whether an exit warrants an automatic restart, given how many attempts have already been made in the current window.

Deliberately narrow. Only deaths with NO good explanation qualify:

  • ExitClean: the process finished its work. Restarting would run it again for no reason.
  • ExitStopped: someone asked for this — a preempt, a session change, or a shutdown. Restarting would fight the operator.
  • ExitIdle: the idle TTL reclaimed it on purpose; the next message spawns a fresh one anyway.
  • ExitRespawn: an internal turn boundary, not a death at all.
  • ExitOOM: the agent exceeded its memory limit. Restarting repeats the work that caused it — the loop this whole subsystem exists to prevent. The operator gets told instead.

That leaves ExitError: a crash, a signal, a vanished process. Those are the ones worth trying again.

func WickListenDocPath added in v1.18.0

func WickListenDocPath(layout agentconfig.Layout) string

WickListenDocPath is where the wick-wide LISTEN.md goes: the agents root.

Types

type ActiveEntry

type ActiveEntry struct {
	SessionID    string
	AgentName    string
	ProviderType string // resolved provider type (claude / codex / gemini)
	ProviderName string // instance name within that type
	CWD          string // resolved workspace path, used by RouteByCWD
	// CallerUserID is the wick user this subprocess actually runs AS — the
	// identity its MCP credential was minted for, baked into the argv and
	// fixed for the life of the process. Not the session owner: on a shared
	// session the two differ, and the spawn's reach follows this one.
	//
	// A spawn no human woke (a delegation result, a schedule fire) still
	// carries the owner its credential was minted for. Empty only when the
	// session has no owner either.
	CallerUserID   string
	PID            int
	Queued         int  // messages waiting after the current turn (RespawnQueue)
	Respawns       bool // one process per turn (codex): a dead PID between turns is normal, not a zombie
	Lifecycle      string
	Substate       string
	LastActive     time.Time
	InFlightEvents []store.TurnEvent
	// PartialText is the assistant text accumulated so far for the
	// in-flight turn (everything received via TextDelta but not yet
	// flushed by Done). Empty when no turn is mid-stream. Used by the
	// SSE snapshot so a refresh keeps the partial bubble visible.
	PartialText string
}

ActiveEntry is the public snapshot view of one running agent. Lifecycle / Substate / PID / LastActive are populated when the pool can read them; older callers that only check SessionID + AgentName keep working.

type AgentFactory

type AgentFactory interface {
	Build(opt FactoryOptions) (BuildResult, error)
}

AgentFactory builds an agent ready to Start. The pool wires the OnExit hook itself (so it can free the slot); the factory should not.

BuildResult.OnStarted is called by the pool right after a.Start succeeds — that's when the OS pid is known and the first user message has been drained from the buffer. Factories use it to finish writing the spawn `start` event with both fields. Optional; nil = nothing to record.

type Buffer

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

Buffer is a small per-session message queue. Operations are idempotent w.r.t. the on-disk meta.json so a crash between in-memory append and disk persist doesn't lose user input.

func NewBuffer

func NewBuffer(layout config.Layout, sessionID string) (*Buffer, error)

NewBuffer reads any pending_input persisted on disk so we resume queued messages after a wick restart.

func (*Buffer) Append

func (b *Buffer) Append(text string) error

Append adds a new line and persists it to meta.PendingInput so a crash before drain doesn't drop it.

func (*Buffer) Drain

func (b *Buffer) Drain() (string, error)

Drain returns all buffered lines joined by newline and clears the buffer (both in-memory and on-disk PendingInput). Returns "" if empty.

Nil-safe: a nil buffer drains to "". Drain is reached from bare goroutines (queue grants), where a nil deref is not a recovered request error but the whole process going down — it did, once, when a wake-path spawn arrived without a buffer. spawn now guarantees the buffer exists; this guard is the backstop for the next wiring gap.

func (*Buffer) DropHead added in v1.16.0

func (b *Buffer) DropHead(text string) (bool, error)

DropHead removes text when it is the first buffered line — a failover re-send its spawn never delivered. false = the head is something else (already drained), nothing changed.

func (*Buffer) Len

func (b *Buffer) Len() int

Len reports the buffered line count without modifying state.

func (*Buffer) Lines added in v1.16.0

func (b *Buffer) Lines() []string

Lines returns a copy of what is buffered, without draining it.

func (*Buffer) Prepend added in v1.16.0

func (b *Buffer) Prepend(texts ...string) error

Prepend puts texts, in order, ahead of everything buffered: a failover re-send is the turn the held messages came after. Nil-safe like Drain.

type BuildResult

type BuildResult struct {
	Agent     *provider.Agent
	State     *state.Machine
	Store     *store.Store
	OnStarted func(meta SpawnStartMeta)
	// MCPToken is the per-session credential baked into this spawn's argv,
	// reported back so the pool can revoke it when the subprocess dies
	// rather than leaving it valid until its TTL. Empty when the spawn used
	// the shared internal token, which is per-boot and must NOT be revoked.
	MCPToken string
	// RunAsUserID is the wick user that per-session credential was minted
	// for. Empty when no per-user credential was minted (shared token, or a
	// provider with no MCP surface).
	RunAsUserID string
}

BuildResult bundles everything Build returns. New code should pull fields from here; the bare-tuple shape is gone so we don't have to thread one more channel through every callsite when we add another hook later.

type Capacity added in v0.15.2

type Capacity struct {
	Scope     string // "global" or "type/name"
	Used      int    // active + in-flight spawns counted against this scope
	Max       int    // configured cap; 0 = unlimited (provider scope only)
	Remaining int    // slots still grantable right now (Max<=0 → -1 = unlimited)
}

Capacity is a used / max / free snapshot for one scope. Max == 0 means "unlimited" at that scope (only meaningful for the provider scope; the global cap is always a positive number after New() normalises it).

func (Capacity) Unlimited added in v0.15.2

func (c Capacity) Unlimited() bool

Unlimited reports whether this scope imposes no finite cap.

type ClaudeFactory

type ClaudeFactory struct {
	Layout    config.Layout
	Spawner   provider.Spawner // optional override; nil = real claude
	RecordRaw bool
	OnEvent   func(sessionID, agentName string, ev event.AgentEvent)
	OnExit    func(sessionID, agentName string, reason provider.ExitReason, reasonDetail string)

	// Gate (optional) attaches a static command whitelist to every spawn.
	// When non-nil, Build writes a per-session settings.json + spec
	// file to a temp dir, points the spawner at the settings file,
	// and injects WICK_GATE_SPEC into ExtraEnv so wick-gate finds
	// its config. nil = no gate (fail-open, only safe for tests).
	Gate *GateConfig
	// GateLoader (optional) is called on every Build to fetch the
	// current gate config from the live config store. Takes precedence
	// over Gate when non-nil. This lets operators toggle gate_enabled
	// or edit AllowedCmds in the UI without restarting the server.
	GateLoader func() *GateConfig
	// ToolMemoryLoader (optional) returns the ceiling for a shell command
	// the wick provider runs itself, in MB. 0 = unbounded. Read per Build
	// for the same reason as MemGuardLoader.
	ToolMemoryLoader func() int

	// MemGuardLoader (optional) returns the current memory-guard policy,
	// read on every Build so an operator can change the mode or the
	// limits in the UI without restarting the server — the same reason
	// GateLoader exists. nil, or a nil return, means the guard is off and
	// spawns behave exactly as they did before it existed.
	//
	// The per-instance ceiling is resolved here rather than by the caller,
	// since only Build knows which instance a session ended up on.
	MemGuardLoader func() *provider.MemGuard

	// PermissionModeLoader (optional) is called on every Build to read
	// the current GateConfig.PermissionMode value. Return "bypass" to
	// force --permission-mode bypassPermissions on Claude (and the
	// equivalent on codex/gemini) when no gate hook is installed.
	// Any other value (including empty) means "prompt as normal".
	PermissionModeLoader func() string

	// SystemPromptLoader (optional) returns a global system prompt
	// fragment appended to the loaded preset body on every spawn.
	// Empty string = no append. Lets operators set org-wide rules
	// (prompt-injection defenses, shared conventions) without editing
	// every preset. Preset stays the primary; this only adds to it.
	SystemPromptLoader func() string

	// SenderVisibilityLoader (optional) returns how much of a message
	// sender's identity reaches the model. Forwarded to spawners that replay
	// conversation.jsonl themselves, so a replayed turn is attributed the
	// same way the live send was. nil = store.SenderName.
	SenderVisibilityLoader func() string

	// TraceEventMaxKBLoader (optional) returns the current trace_event_max_kb
	// config value. 0 = no cap.
	TraceEventMaxKBLoader func() int

	// TraceBlobMaxMBLoader (optional) returns the current trace_blob_max_mb
	// config value. 0 = store default (10 MB).
	TraceBlobMaxMBLoader func() int

	// TraceInlineKBLoader (optional) returns the current trace_event_inline_kb
	// config value. Called on every Build so operators can change the threshold
	// without restarting the server. 0 or negative = use DefaultTraceInlineBytes.
	TraceInlineKBLoader func() int

	// ConnectorCatalogLoader (optional) returns a "## Available wick
	// connectors" markdown block listing the connectors the spawning
	// agent should prefer over hand-rolled HTTP. Wired in server.go
	// so the loader can call connectorsSvc and filter to instances
	// whose status is "ready" — connectors the operator has finished
	// configuring. Empty string = no append (no connectors ready, or
	// service unavailable). Inserted between the immutable rules and
	// the preset body so the catalog can't override either layer.
	ConnectorCatalogLoader func() string

	// TicketPointerLoader (optional) returns a short block naming the
	// ticket this session belongs to and how many notes it carries — a
	// COUNT, never the note bodies. It exists so the agent knows the
	// notes are there and reads them through the notes connector when
	// they matter, instead of the prompt growing with every note ever
	// written on a long-lived ticket. Empty string = nothing to point at
	// (no ticket, no notes) and nothing is appended.
	TicketPointerLoader func(sessionID string) string

	// LinkedChatsLoader (optional) returns the "This session" lines that
	// name the chat paired with sessionID at each Team teammate, "" for
	// none (nothing is appended).
	LinkedChatsLoader func(sessionID string) string
	// LinkedSessionsLoader (optional) returns the "Linked sessions"
	// section: the sessions linked to this one when its process starts
	// (sessionlink), "" for none. Live state rides on each turn instead.
	LinkedSessionsLoader func(sessionID string) string

	// ListenPromptLoader (optional) returns the channel's listen-mode
	// section for sessionID (Slack: the listen rules and LISTEN.md), ""
	// for none.
	ListenPromptLoader func(sessionID string) string

	// TeamPromptLoader (optional) returns the Team part of the prompt for
	// sessionID: the Team overlay plus "Who you are" for a Team agent's
	// own session, one line for a sub-agent working under one, "" for an
	// ordinary session. Spliced right after the immutable rules, before
	// any persona, so a persona cannot talk over it.
	TeamPromptLoader func(sessionID string, subAgent bool) string

	// TeamSpawnLoader (optional) returns the spawn parts of a Team
	// agent's OWN session (see TeamSpawn); false for any other session,
	// a sub-agent under a Team session included. When it answers true the
	// prompt is assembled in the Team order (see composePrompt) and
	// TeamPromptLoader is not consulted.
	TeamSpawnLoader func(sessionID string) (TeamSpawn, bool)

	// RemoteSpawnerLoader (optional) returns the spawner of a session that
	// talks to an A2A remote agent (package a2aremote): no process, each
	// turn is a call to the remote. false for any other session. It wins
	// over the provider type, so such a session never starts a local CLI.
	RemoteSpawnerLoader func(sessionID string) (provider.Spawner, bool)

	// TeamLimitsLoader (optional) returns the native-tool and Bash limits
	// of the Team agent sessionID works for — its own session or any
	// sub-agent under it, so a delegated child is held to the same limits
	// (see TeamLimits); false outside the Team.
	TeamLimitsLoader func(sessionID string) (TeamLimits, bool)

	// AdminContactLoader (optional) returns the `admin_contact` config
	// row: whom the built-in rules tell people to ask for missing access.
	// Empty = "the wick admin".
	AdminContactLoader func() string

	// PathGuardLoader (optional) returns the `path_guard` mode ("off" or
	// "block") and the `path_guard_allow` exceptions, read per spawn.
	// Nil = no path guard.
	PathGuardLoader func() (mode, allow string)

	// PathGuardBinary is the gate binary the path guard hook runs. Set on
	// its own because the guard must hold even when the approval gate is
	// off (gate_enabled=false or bypass permissions). Empty = fall back to
	// the approval gate's binary.
	PathGuardBinary string

	// SecurityPromptLoader (optional) returns the `system_prompt_security`
	// config row: admin-managed security rules every spawn carries right
	// after the immutable rules — project, Team and sub-agent sessions
	// alike. Empty = no section.
	SecurityPromptLoader func() string

	// TeamSystemPromptLoader (optional) returns the `system_prompt_team`
	// config row: a Team-only addition placed right after the shared
	// `system_prompt` in Team agent sessions. Empty = nothing added.
	TeamSystemPromptLoader func() string

	// SpawnLogger (optional) writes one jsonl per spawn under
	// `<base>/backends/spawns/`. Each spawn emits `start` on Build +
	// `exit` from the OnExit hook so the Backends UI can list spawn
	// history per backend by `ls`-ing the directory. nil = no logging.
	SpawnLogger *provider.SpawnLogger

	// MCPToken is the per-boot internal MCP secret forwarded to the
	// claude spawner so agents reach the live MCP server over loopback.
	// It maps to a synthetic ADMIN principal, so it is only a FALLBACK:
	// used when SessionMCPToken is unset, or when it declines to mint
	// (a session with no owner — legacy rows, cron, system jobs).
	MCPToken string

	// SessionMCPToken mints a per-SESSION MCP credential that authenticates
	// as the human who owns the session, instead of the shared admin
	// principal MCPToken grants. Without it, every user's spawn reaches the
	// MCP server as the same synthetic admin, so connector access control
	// and tag filtering never apply to a web chat.
	//
	// Returning ok=false means "no real owner" and the caller falls back to
	// MCPToken — an ownerless session must keep working rather than lose
	// MCP entirely. nil = per-user identity disabled (fallback for all).
	//
	// identity is the wick user the token was minted for. The pool only
	// knows the caller of the message that woke the spawn, which is empty
	// whenever no human did (a delegation result, a schedule fire) even
	// though the minter then picked the owner — so the minter, the one place
	// that decides, reports it back.
	SessionMCPToken func(sessionID, callerUserID string) (token, identity string, ok bool)

	// InstanceOverride pins a specific Instance for every Build call,
	// bypassing the provider.Find registry lookup. Tests use this to
	// inject ExtraArgs / Env without touching userconfig files.
	InstanceOverride *provider.Instance
}

ClaudeFactory is the production AgentFactory: wires a ClaudeParser + ClaudeSpawner into a fresh provider.Agent for each Build call.

The factory owns no per-spawn state; the pool calls Build once per session activation.

func (*ClaudeFactory) Build

func (f *ClaudeFactory) Build(opt FactoryOptions) (BuildResult, error)

Build returns a fresh agent + state machine + store wired for one session+agent. Caller (the pool) is responsible for calling agent.Start.

type FactoryOptions

type FactoryOptions struct {
	// CallerUserID is the wick user whose message triggered this spawn.
	// Empty = no resolved caller (cron, system job, legacy session).
	CallerUserID    string
	SessionID       string
	AgentName       string
	ProviderType    string
	ProviderName    string
	Workspace       string
	ResumeID        string
	IdleTimeout     time.Duration
	KillAfterIdle   time.Duration
	TurnIdleTimeout time.Duration
	OnEvent         func(event.AgentEvent)
	// PresetName is the preset name from session meta. Factory resolves
	// the content from disk — pool passes the name so factory avoids a
	// redundant session.Load.
	PresetName string
	// SystemAddon is free-text prompt content appended AFTER the preset.
	// Carries per-session prompt text that has no named preset file — a
	// sub-agent role's system prompt, or a project's default addon.
	SystemAddon string
	// Origin is the session origin (e.g. "slack", "ui", "rest") written
	// into the spawn log so Recent Spawns can show the channel without a
	// registry lookup.
	Origin string
	// IsSubAgent selects the delegated-child immutable prompt instead of
	// the human-facing one. Set from the session's ParentSessionID — the
	// one property that makes a session a sub-agent — so a role or preset
	// cannot claim the wrong audience.
	IsSubAgent bool
	// Title / TitleCustom are the session's current title state, surfaced
	// in the "This session" system-prompt block so the agent knows
	// whether it still needs to set a title without a wick_session_info
	// round-trip. Snapshot at spawn time.
	Title       string
	TitleCustom bool
	// MaxTurns caps agentic turns on the spawn (--max-turns). Pulled from
	// the agent entry by the pool; 0 = no cap.
	MaxTurns int
	// ThinkingTokens is the resolved MAX_THINKING_TOKENS env value for the
	// spawn (claude). Pulled from the agent entry by the pool; empty = unset
	// (provider default, thinking on); "0" = disabled; "<n>" = budget.
	ThinkingTokens string
	// ModelID pins a model id on the spawn, scoped to the active provider
	// instance. Pulled from the agent entry by the pool; empty = that
	// provider's own default.
	ModelID string
	// OnFailover / OnTurnOK are the pool's failover hooks for this spawn
	// (failover.go), forwarded to provider.Options. The factory leaves
	// OnFailover off for a remote spawner.
	OnFailover func(provider.FailoverRequest) provider.FailoverVerdict
	OnTurnOK   func(sentAt time.Time)
	// FailoverMsgKey is the failover run this spawn re-sends a turn for
	// ("" = none); see provider.Options.FailoverMsgKey.
	FailoverMsgKey string
}

FactoryOptions is what the pool hands to the factory. ResumeID is pulled from the session's agents.json by the pool. ProviderType / ProviderName identify which provider runtime instance to spawn against — empty ProviderName resolves to the per-type default whose name equals the type itself ("claude" / "codex" / "gemini"). Both are forwarded to the spawn logger so /tools/agents/providers can surface per-provider history without re-parsing files.

type GateConfig

type GateConfig struct {
	// GateBinary is the absolute path to the wick-gate binary. Required.
	GateBinary string
	// Rules is the whitelist enforced for every spawn under this factory.
	Rules []gate.CommandRule
	// AppName drives the shared spec path (~/.<app>/agents/gate/spec.json).
	// Falls back to "wick" when empty.
	AppName string
	// DefaultScope is written into spec.json as the fallback scope for
	// rules that have an empty Scope field. Typically the default
	// workspace directory so no-scope rules are still path-restricted.
	DefaultScope string
	// TempDirRoot is where per-spawn gate artifacts live. If empty,
	// `<Layout.SessionDir(id)>/gate` is used.
	TempDirRoot string
}

GateConfig describes the gate plumbing: where the wick-gate binary lives + what rules it enforces. The factory writes the shared spec.json from Rules on every spawn so UI changes propagate immediately without restarting the server.

type LifecycleEvent

type LifecycleEvent struct {
	SessionID    string
	AgentName    string
	Lifecycle    string // "spawning" | "killed"
	PID          int
	At           time.Time
	ProviderType string
	ProviderName string
	// Ctx is the spawn-time context from the originating Send. Carries
	// the zerolog logger the HTTP middleware attached, so callbacks
	// can `log.Ctx(ev.Ctx)` and recover the request_id. Never nil —
	// pool sets it to context.Background() when no spawn ctx applies
	// (e.g. exit fired from an already-released runEntry).
	Ctx context.Context
}

LifecycleEvent is emitted for the two transitions the pool drives directly (no parser event triggers them): a fresh spawn coming online, or a subprocess dying. PID is populated for spawning → working; 0 for killed.

type Pool

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

Pool is the global slot manager. It tracks how many agent subprocesses are alive across all sessions, FIFO-queues sessions that arrive while full, and grants slots when one frees up.

Pool deliberately knows nothing about CLI specifics — it asks an AgentFactory to build an *provider.Agent for a given session+agent name. Tests inject a factory that returns agents wired to the fakeSpawner; production wires ClaudeSpawner.

func New

func New(cfg PoolConfig) *Pool

func (*Pool) Active

func (p *Pool) Active() int

Active returns the number of running agents.

func (*Pool) ActiveCount added in v1.2.9

func (p *Pool) ActiveCount() int

ActiveCount reports how many turns are running right now. Used by the drain path for progress logging.

func (*Pool) ActiveSessions added in v1.2.9

func (p *Pool) ActiveSessions() []string

ActiveSessions lists the sessions with a turn in flight. Sorted so a drain log line is stable, and named rather than counted so an operator waiting on a long drain can see WHICH conversation is still working.

func (*Pool) ActiveSnapshot

func (p *Pool) ActiveSnapshot() []ActiveEntry

ActiveSnapshot returns a defensive copy of every running agent in the pool. Used by the Backends UI to show what's eating each slot.

func (*Pool) AutoReplyOn added in v0.28.0

func (p *Pool) AutoReplyOn(sessionID string) bool

AutoReplyOn reports the persisted Slack auto-reply flag (meta.json). It reads the session meta fresh so a restart picks up the last saved state. Missing session or read error → false (fail closed).

func (*Pool) CancelQueued added in v1.2.9

func (p *Pool) CancelQueued(sessionID, id string) bool

Kill stops the running agent for sessionID+agentName. Idempotent if the agent is not currently active — returns nil in that case. The normal onAgentExit hook still fires, releasing the slot and draining the queue. CancelQueued drops a message queued behind sessionID's running remote turn (id from its remote_queue line) before it is sent; false when none of the session's agents holds it.

func (*Pool) Capacity added in v0.15.2

func (p *Pool) Capacity() Capacity

Capacity returns the global slot usage. Caller need not hold p.mu.

func (*Pool) Dequeue

func (p *Pool) Dequeue(sessionID, agentName string) int

Dequeue drops every queued request matching sessionID+agentName. Returns the number of removed entries — operators use this to cancel a session that has been waiting too long without ever getting a slot. Active spawns are NOT touched; use Kill for that.

func (*Pool) DequeueSession added in v0.14.21

func (p *Pool) DequeueSession(sessionID string) int

DequeueSession drops every queued request for the session regardless of agent name, and clears its buffered/pending input so the session won't execute later (even across a restart). Returns the number of queue entries removed. Use this from the operator UI where the caller only knows the session id — Dequeue requires an exact agent match, which the UI often can't supply.

func (*Pool) Drain added in v1.2.9

func (p *Pool) Drain(ctx context.Context) int

Stop tears down all active agents and waits for trailing post-exit work (markStatus, queue drain). Used on graceful shutdown and by tests to flush goroutines before TempDir cleanup. Drain waits for every in-flight turn to finish on its own. Unlike Stop it never signals a running agent: a debug run that is eight minutes into its work keeps going and still posts its reply.

This is the graceful-upgrade path. Deliberately it does NOT close the pool. The draining process still owns intake (channel listeners, cron) until it exits, so closing here would make it REFUSE the very messages it is still the only process listening for — a restart that answers "agent error" instead of working. Old work and any work that arrives mid-drain both finish on the old binary; the successor starts fresh once this returns.

Returns the number of turns still active when it gave up — 0 means a clean drain. ctx bounds the wait: on a host with continuous traffic the pool may never reach zero, so the caller's timeout is what guarantees termination.

func (*Pool) EnsureSession added in v0.13.0

func (p *Pool) EnsureSession(ctx context.Context, sessionID, source, projectID string) error

EnsureSession is the public wrapper for ensureSession. Workflow's session_init executor calls this to materialize the registry entry + sidebar row up-front, before any agent node actually dispatches a message. Idempotent — a second call for the same sessionID is a no-op (or backfills project binding).

func (*Pool) EnsureSessionOwner added in v0.17.0

func (p *Pool) EnsureSessionOwner(ctx context.Context, sessionID, userID string)

EnsureSessionOwner records userID against an existing session: it stamps UserID when the session has no owner yet, and adds them to Participants either way. No-op when the session does not exist.

Owner is first-writer-wins — a later sender never takes the session over, because UserID decides whose identity a spawn runs as and handing that to whoever spoke last would silently move the whole conversation's access. Participants is additive instead: a Slack thread is genuinely multi-user, and someone who replied into it should find it under their own "Yours" without owning it.

The OnSessionMeta callback at the end is load-bearing, not cosmetic. This writes to DISK, but the per-spawn MCP credential is minted from the IN-MEMORY registry (see SessionMCPToken). Without the refresh the registry keeps serving a session with no owner, so every later spawn falls back to the shared internal token and the agent runs as the synthetic admin — even though the owner was recorded correctly. That was the "wick_me says wick-agent-internal" bug, and it survived retries precisely because the disk was right and only the cache was wrong.

func (*Pool) FailingOver added in v1.16.0

func (p *Pool) FailingOver(sessionID, agentName string) bool

FailingOver reports whether sessionID's agent is being moved to another provider right now.

func (*Pool) HandleExit

func (p *Pool) HandleExit(sessionID, agentName string, reason provider.ExitReason, reasonDetail string)

HandleExit is the public hook the factory wires into agent.OnExit. It frees the pool slot when a process exit means the AGENT is done — but for respawn-mode providers (codex) one agent spans many short-lived processes, so a turn-boundary exit (ExitClean) or an internal respawn kill (ExitRespawn) must NOT release the slot. Only a terminal reason (idle TTL, Stop/Kill, crash) tears the runEntry down. Without this gate every codex turn-end deletes the entry, and the next Send sees "no live subprocess" and spawns a SECOND concurrent agent (the double-spawn bug).

claude (append mode) keeps the 1-agent-1-process model: every exit is the agent dying, so all reasons release.

func (*Pool) HandleExitOutcome added in v1.16.0

func (p *Pool) HandleExitOutcome(sessionID, agentName string, reason provider.ExitReason, reasonDetail string) (turnEnds, restarting bool)

HandleExitOutcome is HandleExitTurnEnds that also says whether the exit restarted the agent, so a delegation waiting on its turn keeps waiting for the restarted process instead of closing on half a turn.

func (*Pool) HandleExitTurnEnds added in v1.16.0

func (p *Pool) HandleExitTurnEnds(sessionID, agentName string, reason provider.ExitReason, reasonDetail string) bool

HandleExitTurnEnds is HandleExit that also says whether the exit ends a turn (the caller then publishes its synthetic Done): false for the exit of a process a failover stopped. One decision, taken where the exit is handled, so the caller cannot read a failover flag that changed in between.

func (*Pool) HandoverBlockerCount added in v1.2.9

func (p *Pool) HandoverBlockerCount() int

HandoverBlockerCount is HandoverBlockers as the count the drain tracker polls. Zero means settled.

func (*Pool) HandoverBlockers added in v1.2.9

func (p *Pool) HandoverBlockers() []string

HandoverBlockers names the reasons a graceful handover must not complete yet. Empty means the pool has settled and the successor can take over.

One kind of blocker, and it is not a clock running against the work:

  • A turn is actually producing (lifecycle spawning or working). The lifecycle is driven by normalised agent events, so this holds for every provider — claude, codex, anything added later — without this code knowing which one is running. Except a ghost: a lifecycle stuck at spawning/working with no process left behind it (see ghostTurn). Such an entry can never finish, so waiting on it held a drain open forever — the old process never exited and the successor never got the intake baton. It is logged once, its dead process reaped through the normal exit path, and the handover proceeds. Real work is still waited for however long it runs.
  • Nothing else. The gap AFTER a turn ends — where a tool result, a queued message or a sub-agent reply usually lands — is covered once, globally, by the drain's settle window (upgrade.DrainQuiet), so it does not need repeating per subsystem here.

An idle subprocess is deliberately NOT a blocker. It holds no turn — it is waiting out its auto-kill countdown — and the next message spawns in the successor. Counting those is what forced the old fixed grace: len(active) stays non-zero for minutes after everybody has stopped talking, so waiting on it meant waiting on the idle TTL, and the only way out was a deadline that also cut live turns.

func (*Pool) IdleTimeout

func (p *Pool) IdleTimeout() time.Duration

IdleTimeout returns the configured idle timeout. UI consumers use it to render the auto-kill countdown alongside LastActive.

func (*Pool) Kill

func (p *Pool) Kill(sessionID, agentName string) error

func (*Pool) KillAgent added in v0.36.0

func (p *Pool) KillAgent(sessionID, agentName string) error

KillAgent stops exactly ONE agent inside a session, leaving its siblings running.

Kill remains "stop the whole session" — cascade teardown and the existing /sessions/{id}/kill route depend on that semantic, so this is a new method rather than a fix to Kill's ignored agentName parameter.

Returns ErrAgentNotActive when no live entry matches.

func (*Pool) KillAgentBy added in v1.2.9

func (p *Pool) KillAgentBy(sessionID, agentName, by, note string) error

KillAgentBy is KillAgent with an author — see KillBy. The delegation paths use it so a sub-agent that was stopped by its parent says so, rather than looking like it died on its own.

func (*Pool) KillBy added in v1.2.9

func (p *Pool) KillBy(sessionID, agentName, by, note string) error

KillBy is Kill with an author. The turn that gets cut short records who did it, so the transcript can say "stopped by <person>" instead of leaving the reader to guess between a person, the agent, and wick going down — which is the difference between "fine, that was me" and "why did my work vanish". Pass empty strings when nothing is known.

func (*Pool) LeaseCount added in v1.2.9

func (p *Pool) LeaseCount() int

LeaseCount reports how many slots are currently lent out.

func (*Pool) ListenChannel added in v1.18.0

func (p *Pool) ListenChannel(instance, chatID string) bool

ListenChannel reports whether instance listens to every thread it has in chatID (scope "channel").

func (*Pool) ListenDocs added in v1.18.0

func (p *Pool) ListenDocs(sessionID string) (wickDefault, agent string)

ListenDocs returns the wick-wide default LISTEN.md (agents root) and the one in the session's project folder. Read on every call: an edit applies to the next message without a restart.

func (*Pool) ListenThread added in v1.18.0

func (p *Pool) ListenThread(sessionID string) agentchannels.ListenThread

ListenThread reports what a "listen" request stored on sessionID.

func (*Pool) MaxConcurrent

func (p *Pool) MaxConcurrent() int

MaxConcurrent surfaces the configured slot cap for the Backends UI. Read-only — change via PoolConfig at construction time.

func (*Pool) NoteOutput added in v1.17.0

func (p *Pool) NoteOutput(sessionID string)

NoteOutput tells the pool sessionID's agent produced output: a restart under way has come back. Cheap when nothing restarts, so it can run on every event.

func (*Pool) PartialText added in v0.36.0

func (p *Pool) PartialText(sessionID, agentName string) string

PartialText returns the assistant text one agent has produced in its current, not-yet-flushed turn. Empty when the agent is not active or no turn is mid-stream.

This is how partial work is captured before a kill: the last turn of an interrupted or turn-capped sub-agent never reaches Done, so it is never persisted by the normal path, and reading it here is the only way to hand it back to the leader instead of losing it.

func (*Pool) ProviderCapacity added in v0.15.2

func (p *Pool) ProviderCapacity(pType, pName string) Capacity

ProviderCapacity returns the EFFECTIVE capacity for one provider instance: bounded by both its own per-instance cap and the global remaining. Used == active+spawning entries for that provider. Remaining is what can actually be granted right now (the min of the two scopes). Caller need not hold p.mu.

func (*Pool) ProviderOf added in v1.17.0

func (p *Pool) ProviderOf(sessionID, agentName string) (pType, pName string)

ProviderOf is the provider instance sessionID's agent runs on, as the spawn gate resolves it ("" when the session cannot be read).

func (*Pool) QueueLen

func (p *Pool) QueueLen() int

QueueLen returns the number of queued requests.

func (*Pool) QueueSnapshot

func (p *Pool) QueueSnapshot() []QueueEntry

QueueSnapshot returns a defensive copy of the current FIFO queue (oldest first). Used by the Backends UI to show what's waiting.

func (*Pool) ReconcileDead added in v0.15.2

func (p *Pool) ReconcileDead()

ReconcileDead scans active entries and Stops any whose subprocess is no longer alive at the OS level — a crash or external kill that the reader loop never saw as stdout EOF (common on Windows, where killing a process does not reliably close its pipe). Stop() fires the exit hook, releasing the slot and draining the queue, so a zombie entry can't wedge the pool. Cheap signal-0 probe per entry; safe to call from request handlers (panel open) and a periodic ticker.

func (*Pool) ReleaseDone added in v1.18.0

func (p *Pool) ReleaseDone(sessionID, cause string) int

ReleaseDone stops sessionID's processes whose work is over, so their slots and memory return to the pool now instead of after the idle TTL. A process mid-turn, mid-spawn, holding queued messages or waiting on a background task is left alone (Agent.StopIfDone). The session keeps its CLI session ID and resumes via --resume on its next message. Returns how many processes were stopped. Stop blocks, so call it off any lock.

func (*Pool) Resend added in v1.16.0

func (p *Pool) Resend(ctx context.Context, sessionID, agentName string, texts ...string) error

Resend delivers texts to sessionID's agent as the head of its next turn without recording them: they are a turn already in conversation.jsonl (or wick's own continue message), so no user bubble is written and no user-message hook fires. Empty texts are skipped.

It also ends the agent's failover, before spawning: what is held is in the buffer behind texts by then, and the spawn's own exit or failure must reach the consumers like any other.

func (*Pool) Send

func (p *Pool) Send(ctx context.Context, sessionID, agentName, source, role, text string) error

func (*Pool) SendWithAttachments added in v0.14.18

func (p *Pool) SendWithAttachments(ctx context.Context, sessionID, agentName, source, role, text, projectID string, atts []store.Attachment) error

SendWithAttachments is Send with a list of user-uploaded files. The caller is responsible for materializing the files on disk under SessionDir/uploads/ — the pool only persists the metadata into conversation.jsonl and appends a small `[Attached files]` block to the text sent to the CLI subprocess so it can Read the paths.

func (*Pool) SendWithProject added in v0.14.21

func (p *Pool) SendWithProject(ctx context.Context, sessionID, agentName, source, role, text, projectID string) error

SendWithProject is like Send but binds sessionID to the given project id when auto-creating the session. Pass an empty string for the default.

func (*Pool) SessionExists added in v0.9.4

func (p *Pool) SessionExists(sessionID string) bool

Send routes a user message into the right session. If a slot is free the agent is spawned and the message sent immediately; else the message is appended to the session's buffer and the request is queued. The on-disk session meta status is updated to reflect running/queued so UI listings stay correct. SessionExists reports whether sessionID already has on-disk state. Cheap stat — no JSON parse. Used by channels (Slack, Telegram) to decide whether the next inbound message starts a brand-new session and needs a one-time origin-context turn injected before the user message.

Implements channels.SessionChecker.

func (*Pool) SetAutoReply added in v0.28.0

func (p *Pool) SetAutoReply(sessionID string, on bool)

SetAutoReply persists the Slack auto-reply flag on the session meta. A missing session or save error is logged and swallowed — the in-memory fallback in the channel keeps the turn working even if persistence fails.

func (*Pool) SetListenChannel added in v1.18.0

func (p *Pool) SetListenChannel(instance, chatID string, on bool)

SetListenChannel adds or removes chatID from instance's listened channels.

func (*Pool) SetListenThread added in v1.18.0

func (p *Pool) SetListenThread(sessionID string, lt agentchannels.ListenThread)

SetListenThread stores lt on sessionID. A missing session is logged and skipped, like SetAutoReply.

func (*Pool) SetMaxTurns added in v0.15.5

func (p *Pool) SetMaxTurns(sessionID, agentName string, maxTurns int) error

SetMaxTurns persists the per-spawn turn cap on the session's agent entry (creating it if missing) so the next spawn passes --max-turns.

func (*Pool) SetModelID added in v1.2.9

func (p *Pool) SetModelID(sessionID, agentName, modelID string) error

SetModelID pins a model id on the session's agent entry (creating it if missing) so the next spawn runs that model. Empty = unset (the provider's own default). Used by a workflow agent node with a model.

func (*Pool) SetNodeProvider added in v1.18.0

func (p *Pool) SetNodeProvider(sessionID, agentName, providerKey, modelID string) error

SetNodeProvider repoints the session's agent entry at a workflow agent node's provider ("type/name") and model, so the next spawn resolves them; an agent a failover moved off that provider stays on its stand-in (session.SetNodeProvider). No-op when the entry does not exist — create it first (SetMaxTurns does).

func (*Pool) SetOnWaitChange added in v1.17.0

func (p *Pool) SetOnWaitChange(f func())

SetOnWaitChange registers f, called (on its own goroutine) whenever a session starts or stops restarting or the queue moves. f re-reads WaitOf for what it shows.

func (*Pool) SetThinkingTokens added in v0.18.7

func (p *Pool) SetThinkingTokens(sessionID, agentName, v string) error

SetThinkingTokens persists the resolved MAX_THINKING_TOKENS env value on the session's agent entry (creating it if missing) so the next spawn applies it. Empty = unset (provider default); "0" = disabled; "<n>" = token budget.

func (*Pool) SetThreadBinding added in v1.2.9

func (p *Pool) SetThreadBinding(sessionID string, b agentchannels.ThreadBinding)

SetThreadBinding persists the binding on the session meta. Idempotent — an unchanged binding writes nothing. LastSeenTS only moves forward within the same thread; it changes once per Slack message that starts a turn.

func (*Pool) Stop

func (p *Pool) Stop()

func (*Pool) TakeGiveUp added in v1.17.0

func (p *Pool) TakeGiveUp(sessionID string) string

TakeGiveUp returns, and forgets, why the idle retries of sessionID stopped ("" = they did not): the Done of that exit carries it, so the waiting side fails with a plain reason instead of an empty answer.

func (*Pool) ThreadBinding added in v1.2.9

func (p *Pool) ThreadBinding(sessionID string) (agentchannels.ThreadBinding, bool)

ThreadBinding reads the persisted chat-thread binding for a session. Loaded fresh so a restart — or a handover to another process — sees the last saved value rather than nothing.

func (*Pool) TryLease added in v1.2.9

func (p *Pool) TryLease(key, pType, pName string) (release func(), ok bool)

TryLease reserves one slot for key on provider pType/pName. ok is false when the pool is closed, a session is queued, the key already holds a lease, or either cap (or the free-memory floor) is exhausted — the caller waits and tries again. release is idempotent.

func (*Pool) WaitOf added in v1.17.0

func (p *Pool) WaitOf(sessionID string) WaitState

WaitOf is what sessionID's next answer waits on.

type PoolConfig

type PoolConfig struct {
	MaxConcurrent int
	IdleTimeout   time.Duration
	KillAfterIdle time.Duration
	// TurnIdleTimeout is the silence a spawn may keep while a turn is
	// open or a background task is pending (provider.Options). 0 = none:
	// IdleTimeout everywhere, the legacy behaviour. The server passes
	// DefaultTurnIdleTimeout.
	TurnIdleTimeout time.Duration
	// MinFreeMemoryLoader returns the floor, in MB, below which a spawn is
	// queued rather than started. 0 or a nil loader disables the check, so
	// a pool built without it behaves exactly as it always has.
	//
	// A loader rather than a value because the operator changes this in
	// the UI while wick is running — the same reason the factory's Gate
	// and MemGuard settings are loaders. MaxConcurrent above counts
	// PROCESSES; this counts BYTES, and a free slot says nothing about
	// whether the machine can host what would fill it.
	MinFreeMemoryLoader func() int

	// SpawnHold reports whether the resource guard wants new agents held
	// back because memory is FALLING toward the floor — the trend a static
	// MinFreeMemoryLoader floor cannot see. nil = no trend gate.
	SpawnHold func() bool
	// SpawnHoldReason says what the guard saw when it held a spawn
	// ("memory pressure full avg10 25%"), for the log. nil = unknown.
	SpawnHoldReason func() string

	// StopAfterMachineTurn reports whether a process whose turn no person
	// asked for (a schedule, a workflow, a watch, a sub-agent, the CLI…)
	// is stopped as soon as that turn ends, instead of idling until
	// IdleTimeout while it holds a slot and its memory. A person's turn
	// (web, Slack, Telegram…) always idles as usual. Read live; nil = off.
	// Team turns are decided per agent instead (StopAfterTeamTask).
	StopAfterMachineTurn func() bool
	// CallerUserID resolves the wick user behind a Send from its context.
	// The pool stays decoupled from the auth packages: the server injects
	// this. nil (or empty result) = no resolved caller, which disables
	// caller-change respawn for that message.
	CallerUserID func(ctx context.Context) string

	// CallerToken resolves the credential behind a Send — id and label of
	// the Personal Access Token, for channels that authenticate with one.
	// Recorded on the session at create time so a machine caller can be
	// identified later by WHAT called, not only by whose account it used.
	// nil (or an empty id) = nothing to record, which is the normal case
	// for a human typing in a browser.
	CallerToken func(ctx context.Context) (id, name string)

	// SenderFrom resolves WHO sent a message from its context — the human
	// identity the originating channel read off its own transport envelope.
	// Injected for the same reason as CallerUserID: the pool must not import
	// the channels package.
	//
	// Distinct from CallerUserID, which answers "whose wick account does this
	// turn run as" (a permissions question, and the reason a process gets
	// recycled). This answers "who is the agent talking to" — a display and
	// prompting question. They diverge whenever a Slack user has no mapped
	// wick account, or when several people share one channel-owner identity.
	//
	// nil (or a nil result) = anonymous turn: no `[wick-sender ...]` prefix
	// and no sender persisted, exactly how every turn behaved before this
	// existed.
	SenderFrom func(ctx context.Context) *store.Sender

	// SenderVisibilityLoader reports how much of the sender to write into the
	// text handed to the model: SenderOff / SenderName / SenderNameID /
	// SenderFull. nil or an empty result means SenderName.
	//
	// A loader rather than a value because the operator changes this in the
	// UI while wick is running, same as the memory-guard settings. It governs
	// the model's copy only — the store and the dashboard always get the full
	// sender.
	SenderVisibilityLoader func() string

	// RevokeMCPToken invalidates a per-session MCP credential once its
	// subprocess is gone, so a leaked token stops working at process death
	// instead of at its TTL. nil = no revocation (tokens simply expire).
	RevokeMCPToken func(token string)

	// RespawnOnCallerChange makes a session whose incoming message comes
	// from a DIFFERENT user than the running subprocess kill and respawn
	// that subprocess, so the new user's turn runs under their own MCP
	// identity rather than inheriting the previous caller's.
	//
	// Off by default: it costs the process's context (conversation history
	// is reloaded, but in-memory state is lost), which is the wrong trade
	// for the common single-user session. Turn it on for shared sessions
	// where per-user attribution matters more than continuity.
	RespawnOnCallerChange bool

	// IdentityFixed reports whether a session's spawn identity is the same
	// whoever triggers the turn (a Team agent running as its owner). Such a
	// session is never recycled on caller grounds: the respawn would mint
	// the very identity the running process already holds. nil = none is.
	IdentityFixed func(ctx context.Context, sessionID string) bool

	// PreemptIdle, when true, lets a queued send kick out the longest-idle
	// active subprocess (Lifecycle == Idle) so the new session doesn't have
	// to wait for the idle TTL. The preempted session keeps its CLI session
	// ID in agents.json and resumes via --resume on its next message.
	PreemptIdle bool
	// PredecessorHolds reports whether a still-draining previous process is
	// running sessionID's turn. During a handover this process already takes
	// the channels while that turn finishes there; a message for the same
	// session waits buffered until it does, so one session never runs two
	// agents at once. Nil = never.
	PredecessorHolds func(sessionID string) bool
	Layout           config.Layout
	Factory          AgentFactory
	// DefaultProvider is the instance key ("claude", "claude/work", ...)
	// used when a session's agent entry has no provider bound — the
	// channel/API/quick-create path where AddAgent is called with an empty
	// provider. Empty falls back to the per-type claude default (see
	// factory.go). Sourced from GeneralConfig.DefaultProvider.
	DefaultProvider string
	// OnSessionCreated is called after the pool auto-creates a session for a
	// channel message (e.g. Slack thread_ts). Wire this to
	// manager.Register so the dashboard sees the session immediately.
	OnSessionCreated func(s session.Session)
	// OnAgentAdded is called after the pool auto-adds an agent entry to
	// agents.json (channel sessions bypass the UI AddAgent flow). Wire
	// this to manager.RefreshSession so the in-memory registry reflects
	// the new agent before sendMessage resolves agentName.
	OnAgentAdded func(sessionID string)
	// OnSessionMeta is called after the pool mutates a session's meta on
	// disk (e.g. setLabelIfEmpty derives the first-message title). Wire
	// this to syncSessionMeta so the in-memory registry refreshes and the
	// new title broadcasts over SSE — otherwise the sidebar/list would
	// only catch up on the next page load. Optional; nil = no callback.
	OnSessionMeta func(sessionID string)
	// TurnNote, when set, returns a block put in front of the agent-facing
	// text of a user turn ("" for none): the [linked] line of sessions
	// working on the same matter right now. Never stored in the history.
	TurnNote func(sessionID string) string
	// OnFirstUserMessage fires once per session, right after the first
	// user message has been persisted and the auto-label derived. Wired
	// to the ticket auto-create evaluator: its rules can key off the
	// message text, which is only knowable at this point — not when the
	// session was created. Runs in the caller's goroutine, so keep it
	// cheap; failures are the callback's own to log. Optional.
	OnFirstUserMessage func(sessionID, text string)
	// OnLifecycle fires when the pool transitions a session+agent's
	// lifecycle (Spawning, Killed). Idle/Working transitions are
	// implicit from event flow and are NOT routed here — UIs that
	// want every transition should subscribe to AgentEvent via
	// the factory's OnEvent. Optional; nil = no callback.
	OnLifecycle func(LifecycleEvent)
	// OnFailoverNotify carries an automatic provider failover's notice
	// out, like SwitchOptions.Notify of a manual switch: the system turn's
	// chip and steps for the web UI. Channels get no notice (no Reply): to
	// a thread the turn just goes on, on the next provider. Optional.
	OnFailoverNotify func(sessionID, agentName, chip string, steps []string)
	// OnFailoverAbort publishes the end of a turn a failover took over
	// but could not carry on (switch refused, re-send failed, session
	// stopped): the original Error when there is one, then Done. Optional.
	OnFailoverAbort func(sessionID, agentName string, evs []event.AgentEvent)
	// OnUserMessage fires when a user-role message is injected into a
	// session from a NON-web source (a channel or the schedule runner).
	// It lets the web SSE layer push the incoming turn to connected
	// viewers, which otherwise only see the assistant reply (the web
	// composer renders its own sends optimistically, so "ui"-sourced
	// turns are skipped here to avoid a duplicate). Optional; nil = no
	// callback.
	OnUserMessage func(UserMessageEvent)
	// OnSend fires at the start of every Send, whatever its source or
	// role, before the message is routed to a live process or buffered,
	// with the sender's ctx. It may block: the team task gate holds a
	// message back while it stops a task's turn in the session. An error
	// refuses the message (Send returns it). Otherwise done is called once
	// the send is over, delivered telling whether the message was written
	// to the live process or the session's buffer. Optional; nil = no
	// callback.
	OnSend func(ctx context.Context, sessionID, role string) (done func(delivered bool), err error)
	// OnSpawnError fires when a spawn fails before the agent process starts
	// (e.g. the CLI binary can't be launched). The wiring surfaces Message
	// as a live error event so it shows inline in the conversation instead of
	// only as a request-level error/toast; the pool has already persisted the
	// same text as a system error turn. Optional; nil = no callback.
	OnSpawnError func(SpawnErrorEvent)
}

PoolConfig knobs.

A session with no project bound falls back to a per-session temp dir so claude still has a stable cwd. See agents-design.md §0.2 D4.

type QueueEntry

type QueueEntry struct {
	SessionID string
	AgentName string
	Enqueued  time.Time
}

QueueEntry is the public snapshot view of one queued request.

type SpawnErrorEvent added in v0.31.0

type SpawnErrorEvent struct {
	SessionID    string
	AgentName    string
	Ctx          context.Context
	Message      string
	Err          error
	ProviderType string
	ProviderName string
}

SpawnErrorEvent carries a failed-spawn notice to the SSE layer. Message is the human-readable text already persisted to conversation.jsonl; the raw fields are there for logging/formatting by the wiring.

type SpawnStartMeta

type SpawnStartMeta struct {
	PID              int
	Binary           string
	Argv             []string
	Env              []string
	FirstUserMessage string
}

SpawnStartMeta is the post-Start snapshot the pool feeds back to the factory so the spawn log gets a complete `start` record. PID, argv, and binary path are only knowable after Spawner.Spawn returns; FirstUserMessage comes from the buffer drain.

type TeamLimits added in v1.2.9

type TeamLimits struct {
	AgentID string
	// DisallowedTools is the claude --disallowedTools list for the
	// switches that are off (Bash included when it is off).
	DisallowedTools []string
	// BashAllowed is the Bash switch. With the gate on it only holds
	// while the gate hook is installed: without it Bash would run every
	// command unasked, so the spawn turns it off instead. With the gate
	// off (bypass) every command already runs unasked, so it holds as is.
	BashAllowed bool
	// BashRules run without asking; anything else goes to the approval
	// prompt. Empty = every command asks.
	BashRules    []gate.CommandRule
	DefaultScope string
	// DisabledSkills are left out of the built-in skill catalog (every
	// provider) and denied as Skill(<name>) on claude, which is how a
	// local or global skill — discovered by the CLI itself — is kept out.
	DisabledSkills []string
}

TeamLimits holds a Team agent's spawns to its native-tool switches and Bash allow-list. Defined here so the pool does not import the team package; server.go adapts team.Limits.

type TeamSpawn added in v1.2.9

type TeamSpawn struct {
	// Prompt is the Team overlay plus the "Who you are" block.
	Prompt string
	// Access is the "Your access" block.
	Access string
	// Subagents and Schedule keep the matching gated sections of the
	// immutable main overlay (see systemprompt.TeamGates).
	Subagents bool
	Schedule  bool
	// Files keeps the HTML render formats (systemprompt.TeamGates.Files).
	Files bool
	// UseGlobalPrompt is no longer read: every Team spawn carries
	// system_prompt. Kept so callers and stored agents still compile.
	UseGlobalPrompt bool
	// TeamInstructions is the owner's Team prompt, for every agent in
	// their Team; "" = no "## Team instructions" section.
	TeamInstructions string
}

TeamSpawn is what a Team agent's own session adds to its prompt beyond the persona. Defined here rather than taken from the team package so the pool does not depend on it; server.go adapts team.SpawnPrompt.

type UserMessageEvent added in v0.29.0

type UserMessageEvent struct {
	SessionID string
	AgentName string
	Source    string
	Text      string
	// Sender is who sent it, when the channel resolved one. Carried here so
	// a live-rendered turn shows the same sender chip a reloaded one does —
	// without it, a Slack message would arrive anonymous and only grow its
	// name after a refetch.
	Sender *store.Sender
}

UserMessageEvent carries an injected user turn to the SSE layer so already-connected web viewers render it live instead of only after a manual refresh. Source is the origin ("slack", "telegram", "schedule", …) so the UI can badge where the message came from.

type WaitState added in v1.17.0

type WaitState struct {
	// RestartAttempt is the idle-kill retry under way (1-based) and
	// RestartMax how many there are; 0 when the session is not being
	// restarted. Cleared at the restarted process's first output.
	RestartAttempt, RestartMax int
	// QueuePos is the session's place in the pool queue (1 = next),
	// 0 when it is not queued.
	QueuePos int
}

WaitState is what a session's next answer waits on. Zero = nothing (running, idle, or unknown).

func (WaitState) Note added in v1.17.0

func (w WaitState) Note() string

Note is w in one line for an agent waiting on the session, "" for none: "target restarting after an idle timeout, retry 1/2".

Jump to

Keyboard shortcuts

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