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
- Variables
- func ShouldRespawn(reason provider.ExitReason, attempts int) bool
- type ActiveEntry
- type AgentFactory
- type Buffer
- type BuildResult
- type Capacity
- type ClaudeFactory
- type FactoryOptions
- type GateConfig
- type LifecycleEvent
- type Pool
- func (p *Pool) Active() int
- func (p *Pool) ActiveCount() int
- func (p *Pool) ActiveSessions() []string
- func (p *Pool) ActiveSnapshot() []ActiveEntry
- func (p *Pool) AutoReplyOn(sessionID string) bool
- func (p *Pool) CancelQueued(sessionID, id string) bool
- func (p *Pool) Capacity() Capacity
- func (p *Pool) Dequeue(sessionID, agentName string) int
- func (p *Pool) DequeueSession(sessionID string) int
- func (p *Pool) Drain(ctx context.Context) int
- func (p *Pool) EnsureSession(ctx context.Context, sessionID, source, projectID string) error
- func (p *Pool) EnsureSessionOwner(ctx context.Context, sessionID, userID string)
- func (p *Pool) HandleExit(sessionID, agentName string, reason provider.ExitReason, reasonDetail string)
- func (p *Pool) HandoverBlockerCount() int
- func (p *Pool) HandoverBlockers() []string
- func (p *Pool) IdleTimeout() time.Duration
- func (p *Pool) Kill(sessionID, agentName string) error
- func (p *Pool) KillAgent(sessionID, agentName string) error
- func (p *Pool) KillAgentBy(sessionID, agentName, by, note string) error
- func (p *Pool) KillBy(sessionID, agentName, by, note string) error
- func (p *Pool) LeaseCount() int
- func (p *Pool) MaxConcurrent() int
- func (p *Pool) PartialText(sessionID, agentName string) string
- func (p *Pool) ProviderCapacity(pType, pName string) Capacity
- func (p *Pool) QueueLen() int
- func (p *Pool) QueueSnapshot() []QueueEntry
- func (p *Pool) ReconcileDead()
- func (p *Pool) Send(ctx context.Context, sessionID, agentName, source, role, text string) error
- func (p *Pool) SendWithAttachments(ctx context.Context, ...) error
- func (p *Pool) SendWithProject(ctx context.Context, ...) error
- func (p *Pool) SessionExists(sessionID string) bool
- func (p *Pool) SetAgentProvider(sessionID, agentName, providerKey string) error
- func (p *Pool) SetAutoReply(sessionID string, on bool)
- func (p *Pool) SetMaxTurns(sessionID, agentName string, maxTurns int) error
- func (p *Pool) SetModelID(sessionID, agentName, modelID string) error
- func (p *Pool) SetThinkingTokens(sessionID, agentName, v string) error
- func (p *Pool) SetThreadBinding(sessionID string, b agentchannels.ThreadBinding)
- func (p *Pool) Stop()
- func (p *Pool) ThreadBinding(sessionID string) (agentchannels.ThreadBinding, bool)
- func (p *Pool) TryLease(key, pType, pName string) (release func(), ok bool)
- type PoolConfig
- type QueueEntry
- type SpawnErrorEvent
- type SpawnStartMeta
- type TeamLimits
- type TeamSpawn
- type UserMessageEvent
Constants ¶
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 ¶
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.
Functions ¶
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.
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 ¶
NewBuffer reads any pending_input persisted on disk so we resume queued messages after a wick restart.
func (*Buffer) Append ¶
Append adds a new line and persists it to meta.PendingInput so a crash before drain doesn't drop it.
func (*Buffer) Drain ¶
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.
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).
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
// 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)
// TeamSystemPromptLoader (optional) returns the `system_prompt_team`
// config row: the operator prompt of Team agent sessions, in place of
// SystemPromptLoader. Empty = no operator prompt at all.
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
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
}
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) ActiveCount ¶ added in v1.2.9
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
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
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
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
Capacity returns the global slot usage. Caller need not hold p.mu.
func (*Pool) Dequeue ¶
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
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
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
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
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) 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) HandoverBlockerCount ¶ added in v1.2.9
HandoverBlockerCount is HandoverBlockers as the count the drain tracker polls. Zero means settled.
func (*Pool) HandoverBlockers ¶ added in v1.2.9
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 ¶
IdleTimeout returns the configured idle timeout. UI consumers use it to render the auto-kill countdown alongside LastActive.
func (*Pool) KillAgent ¶ added in v0.36.0
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
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
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
LeaseCount reports how many slots are currently lent out.
func (*Pool) MaxConcurrent ¶
MaxConcurrent surfaces the configured slot cap for the Backends UI. Read-only — change via PoolConfig at construction time.
func (*Pool) PartialText ¶ added in v0.36.0
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
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) 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) 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
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) SetAgentProvider ¶ added in v1.2.9
SetAgentProvider repoints the session's agent entry at a provider instance ("type/name", e.g. "claude/work") so the next spawn resolves that instance's binary and env. Used by a workflow agent node, whose provider is chosen per node rather than per session. No-op when the entry does not exist — create it first (SetMaxTurns does).
func (*Pool) SetAutoReply ¶ added in v0.28.0
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) SetMaxTurns ¶ added in v0.15.5
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
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) SetThinkingTokens ¶ added in v0.18.7
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, so this can be called on every turn without rewriting meta.json each time.
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
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.
type PoolConfig ¶
type PoolConfig struct {
MaxConcurrent int
IdleTimeout time.Duration
KillAfterIdle 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
// 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
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)
// 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)
// 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)
// 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 ¶
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 swaps system_prompt_team for the global
// system_prompt (an agent converted from a project keeps its rules).
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.