session

package
v1.18.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package session manages on-disk session entries at `<BaseDir>/sessions/<id>/`. A session is one Slack thread or one UI conversation: routing key, status, agent registry, log files, and an optional reference to a project whose folder is the agent cwd.

Sessions own no project files of their own — a project is a shared bundle (see internal/agents/project) whose folder the pool resolves to a cwd at spawn time. See agents-design.md §0.2 for the refactor that removed the per-session git worktree, and the project design (internal/planning/archive/project/design.md) for the Workspace→Project rename.

Files in this package:

  • session.go — Meta + lifecycle (Create/Load/Save/Delete/SetProject)
  • agents.go — per-session AgentEntry + Add/SetActive

Index

Constants

View Source
const (
	// RoomMemberAgent is a Team agent working for OwnerID.
	RoomMemberAgent = "agent"
	// RoomMemberProjectDefault is the project's own prompt and provider,
	// running as whoever sends the message.
	RoomMemberProjectDefault = "project_default"
)

Kinds of a ticket room member (RoomMember.Kind).

Variables

View Source
var ErrNoAgentName = errors.New("session: agent name is empty")

ErrNoAgentName rejects a blank agent name.

The setters below create an entry when the name does not match, which is how a single blank name turned into a growing list of unaddressable rows: nothing can ever match "" again, so every later call appended another one, and the session appeared to hold a second agent nobody created. A blank name is always a caller bug, so it fails loudly instead of writing.

View Source
var ProjectAgent func(projectID string) string

ProjectAgent, when set, names the Team agent that owns a project ("" = none). Create stamps it on every new top-level session of that project that names no agent itself, so a channel thread, a schedule fire or a workflow run in a project converted into an agent is that agent's session — one rule at the one place sessions are made, instead of one per creator. Wired at boot by the Team service.

Functions

func AbandonGoal added in v0.35.2

func AbandonGoal(layout agentconfig.Layout, id, note string) error

AbandonGoal marks the open latch abandoned. No open goal → no-op.

func ActiveRunTarget added in v0.36.2

func ActiveRunTarget(layout config.Layout, id string) (providerKey, modelID string, ok bool)

ActiveRunTarget reports the provider instance + model a session is actually running on, read from its active agent entry.

This is the pair a delegated sub-agent inherits when its role names no provider of its own, so it must read the SAME fields the pool reads on spawn — Provider and ModelID off ONE entry — rather than reconstructing the choice from elsewhere. Returned as two strings rather than a provider.RunTarget because provider imports this package; the caller pairs them.

The entry is picked by Meta.ActiveAgent, falling back to the first one: a session created outside the UI flow may never have had an active agent set, and treating that as "runs on nothing" would silently drop the inheritance the caller asked for.

ok=false means the session could not be read or has no agent entries — distinct from an entry that names no provider, which is a real answer ("this session has no opinion") and returns ok=true with an empty providerKey.

func AddAgent

func AddAgent(layout config.Layout, id, name, provider string) error

AddAgent appends a new agent entry. Errors on duplicate name within the same session.

func AgentOfSessionID added in v1.16.0

func AgentOfSessionID(id string) string

AgentOfSessionID names the Team agent whose own Slack bot opened the session id, "" for any other id. The id says it outright, so it holds even where ProjectAgent cannot: an agent adopted onto an ordinary project (no agent tag) still owns the threads its bot answers.

func ClearFailoverState added in v1.16.0

func ClearFailoverState(layout config.Layout, id, name string) error

ClearFailoverState drops the agent's failover state, home included. No-op when the entry doesn't exist or carries none.

func CompleteGoal added in v0.35.2

func CompleteGoal(layout agentconfig.Layout, id, note string) error

CompleteGoal marks the open latch done. No open goal → no-op.

func Cwd added in v1.2.9

func Cwd(layout config.Layout, sess Session) (string, error)

Cwd is the directory a session's work happens in: its project path when it belongs to a project, else sessions/<id>/cwd. Exported here because three callers need the SAME answer — the SCM HTTP layer, the wick_scm MCP tool, and the system prompt that names the repo being worked on — and a second copy of this rule would drift.

func Delete

func Delete(_ context.Context, layout config.Layout, id string) error

Delete removes the session folder. The project it points at is left untouched — projects are shared, so deleting a session must not delete its files.

func EndFailoverRun added in v1.16.0

func EndFailoverRun(layout config.Layout, id, name string) error

EndFailoverRun closes the agent's failover run (EndRun) and keeps its home: the turn the run was for finished. No-op when the entry doesn't exist or has no run.

func HasOpenGoal added in v0.35.2

func HasOpenGoal(layout agentconfig.Layout, id string) bool

HasOpenGoal reports whether the session has an open goal latch.

func HasOpenGoalDir added in v0.35.2

func HasOpenGoalDir(sessionDir string) bool

HasOpenGoalDir is the engine-side form of HasOpenGoal.

func List

func List(layout config.Layout) ([]string, error)

List returns every top-level session ID, sorted. Sub-agent sessions live inside their parent's folder and are deliberately NOT returned — this is what keeps them out of the conversation list.

func ListAll added in v0.36.1

func ListAll(layout config.Layout) ([]string, error)

ListAll returns every session ID, sub-agents included, parents before their children.

Callers that hydrate runtime state — the boot registry, the workspace sweeper — must use this rather than List: a sub-agent is a real session with a real transcript and real connector instances, and skipping it would leave it unrecoverable after a restart and its instances unreaped. Anything that renders the conversation list wants List.

func ListChildren added in v0.36.1

func ListChildren(layout config.Layout, parentID string) ([]string, error)

ListChildren returns the IDs of the sub-agent sessions delegated directly by parentID, sorted. Empty for a session that never delegated.

func OpenGoal added in v0.35.2

func OpenGoal(layout agentconfig.Layout, id, goal, note string) error

OpenGoal writes/replaces an open latch.

func ProviderInstance added in v1.16.0

func ProviderInstance(key string) string

ProviderInstance returns the full "type/name" key of a provider key; a bare type is its default instance ("claude" → "claude/claude"), and "" stays "".

func ProviderScope added in v0.39.10

func ProviderScope(key string) string

ProviderScope returns the provider type of a provider key ("claude/work" → "claude").

Every instance of one provider type resumes from the same transcript store — the same CLI binary reading the same on-disk history — so a resume id captured under one instance is valid under any other of that type, and never valid under a different type. ProviderSessions is keyed by this.

Lives here rather than in the provider package because the switcher AND the store both write ProviderSessions and must agree on the key; provider imports store, so store cannot import provider, and session is the package both already depend on.

func ResumeIDForScope added in v0.39.10

func ResumeIDForScope(m map[string]string, scope string) string

ResumeIDForScope finds the resume id recorded for a provider type, tolerating every key shape written before ids were scoped: the bare scope, the normalized "type/type", and any "type/<instance>". Keys are sorted so a file holding several legacy instance keys of one type resolves the same id on every call — Go randomizes map iteration, and an id that changes per lookup is a resume that works only sometimes.

func SaveAgents

func SaveAgents(layout config.Layout, id string, agents []AgentEntry) error

SaveAgents atomically rewrites sessions/<id>/agents.json. nil becomes an empty array on disk so consumers don't have to handle `null`.

func SaveMeta

func SaveMeta(layout config.Layout, id string, meta Meta) error

SaveMeta atomically rewrites sessions/<id>/meta.json.

func SetActiveAgent

func SetActiveAgent(layout config.Layout, id, name string) error

SetActiveAgent updates meta.json's active_agent field. The named agent must already exist in agents.json.

func SetAgentProvider added in v0.36.2

func SetAgentProvider(layout config.Layout, id, name, providerKey string) error

SetAgentProvider repoints an existing agent entry at another provider instance, leaving the rest of the entry (resume id, caps) intact.

Distinct from AddAgent, which refuses a name that already exists. Used to repair an entry created with no provider, and by a workflow node repointing a reused session: the spawn path has to fill one in, and re-adding would drop the resume id the entry already carries. Like a manual switch, the new provider becomes the home and any failover run is over. No-op when the entry doesn't exist.

func SetCLISessionID added in v0.15.5

func SetCLISessionID(layout config.Layout, id, name, cliID string) error

SetCLISessionID writes (or clears, with "") the CLI resume id on the agent entry. No-op when the entry doesn't exist.

func SetFailoverState added in v1.16.0

func SetFailoverState(layout config.Layout, id, name string, st FailoverState) error

SetFailoverState writes st onto the agent entry. No-op when the entry doesn't exist: the state belongs to an agent already running.

func SetMaxTurns added in v0.15.5

func SetMaxTurns(layout config.Layout, id, name string, maxTurns int) error

SetMaxTurns persists the per-spawn turn cap on the agent entry, creating it if missing. 0 = unlimited (provider default).

func SetModelID added in v0.34.0

func SetModelID(layout config.Layout, id, name, modelID string) error

SetModelID persists the pinned model id on the agent entry, creating it if missing. Empty = unset (the active provider's own default applies).

func SetModelIDIfEmpty added in v0.36.2

func SetModelIDIfEmpty(layout config.Layout, id, name, modelID string) error

SetModelIDIfEmpty pins a model only when the entry carries no pin.

Inherited defaults use this rather than SetModelID: a session already pinned to a model chose that deliberately, and a project default must not silently move it. No-op when the entry doesn't exist or already has a pin.

func SetNodeProvider added in v1.18.0

func SetNodeProvider(layout config.Layout, id, name, providerKey, modelID string) error

SetNodeProvider is SetAgentProvider (plus the model pin, when modelID is not empty) for a workflow node that re-applies the same provider on every run. An agent a failover moved off that very provider stays on its stand-in: rewriting the entry would send each run back to an account that is still limited, only to fail over again. The node's model then becomes the home's, and the return home brings both back once the account is usable. No-op when the entry doesn't exist.

func SetProject added in v0.14.21

func SetProject(_ context.Context, layout config.Layout, id, newProjectID string) error

SetProject changes the project a session points at. No filesystem work — the next agent spawn will resolve the new project's folder as cwd. Conversation, agent registry, and logs are preserved. Empty newProjectID unscopes the session.

func SetSystemAddon added in v0.36.0

func SetSystemAddon(layout config.Layout, id, addon string) error

SetSystemAddon replaces a session's free-text system-prompt addon.

Takes effect on the next spawn, like a preset edit. Used by delegation to give a sub-agent its role's system prompt: a role is not a named preset, so writing one would put a per-role file into the shared preset list where nobody expects it.

func SetThinkingTokens added in v0.18.7

func SetThinkingTokens(layout config.Layout, id, name, v string) error

SetThinkingTokens persists the resolved MAX_THINKING_TOKENS env value on the agent entry, creating it if missing. Empty = unset (provider default, thinking on); "0" = disabled; "<n>" = budget. Always persisted (including "") so switching a reused session back to full thinking clears a prior value.

func UpdateAgents added in v1.16.0

func UpdateAgents(layout config.Layout, id string, fn func([]AgentEntry) ([]AgentEntry, bool, error)) error

UpdateAgents is the locked read-modify-write of agents.json: fn gets the current entries and returns the new list and whether to save it. fn's error is returned as is, with nothing written. fn must not call another agents.json writer of the same session (the lock is not reentrant).

Types

type AgentEntry

type AgentEntry struct {
	Name             string            `json:"name"`
	Provider         string            `json:"provider"`
	CLISessionID     string            `json:"cli_session_id,omitempty"`
	Status           string            `json:"status"`
	CreatedAt        time.Time         `json:"created_at"`
	LastActive       time.Time         `json:"last_active,omitempty"`
	ProviderSessions map[string]string `json:"provider_sessions,omitempty"`
	// MaxTurns caps agentic turns on the next spawn (--max-turns).
	// 0 = unlimited (provider default). Set per workflow agent node.
	MaxTurns int `json:"max_turns,omitempty"`
	// ThinkingTokens is the resolved MAX_THINKING_TOKENS env value applied on
	// the next spawn (claude). Empty = unset (provider default, thinking on);
	// "0" = disabled; "<n>" = budget. Set per workflow agent node from its
	// thinking + max_thinking_tokens inputs.
	ThinkingTokens string `json:"thinking_tokens,omitempty"`
	// ModelID pins a specific model id this agent uses on its next spawn,
	// scoped to whichever provider Provider currently points at. Empty =
	// use that provider instance's own default-model resolution. Every
	// provider type honors it: wick maps it to a WickModel.ID, the CLI
	// providers pass it to their binary via --model. A switch rewrites it
	// (empty when none is asked for), so a later switch back doesn't
	// resurrect a stale/foreign pin.
	ModelID string `json:"model_id,omitempty"`
	// Failover is the agent's failover bookkeeping: the HOME provider the
	// session belongs on and what an automatic failover already tried.
	// nil on entries written before failover existed, and on agents that
	// never switched.
	Failover *FailoverState `json:"failover,omitempty"`
}

AgentEntry is one row in sessions/<id>/agents.json. CLISessionID is the resume key — wick captures it from the first stream-json event emitted by the CLI and persists it so subsequent spawns can pass `--resume <id>`. See agents-design.md §5.2.

ProviderSessions maps a provider TYPE ("claude", "codex") to that type's last-known CLI session ID. Each type mints and owns its own ids — the transcript stores are not interchangeable — so the outgoing id is parked here on every switch and read back when the session returns to that type. Each id is also kept under its full instance key ("claude/work"): instances of a type with no HistoryCarrier keep separate config dirs, so only the instance that minted an id can resume it. See ProviderScope / ProviderInstance / ResumeIDForScope.

type AgentGroup added in v1.2.9

type AgentGroup struct {
	Name string `json:"name"`
	// Members are agent ids of the owner, in the order the group lists
	// them; the first is the "first" default responder.
	Members []string `json:"members"`
	// DefaultResponder answers a message with no @: "captain" (the
	// Captain when a member, else the first member) or "first".
	DefaultResponder string `json:"default_responder"`
	// MaxHopsOverride lowers the agent-to-agent turn cap below the
	// smallest of the members'; 0 = none. It can never raise it.
	MaxHopsOverride int `json:"max_hops_override,omitempty"`
	// LastReadAt is when the owner last opened the group.
	LastReadAt *time.Time `json:"last_read_at,omitempty"`
}

AgentGroup is a group chat's settings (Meta.AgentGroup).

type ChannelRef added in v1.2.9

type ChannelRef struct {
	// Channel names the adapter ("slack", "telegram").
	Channel string `json:"channel"`
	// ChatID is the room/channel id inside that adapter (a Slack C…).
	ChatID string `json:"chat_id"`
	// ThreadID is the thread within the chat (a Slack thread_ts).
	ThreadID string `json:"thread_id,omitempty"`
	// Instance identifies WHICH configured bot owns the thread, so a
	// multi-instance host replies as the one that was there.
	Instance string `json:"instance,omitempty"`
	// LastSeenTS is the newest message ts in the thread the session has
	// already seen (the message that started a turn, or the bot's own
	// reply). The next turn catches up on what was said after it.
	LastSeenTS string `json:"last_seen_ts,omitempty"`
}

ChannelRef is where a session's replies belong: a chat channel and the thread inside it. Written by the channel that owns the session and read back when its in-memory state is unavailable.

type CreateOptions

type CreateOptions struct {
	ID        string
	ProjectID string
	Origin    Origin
	ChannelID string
	// Preset is the preset name to associate with this session.
	// Stored in meta.json; factory loads content from presets/<name>/agent.md on spawn.
	Preset string
	// UserID is the wick user who is creating this session. Stored in
	// meta.json for ownership checks in MCP handlers.
	UserID string
	// TokenID and TokenName record the credential behind the creation,
	// when the caller authenticated with one. See Meta.TokenID.
	TokenID   string
	TokenName string
	// ParentSessionID marks this session as a delegated sub-agent's
	// isolated context. See Meta.ParentSessionID.
	ParentSessionID string
	// AgentID and AgentMain bind the session to an Agents-app agent. See
	// Meta.AgentID.
	AgentID   string
	AgentMain bool
}

CreateOptions describes a new session. ProjectID is optional — a session may be created without one, in which case the pool falls back to the tools-config default project (or a per-session temp dir if no default is set).

type FailoverState added in v1.16.0

type FailoverState struct {
	// HomeProvider is the home instance's "type/name" key.
	HomeProvider string `json:"home_provider,omitempty"`
	// HomeModelID is the model pin the home runs with ("" = its default).
	HomeModelID string `json:"home_model_id,omitempty"`
	// Tried lists the instance keys this run already failed on, so one
	// message never visits an instance twice.
	Tried []string `json:"tried,omitempty"`
	// MsgKey identifies the user turn the run is for (the message plus a
	// mark unique to that send, so a repeated "ok" is a new run). A new
	// key starts a new run: Tried and Hops only count within one MsgKey.
	MsgKey string `json:"msg_key,omitempty"`
	// Hops is how many automatic switches this run made.
	Hops int `json:"hops,omitempty"`
	// Since is when this run's first failure happened (zero when no run
	// is in progress).
	Since time.Time `json:"since,omitempty"`
	// StandIns lists every instance a failover moved the agent onto
	// since it last sat on its home, in order. Unlike Tried it outlives
	// the run: a return home names them all, since none of their turns
	// is in the home's history. Cleared once back on the home.
	StandIns []string `json:"stand_ins,omitempty"`
}

FailoverState is the HOME of one session agent plus the progress of the failover run in flight. Home is what the user (or the session's creation) picked; an automatic failover moves Provider but never Home, so the chain followed is always Home's and the session can go back to it once it recovers. A manual switch makes the new provider the home and forgets the run.

Plain strings: provider imports this package, so the provider types cannot appear here.

func (*FailoverState) AwayFromHome added in v1.16.0

func (st *FailoverState) AwayFromHome() bool

AwayFromHome reports whether st records a failover run in progress.

func (*FailoverState) EndRun added in v1.16.0

func (st *FailoverState) EndRun()

EndRun forgets the run (Tried, Hops, MsgKey, Since) and keeps the home and StandIns.

func (*FailoverState) RunFor added in v1.16.0

func (st *FailoverState) RunFor(msgKey string, now time.Time) FailoverState

RunFor is the state as seen by the run for msgKey: st itself (a copy) when that run is the one recorded, otherwise the same home with a fresh run — no Tried, no Hops, Since = now. An empty msgKey never matches, so every call starts a new run. Both the reader (before PickTarget) and the writer (the switch that records a hop) go through here, so they cannot disagree on what "this run" holds. nil st = no home yet.

type Goal added in v0.35.2

type Goal struct {
	Goal      string     `json:"goal"`
	Status    GoalStatus `json:"status"`
	Note      string     `json:"note,omitempty"`
	UpdatedAt time.Time  `json:"updated_at"`
}

Goal is the on-disk record.

func LoadGoal added in v0.35.2

func LoadGoal(layout agentconfig.Layout, id string) (*Goal, error)

LoadGoal reads the session's goal latch. Missing file → (nil, nil).

func LoadGoalDir added in v0.35.2

func LoadGoalDir(sessionDir string) (*Goal, error)

LoadGoalDir reads goal.json from an absolute session directory (engine path — it already holds SessionDir, not layout+id).

type GoalStatus added in v0.35.2

type GoalStatus string

GoalStatus is the lifecycle of one session goal.

const (
	GoalOpen      GoalStatus = "open"
	GoalDone      GoalStatus = "done"
	GoalAbandoned GoalStatus = "abandoned"
)

type Meta

type Meta struct {
	// ProjectID references the project this session belongs to. Empty =
	// unscoped (pool falls back to the tools-config default project).
	ProjectID    string    `json:"project_id,omitempty"`
	Origin       Origin    `json:"origin"`
	ChannelID    string    `json:"channel_id,omitempty"`
	ActiveAgent  string    `json:"active_agent,omitempty"`
	Status       Status    `json:"status"`
	CreatedAt    time.Time `json:"created_at"`
	LastActive   time.Time `json:"last_active"`
	PendingInput []string  `json:"pending_input,omitempty"`
	// Label is the session title shown in the sidebar. By default it is
	// the first user message truncated to 60 runes (see
	// pool.setLabelIfEmpty), cached here so sidebar rendering never needs
	// to open conversation.jsonl. Once a human or the agent sets an
	// explicit title (TitleCustom=true) the auto-derived label no longer
	// overwrites it.
	Label string `json:"label,omitempty"`
	// TitleCustom marks Label as an explicit title set by a human or the
	// agent (via the wick_set_title MCP tool), as opposed to the
	// auto-derived first-message label. When true, the first-user-message
	// auto-label is skipped so it never clobbers the chosen title.
	TitleCustom bool `json:"title_custom,omitempty"`
	// Preset is the name of the preset active for this session.
	// Factory reads the preset content from presets/<name>/agent.md on
	// every spawn so edits to the preset take effect on next respawn.
	Preset string `json:"preset,omitempty"`
	// SystemAddon is free-text system-prompt content appended after the
	// preset on every spawn. Unlike Preset it is not a named file, so it
	// carries prompt text that belongs to THIS session and has no reason
	// to appear in the shared preset list — a sub-agent role's system
	// prompt, or a project's default addon.
	//
	// Read by the pool on each spawn, so an edit takes effect on the next
	// respawn exactly like a preset edit does.
	SystemAddon string `json:"system_addon,omitempty"`
	// Subscribers is the list of user IDs that opted in to receive
	// browser push notifications for this session's lifecycle
	// transitions (queue → working → idle). Persisted in meta.json so
	// the subscription survives wick restart. Sessions are shared
	// across users (anyone can open them) but pushes target only the
	// IDs in this list — no auto-subscribe on session create.
	Subscribers []string `json:"subscribers,omitempty"`
	// UserID is the wick user ID that created this session. Empty for
	// legacy sessions created before ownership tracking was added.
	// When non-empty, only the owning user (or app owner) may access it.
	UserID string `json:"user_id,omitempty"`
	// TokenID and TokenName name the credential this session was created
	// with, for callers that authenticate with one — today that means a
	// Personal Access Token on the REST channel. Empty everywhere else:
	// a person typing in the dashboard or in Slack IS the credential.
	//
	// Recorded because one account can hold many tokens, handed to a CI
	// job, a script, an integration. "Created by Yoga" does not tell an
	// admin which of those has been calling, and that is the question
	// asked when traffic looks wrong. TokenName is a copy of the label at
	// create time, so the record still reads if the token is later
	// revoked and its row deleted.
	TokenID   string `json:"token_id,omitempty"`
	TokenName string `json:"token_name,omitempty"`
	// Participants is every wick user who has spoken in this session, in
	// first-seen order, starting with UserID. A Slack thread is not
	// single-owner: anyone in the channel can reply into it, and that
	// reply is their work too — so it must show up under THEIR "Yours"
	// and stay openable by them, without taking the session away from
	// whoever started it.
	//
	// Kept alongside UserID rather than replacing it: UserID still
	// answers "whose identity does a spawn run as" (one answer only),
	// while this answers "whose conversation is this" (possibly several).
	// len>1 is what the UI renders as the shared-thread marker.
	//
	// Empty on sessions created before this shipped; readers must treat
	// that as "just UserID" rather than "nobody" (see Meta.People).
	Participants []string `json:"participants,omitempty"`
	// AutoReply marks a Slack channel thread as auto-reply: while true,
	// replies in the thread are dispatched to the agent without an
	// @mention. Set when the thread is created (the bot also drops a 🤖
	// marker on the parent) and toggled by adding/removing that marker.
	// Persisted here so the switch survives a wick restart even though
	// the channel's in-memory state is lost. Only meaningful for Slack
	// channel sessions; absent/false everywhere else.
	AutoReply bool `json:"auto_reply,omitempty"`
	// Listen mode (Slack) — what a "listen" request set for THIS thread on
	// top of the agent's LISTEN.md. ListenPrompt is extra instructions for
	// the thread; ListenDelaySec overrides the agent's delay (nil = keep it,
	// 0 = answer at once). ListenStopped records an explicit stop (word,
	// tool or 🤖), which wins over a channel/all scope that would otherwise
	// keep the thread listening.
	ListenPrompt   string `json:"listen_prompt,omitempty"`
	ListenDelaySec *int   `json:"listen_delay_sec,omitempty"`
	ListenStopped  bool   `json:"listen_stopped,omitempty"`
	// TeamHold marks the session as taken over by a person: while true, a
	// Team message another AGENT sends to it is recorded (its handoff row)
	// but no turn runs for it, and the task ends rejected. A person's own
	// @mention still runs. Toggled by the team connector's takeover op.
	TeamHold bool `json:"team_hold,omitempty"`
	// ChannelRef binds the session to the chat thread it belongs to, so a
	// reply can be delivered there even when the message did NOT arrive
	// from that chat.
	//
	// The channel keeps this mapping in memory per turn, which is enough
	// while one process handles both sides. It is not enough for two cases
	// that both end with an answer nobody receives: a reply typed in the
	// WEB UI of a Slack-originated session after a restart (the in-memory
	// map is gone, so the agent answers into the void), and a session
	// created by a WORKFLOW, whose turn was registered by a process that
	// has since handed over. Persisting the binding is what lets the
	// channel find the thread again.
	ChannelRef *ChannelRef `json:"channel_ref,omitempty"`
	// ScmRepo is the repository the Source panel has selected in this
	// session, relative to the session cwd ("" = none picked yet, which
	// reads as the first repo discovered). Server-side rather than
	// browser-local because the AGENT needs it too: it is what the
	// system prompt names as the repo being worked on, and what
	// wick_scm reports and switches.
	ScmRepo string `json:"scm_repo,omitempty"`
	// ScmGitConnectors maps a wick user id to the Git CLI connector
	// instance that user's push and pull run through in this session, or
	// the literal "native" for plain git.
	//
	// Per session rather than per repo: a session's checkouts are one
	// body of work, and asking again for each of dozens of repos is a
	// chore. Keyed by user because a session can be shared — a Slack
	// thread is open to everyone in the channel — and a credential is
	// exactly the thing that must not be inherited from whoever pushed
	// first. Absent = plain git, until someone picks otherwise.
	ScmGitConnectors map[string]string `json:"scm_git_connectors,omitempty"`
	// ParentSessionID links a sub-agent's isolated session back to the
	// session that delegated it. Non-empty = this is a child: hidden
	// from the conversation list and surfaced in the parent's Sub-agents
	// rail panel instead.
	//
	// This relation is the ONLY marker of "is a child" — there is
	// deliberately no separate `type: subagent` field, because two
	// sources of truth for the same fact can disagree. Absent on every
	// session created before sub-agents existed, which reads correctly
	// as "not a child".
	ParentSessionID string `json:"parent_session_id,omitempty"`
	// TicketID is a denormalised back-pointer to the ticket this session
	// belongs to (tickets live in internal/agents/ticket, one per folder
	// under the project). It exists so the sidebar and the pool can answer
	// "which ticket is this?" without scanning every ticket.
	//
	// NOT authoritative: the ticket's own Sessions list is the record. A
	// back-pointer the ticket does not confirm is treated as stale and
	// ignored — see notes.Resolve.
	TicketID string `json:"ticket_id,omitempty"`
	// AgentID names the Agents-app agent (entity.AgentPersona) this
	// session talks to. The MCP layer reads it to narrow connector access
	// to that agent's checklist; a sub-agent session carries none and
	// inherits its parent's through ParentSessionID (see
	// team.AgentOfSession). Absent = an ordinary session, unscoped.
	AgentID string `json:"agent_id,omitempty"`
	// AgentMain marks the agent's one main conversation — the chat the
	// Agents app opens when the agent is picked. Other sessions with the
	// same AgentID are side conversations started with "Chat baru".
	AgentMain bool `json:"agent_main,omitempty"`
	// AgentGroup makes the session a group chat of the owner's Team
	// agents. It never spawns a provider itself: each member answers in
	// its own backing session (GroupSessionID) with its own access, and
	// the replies are copied into this thread. nil = not a group.
	AgentGroup *AgentGroup `json:"agent_group,omitempty"`
	// TicketRoom makes this session the room of one ticket: a group chat
	// that lives in the ticket's project, whose members work for the
	// people who brought them in. Kept apart from AgentGroup, whose
	// single-owner rules do not fit a room. nil = not a ticket room.
	TicketRoom *TicketRoom `json:"ticket_room,omitempty"`
	// GroupSessionID marks a member's backing session: the group chat it
	// answers for. Hidden from the agent's own chat list.
	GroupSessionID string `json:"group_session_id,omitempty"`
	// TicketBacking marks a backing session made for a ticket room or an
	// ordinary ticket session: it answered another person there, read
	// everyone's text, and stays held to a room's rules even after its
	// parent leaves the ticket or is gone.
	TicketBacking bool `json:"ticket_backing,omitempty"`
	// LinkedFromSession pairs this chat of a Team agent with the
	// conversation that messages it (team_message or an @mention): later
	// messages from that conversation land here instead of the agent's
	// main chat. Kept on disk so the pair outlives a restart.
	LinkedFromSession string `json:"linked_from_session,omitempty"`
	// Links are the other sessions handling the same matter (the
	// sessionlink package): each knows the others exist, what they are
	// doing now, and can read their latest turns. Written to both sides.
	Links []SessionLink `json:"links,omitempty"`
}

Meta is the persisted-on-disk shape of a session. PendingInput is the message buffer that survives wick restart so a session that was queued at shutdown gets its messages drained on next boot.

func (*Meta) AddParticipant added in v1.2.9

func (m *Meta) AddParticipant(userID string) bool

AddParticipant appends userID to Participants if not already there. Returns true if the list changed (i.e. caller should persist Meta).

Seeds from People() rather than the raw slice so a legacy session's owner keeps first position instead of being appended after whoever happens to speak next.

func (*Meta) AddSubscriber added in v0.15.0

func (m *Meta) AddSubscriber(userID string) bool

AddSubscriber appends userID to Subscribers if not already present. Returns true if the list changed (i.e. caller should persist Meta).

func (*Meta) IsParticipant added in v1.2.9

func (m *Meta) IsParticipant(userID string) bool

IsParticipant reports whether userID has spoken in this session (or owns it — see People).

Deliberately does NOT go through People(): this runs once per session per list render, over every session the caller can see, so the owner-only fallback must not allocate a slice to answer one comparison.

func (*Meta) IsSubscribed added in v0.15.0

func (m *Meta) IsSubscribed(userID string) bool

IsSubscribed returns true when userID has opted in to receive lifecycle push notifications for this session.

func (*Meta) People added in v1.2.9

func (m *Meta) People() []string

People returns everyone who has spoken in this session, in first-seen order — Participants when it is populated, else the owner alone.

The fallback is what makes the field safe to add to a live install: every session that predates Participants carries only UserID, and answering "nobody" there would drop those rows out of their owner's list the moment the visibility checks start reading this.

func (*Meta) PeopleCount added in v1.2.9

func (m *Meta) PeopleCount() int

PeopleCount is len(People()) without building the slice — the count the UI needs for its shared-thread marker, on the same hot path as IsParticipant.

func (*Meta) RemoveSubscriber added in v0.15.0

func (m *Meta) RemoveSubscriber(userID string) bool

RemoveSubscriber drops userID from Subscribers. Returns true if the list changed.

func (*Meta) Shared added in v1.2.9

func (m *Meta) Shared() bool

Shared reports whether more than one person has spoken here — the condition behind the sidebar's multi-user marker.

type Origin

type Origin string

Origin identifies where the session was first created from. Slack threads use thread_ts as the session ID; UI/API sessions use a UUID generated by wick.

const (
	OriginSlack    Origin = "slack"
	OriginTelegram Origin = "telegram"
	OriginREST     Origin = "rest"
	OriginUI       Origin = "ui"
	// OriginSchedule marks a session the schedule runner created for a
	// project-scoped fire. Distinct so cleanup can tell disposable
	// scheduler output from a conversation someone started.
	OriginSchedule Origin = "schedule"
	// OriginWorkflow marks a session a workflow run created for its agent
	// nodes. Provider failover leaves these alone.
	OriginWorkflow Origin = "workflow"
)

type RoomMember added in v1.16.0

type RoomMember struct {
	Kind    string `json:"kind"`
	AgentID string `json:"agent_id,omitempty"`
	// OwnerID is the person the member works for ("" for a project
	// default, which works for whoever sends).
	OwnerID string `json:"owner_id"`
	// Home marks the member every room starts with; it cannot be removed.
	Home bool `json:"home,omitempty"`
}

RoomMember is one member of a ticket room. Identity is (AgentID, OwnerID), never the handle: everyone's Captain is "captain".

type Session

type Session struct {
	ID     string       `json:"id"`
	Meta   Meta         `json:"meta"`
	Agents []AgentEntry `json:"agents"`
}

Session is the in-memory view: ID + meta + agent registry. Mirrors the trio of files at sessions/<id>/.

func Create

func Create(_ context.Context, layout config.Layout, opt CreateOptions) (Session, error)

Create materializes sessions/<id>/: meta.json, agents.json (empty array), agent.md snapshot. No filesystem work touches the project folder — project folders live under projects/<id>/ and are shared across sessions; the session simply stores the project id as a reference.

func Load

func Load(layout config.Layout, id string) (Session, error)

Load reads meta.json + agents.json. Missing agents.json is treated as an empty list.

type SessionLink struct {
	// Session is the linked session's id.
	Session string `json:"session"`
	// Why says what ties the two together, for people and agents alike
	// ("same ticket T-1", "thread opened from this session", "manual: …").
	Why string    `json:"why,omitempty"`
	At  time.Time `json:"at"`
}

SessionLink is one entry of Meta.Links.

type Status

type Status string

Status is the high-level pool view: idle (no subprocess), queued (waiting for a slot), running (subprocess alive).

const (
	StatusIdle    Status = "idle"
	StatusQueued  Status = "queued"
	StatusRunning Status = "running"
)

type TicketRoom added in v1.16.0

type TicketRoom struct {
	TicketID string       `json:"ticket_id"`
	Members  []RoomMember `json:"members"`
	// ShareFull is, per user id, whether that person's agents read the
	// whole thread — other people's messages and agents included — or
	// only that person's own part of it (the default).
	ShareFull map[string]bool `json:"share_full,omitempty"`
}

TicketRoom is a ticket room's settings (Meta.TicketRoom).

func (*TicketRoom) Home added in v1.16.0

func (r *TicketRoom) Home() (RoomMember, bool)

Home returns the room's home member.

func (*TicketRoom) Member added in v1.16.0

func (r *TicketRoom) Member(agentID, ownerID string) (RoomMember, bool)

Member returns the agent member agentID working for ownerID.

type TodoDetail added in v1.2.9

type TodoDetail struct {
	Format string `json:"format,omitempty"` // text | markdown | json | html | xml
	Body   string `json:"body"`
}

TodoDetail is whatever the step wants to show that a one-line label cannot: a log tail, a JSON result, a small table. Format tells the UI how to render it; the body is stored as it arrived and truncated, never interpreted here.

type TodoItem added in v1.2.9

type TodoItem struct {
	ID          string        `json:"id,omitempty"`
	Title       string        `json:"title,omitempty"`
	Description string        `json:"description,omitempty"`
	Step        string        `json:"step,omitempty"`
	Status      string        `json:"status"`
	Substeps    []TodoSubstep `json:"substeps,omitempty"`
	Progress    *TodoProgress `json:"progress,omitempty"`
	Detail      *TodoDetail   `json:"detail,omitempty"`
}

TodoItem mirrors the tool's item shape, including the deprecated `step` label so a list recorded by an older caller still reads correctly.

func (TodoItem) Label added in v1.2.9

func (t TodoItem) Label() string

Label is what the item is called, whichever field carried it.

type TodoList added in v1.2.9

type TodoList struct {
	Items     []TodoItem `json:"items"`
	StartedAt time.Time  `json:"started_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	// Done is true when every item is completed. Kept on the record rather
	// than derived by each reader, so "was this finished or abandoned?"
	// survives into the history.
	Done bool `json:"done"`
	// Stopped marks a list somebody gave up on — the job died, the run was
	// cancelled, the card was stuck. Distinct from Done: "nobody is working
	// on this" and "this finished" look identical in a half-ticked list, and
	// only one of them means the work happened.
	Stopped   bool      `json:"stopped,omitempty"`
	StoppedAt time.Time `json:"stopped_at,omitempty"`
	Note      string    `json:"note,omitempty"`
}

TodoList is one checklist over its lifetime — the same list as it was updated, not one entry per update.

type TodoPatch added in v1.2.9

type TodoPatch struct {
	// Select is the item's id, or its label when it has no id. An item that
	// is not there yet is appended: a script reporting its first stage
	// should not have to create the list in a separate call.
	Select      string
	Title       string
	Description string
	Status      string
	Progress    *TodoProgress
	Detail      *TodoDetail
	Substeps    []TodoSubstep
}

TodoPatch updates ONE item of the active list without resending the rest.

The tool call that writes a whole checklist is the model's shape: it holds the list in its head. A build script does not — it knows "stage 2 of 6 is running" and nothing about the other five, and making it restate them would mean inventing them. So a patch names one item and touches only the fields it carries.

type TodoProgress added in v1.2.9

type TodoProgress struct {
	Done  int    `json:"done"`
	Total int    `json:"total"`
	Label string `json:"label,omitempty"` // "packages", "MB", …
}

TodoProgress is how far one item has got. A checklist answers "which step are we on"; this answers "how far into that step" — the difference between a spinner and a bar you can read a finishing time off.

type TodoSubstep added in v1.2.9

type TodoSubstep struct {
	Step   string `json:"step"`
	Status string `json:"status"`
}

TodoSubstep is one nested step under an item.

type Todos added in v1.2.9

type Todos struct {
	Active  *TodoList  `json:"active,omitempty"`
	History []TodoList `json:"history,omitempty"`
}

Todos is the session's whole checklist record.

func ClearTodos added in v1.2.9

func ClearTodos(layout agentconfig.Layout, id string, all bool) (*Todos, error)

ClearTodos drops the finished lists, and with all=true the active one too. The escape hatch for a panel full of runs nobody will look at again.

func LoadTodos added in v1.2.9

func LoadTodos(layout agentconfig.Layout, id string) (*Todos, error)

LoadTodos reads the session's checklists. Missing file → empty record, not an error: a session that has never used the tool is the normal case.

func PatchTodoItem added in v1.2.9

func PatchTodoItem(layout agentconfig.Layout, id string, p TodoPatch) (*Todos, error)

PatchTodoItem applies one patch to the session's active checklist, creating the list when there is none. Returns the whole record so the caller can report the state it produced.

func RecordTodos added in v1.2.9

func RecordTodos(layout agentconfig.Layout, id string, items []TodoItem) (*Todos, error)

RecordTodos stores a checklist the tool just received.

The hard part is deciding whether a call UPDATES the active list or STARTS a new one — the tool carries no list id, so the items have to answer it. A call that mentions any item the active list already has is the same list moving forward (that is what a checkpoint looks like: same steps, one more ticked). A call that shares nothing with it is a new list, and the old one goes to history rather than being overwritten and lost.

func StopTodos added in v1.2.9

func StopTodos(layout agentconfig.Layout, id, note string) (*Todos, error)

StopTodos marks the active list as given up on. The list stays visible — a stuck job is worth seeing — but it stops claiming to be in progress, and the next checklist starts fresh instead of merging into it.

Jump to

Keyboard shortcuts

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