session

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TodoPending    = "pending"
	TodoInProgress = "in_progress"
	TodoDone       = "done"
)

Todo statuses. Anything other than TodoDone counts as outstanding work.

View Source
const (
	FinishCompleted = "completed"
	FinishBlocked   = "blocked"
)

Run finish statuses.

View Source
const CLICurrentLinkName = "cli_current.jsonl"

CLICurrentLinkName is a symlink in the session store dir pointing at the JSONL file CLI should attach to on the next start.

View Source
const DefaultCLISessionID = agentkit.SessionID("cli:default")
View Source
const DefaultMaxStoredTextBytes = 8192

DefaultMaxStoredTextBytes caps text persisted in session history.

View Source
const DefaultSessionScope = ScopeChannel

DefaultSessionScope is the runner default when sessionScope is unset.

View Source
const InterruptedToolResultText = "tool execution was interrupted before it produced a result (process exited); re-run it if the result is still needed"

InterruptedToolResultText is the tool result synthesized for a call the process never got to answer. It is model-visible on purpose: the agent needs to know the call was cut off rather than silently succeeded.

View Source
const MetadataLogicalChars = "logical_chars"

MetadataLogicalChars stores pre-sanitize message size on user/assistant events.

View Source
const TenantToolWorkDir = "work"

TenantToolWorkDir is the workspace-relative directory for shell cwd and temp artifacts.

Variables

This section is empty.

Functions

func ActiveEntryKey added in v0.2.1

func ActiveEntryKey(route agentkit.RouteRef, policy RoutePolicy, userID string) agentkit.SessionID

ActiveEntryKey returns the stable key for /new active-session mapping.

func ActiveEntryKeyFromContext added in v0.2.1

func ActiveEntryKeyFromContext(ctx context.Context) agentkit.SessionID

ActiveEntryKeyFromContext derives the stable /new active-session mapping key from the turn route. Conversation may already be resolved to a child session.

func ActiveSessionEntryKey added in v0.1.6

func ActiveSessionEntryKey(platform string, delivery agentkit.SessionID, scope SessionScope, userID string) agentkit.SessionID

ActiveSessionEntryKey returns the stable session-store key used for /new active-session mapping.

func AgentIDFromContext added in v0.2.1

func AgentIDFromContext(ctx context.Context) agentkit.AgentID

AgentIDFromContext reports the agent executing the current turn.

func AppendAutoRetryEnd

func AppendAutoRetryEnd(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data AutoRetryEndData) error

func AppendAutoRetryStart

func AppendAutoRetryStart(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data AutoRetryStartData) error

func AppendCompaction

func AppendCompaction(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data compaction.EventData) error

func AppendOverflowRecovery

func AppendOverflowRecovery(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data OverflowRecoveryData) error

func AppendRunFinish

func AppendRunFinish(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data RunFinishData) error

func AppendSessionRecovery

func AppendSessionRecovery(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data RecoveryData) error

func AppendSkillLoad

func AppendSkillLoad(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, content skill.Content) error

func AppendStepEnd

func AppendStepEnd(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, step int) error

func AppendStepStart

func AppendStepStart(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, step int) error

func AppendSubagentEnd

func AppendSubagentEnd(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data SubagentEndData) error

func AppendSubagentStart

func AppendSubagentStart(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data SubagentStartData) error

func AppendSummarizationRetryEnd

func AppendSummarizationRetryEnd(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data SummarizationRetryEndData) error

func AppendSummarizationRetryStart

func AppendSummarizationRetryStart(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data SummarizationRetryStartData) error

func AppendTodoUpdate

func AppendTodoUpdate(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, items []Todo) error

func AppendToolCall

func AppendToolCall(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, call agentkit.ToolCall) error

func AppendToolResult

func AppendToolResult(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, result agentkit.ToolResult) error

func AppendTurnContinue

func AppendTurnContinue(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data TurnContinueData) error

func AppendTurnEnd

func AppendTurnEnd(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, steps int) error

func AppendTurnStart

func AppendTurnStart(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID) error

func AppendUsage

func AppendUsage(ctx context.Context, s agentkit.Session, agentID agentkit.AgentID, data UsageData) error

func ApplyEnvelopeToContext added in v0.2.1

func ApplyEnvelopeToContext(ctx context.Context, env agentkit.TurnEnvelope) context.Context

ApplyEnvelopeToContext stores the turn envelope on ctx.

func ApplyScope added in v0.1.3

func ApplyScope(delivery agentkit.SessionID, scope SessionScope, userID string) agentkit.SessionID

ApplyScope derives the effective session id used for Loop locking, history, and permission pending. delivery is the platform-owned routing id; userID fills in a missing :u: segment when present on the event envelope.

func BuildDeliverySessionID added in v0.1.3

func BuildDeliverySessionID(platform, channel, thread, user string) agentkit.SessionID

BuildDeliverySessionID is the canonical finest-grain id platforms should emit. Runner applies sessionScope to collapse it for scheduling and history.

Examples:

slack:C001
slack:C001:t:1712345678.9
slack:C001:t:1712345678.9:u:U456

func BuildSessionRoute added in v0.2.1

func BuildSessionRoute(in SessionRouteInput) agentkit.RouteRef

BuildSessionRoute builds a session-kind RouteRef from structured fields. When DeliveryID is empty, it is derived from platform/channel/thread/scope user.

func ChannelKeyMatches added in v0.1.10

func ChannelKeyMatches(jobChannelKey, contextChannelKey string) bool

ChannelKeyMatches reports whether a job belongs to the given channel key.

func ChildConversationID added in v0.2.1

func ChildConversationID(parentConversation, agentName string, seq int64) string

ChildConversationID returns a subagent conversation id under a parent.

func ContextWithDeliveryRoute added in v0.2.1

func ContextWithDeliveryRoute(ctx context.Context, platform string, delivery agentkit.SessionID) context.Context

ContextWithDeliveryRoute attaches a minimal session-kind delivery route to ctx.

func ConversationFromContext added in v0.2.1

func ConversationFromContext(ctx context.Context) string

ConversationFromContext reports the history/lock key for the current turn.

func ConversationFromEvent added in v0.2.1

func ConversationFromEvent(event agentkit.MessageEvent) agentkit.SessionID

ConversationFromEvent returns the conversation key for Loop locking and history.

func ConversationFromLoopRequest added in v0.2.1

func ConversationFromLoopRequest(req agentkit.LoopRequest) agentkit.SessionID

ConversationFromLoopRequest returns the conversation key for a queued turn.

func DecodeSessionRoute added in v0.2.1

func DecodeSessionRoute(route agentkit.RouteRef) (agentkit.SessionRouteTarget, bool)

DecodeSessionRoute decodes a session-kind RouteRef into SessionRouteTarget.

func DeliveryFromEnvelope added in v0.2.1

func DeliveryFromEnvelope(env agentkit.TurnEnvelope) agentkit.SessionID

DeliveryFromEnvelope returns the outbound delivery id from a turn envelope.

func DeliveryRouteFromContext added in v0.2.1

func DeliveryRouteFromContext(ctx context.Context) agentkit.SessionID

DeliveryRouteFromContext returns the platform delivery target from the turn envelope.

func DeliveryWithUser added in v0.1.3

func DeliveryWithUser(delivery agentkit.SessionID, userID string) agentkit.SessionID

DeliveryWithUser returns a delivery SessionID with the :u: segment set or replaced. Non-routable ids (cli:default, sub:...) are returned unchanged.

func EnvelopeFromContext added in v0.2.1

func EnvelopeFromContext(ctx context.Context) agentkit.TurnEnvelope

EnvelopeFromContext returns the current turn envelope, or zero when unset.

func EstimateLogicalChars added in v0.1.12

func EstimateLogicalChars(msg agentkit.ModelMessage) int

EstimateLogicalChars approximates model-visible size before session storage.

func HydrateLocalAttachments added in v0.1.12

func HydrateLocalAttachments(ctx context.Context, msgs []agentkit.ModelMessage, ws workspace.Service, maxImageBytes int) ([]agentkit.ModelMessage, error)

HydrateLocalAttachments reloads workspace images for LLM vision: attachment_ref on the latest user message, and read-tool image paths from the current tool batch since that user turn.

func InboundDeliveryID added in v0.2.1

func InboundDeliveryID(event agentkit.MessageEvent) agentkit.SessionID

InboundDeliveryID returns the platform delivery target from an inbound message.

func InterruptedToolResult

func InterruptedToolResult(call agentkit.ToolCall) agentkit.ToolResult

InterruptedToolResult is the stand-in result for a call that never ran to completion.

func LastAssistantText

func LastAssistantText(events []agentkit.SessionEvent, seq agentkit.EventSeq) string

LastAssistantText returns the text of the most recent assistant message after seq.

func LatestEventSeq

func LatestEventSeq(events []agentkit.SessionEvent) agentkit.EventSeq

func LatestSeq added in v0.1.9

func LatestSeq(ctx context.Context, s agentkit.Session) (agentkit.EventSeq, error)

LatestSeq returns the highest durable event sequence for the session.

func MetadataFromContext added in v0.2.1

func MetadataFromContext(ctx context.Context) map[string]any

MetadataFromContext returns platform metadata for the current turn.

func NewCLISessionID

func NewCLISessionID() agentkit.SessionID

NewCLISessionID returns a fresh opaque CLI session id.

func NewConversationID added in v0.2.1

func NewConversationID(current string) string

NewConversationID returns a fresh conversation id for /new.

func NewJSONL

func NewJSONL(cfg JSONLConfig) (agentkit.Session, error)

NewJSONL registers session/jsonl: Append-only JSONL event log for one session.

Best practices:

  • Reopening a file resumes event sequence numbering, so seq stays unique across restarts.

func NewMemory

func NewMemory(cfg MemoryConfig) (agentkit.Session, error)

NewMemory registers session/memory: Ephemeral in-memory session. Nothing survives the process.

func NewSessionID added in v0.1.6

func NewSessionID(base agentkit.SessionID) agentkit.SessionID

NewSessionID returns a fresh logical session id derived from the current stable session key. CLI keeps its historic cli:<timestamp> format.

func NewStatic

func NewStatic(_ StaticConfig, deps StaticDeps) (agentkit.SessionStore, error)

NewStatic registers session/static: Wrap one pre-built Session as a store that returns it for every id.

Best practices:

  • For tests and single-session hosts; every session id maps to the same log.

func NewStore

func NewStore(cfg StoreConfig, deps StoreDeps) (agentkit.SessionStore, error)

NewStore registers session/store: Resolve durable JSONL sessions by id; contributes /new and /session.

func OutboundFromEnvelope added in v0.2.1

func OutboundFromEnvelope(env agentkit.TurnEnvelope, typ agentkit.EventType, data []byte) agentkit.OutboundEvent

func OutboundRouteID added in v0.2.1

func OutboundRouteID(event agentkit.OutboundEvent) agentkit.SessionID

OutboundRouteID returns the platform routing target for an outbound event.

func PlatformFromContext added in v0.2.1

func PlatformFromContext(ctx context.Context) string

PlatformFromContext reports the platform id for the current turn.

func ReadAllEvents

func ReadAllEvents(ctx context.Context, s agentkit.Session) ([]agentkit.SessionEvent, error)

func RegisterPlatformPolicy added in v0.2.1

func RegisterPlatformPolicy(platform string, policy PlatformSessionPolicy)

RegisterPlatformPolicy registers or overrides routing policy for a platform id.

func RepeatedToolCalls

func RepeatedToolCalls(events []agentkit.SessionEvent, seq agentkit.EventSeq) int

RepeatedToolCalls returns how many times the most recent tool call signature repeats consecutively at the tail of the log after seq.

func ResolveActiveSessionID added in v0.1.23

func ResolveActiveSessionID(ctx context.Context, store agentkit.SessionStore, entryKey agentkit.SessionID) (agentkit.SessionID, error)

ResolveActiveSessionID maps a stable active-session entry key to the current history SessionID. When no /new mapping exists, entryKey is returned unchanged.

func ResolveEnvelope added in v0.2.1

func ResolveEnvelope(event agentkit.MessageEvent, policy RoutePolicy) agentkit.TurnEnvelope

ResolveEnvelope builds a TurnEnvelope from an inbound MessageEvent and policy.

func RouteRefFromContext added in v0.2.1

func RouteRefFromContext(ctx context.Context) agentkit.RouteRef

RouteRefFromContext returns the outbound route from the turn envelope.

func RouteReplyTo added in v0.2.1

func RouteReplyTo(route agentkit.RouteRef) string

RouteReplyTo returns the ephemeral reply anchor for this turn, if any.

func RouteSessionID added in v0.2.1

func RouteSessionID(route agentkit.RouteRef) (agentkit.SessionID, bool)

RouteSessionID decodes a session-kind RouteRef into a delivery SessionID.

func RunStartSeq

func RunStartSeq(events []agentkit.SessionEvent) agentkit.EventSeq

RunStartSeq returns the seq of the most recent inbound user message.

func SanitizeModelMessageForStorage added in v0.1.12

func SanitizeModelMessageForStorage(msg agentkit.ModelMessage, maxTextBytes int) agentkit.ModelMessage

SanitizeModelMessageForStorage removes bulky media payloads and truncates long text before writing user/assistant messages to durable session history.

func SessionIDFromContext added in v0.2.1

func SessionIDFromContext(ctx context.Context) agentkit.SessionID

SessionIDFromContext reports the history/lock key for the current turn.

func SessionRouteFromDelivery added in v0.2.1

func SessionRouteFromDelivery(platform string, delivery agentkit.SessionID, replyTo string) agentkit.RouteRef

SessionRouteFromDelivery builds a session route from a delivery SessionID.

func SlackSessionID

func SlackSessionID(channelID, threadTS string) agentkit.SessionID

SlackSessionID builds a stable session key from Slack channel and optional thread timestamp. Use threadTS from event.ThreadTimeStamp; for top-level channel messages pass "".

func SlackSessionIDForScope

func SlackSessionIDForScope(scope SessionScope, channelID, threadTS, userID string) agentkit.SessionID

SlackSessionIDForScope builds the effective session id for Slack components. Prefer ApplyScope(BuildDeliverySessionID(...), scope, userID) in new code; this helper remains for tests and direct agent invocations.

func StepCount

func StepCount(events []agentkit.SessionEvent, seq agentkit.EventSeq) int

StepCount counts the steps completed after seq.

func SumLogicalCharsFromEvents added in v0.1.12

func SumLogicalCharsFromEvents(events []agentkit.SessionEvent, agentID agentkit.AgentID) int

SumLogicalCharsFromEvents totals logical message size for compaction estimates.

func SyncMessageEvent added in v0.2.1

func SyncMessageEvent(event agentkit.MessageEvent, env agentkit.TurnEnvelope) agentkit.MessageEvent

func TrimCompacted added in v0.1.9

func TrimCompacted(s agentkit.Session, agentID agentkit.AgentID, beforeSeq agentkit.EventSeq)

TrimCompacted drops model-visible history superseded by a compaction marker.

func UserIDFromContext added in v0.2.1

func UserIDFromContext(ctx context.Context) string

UserIDFromContext reports the end-user id for the current turn.

func WithAgentID added in v0.2.1

func WithAgentID(ctx context.Context, agentID agentkit.AgentID) context.Context

WithAgentID returns ctx with an updated envelope agent id.

func WithConversation added in v0.2.1

func WithConversation(ctx context.Context, conversation string) context.Context

WithConversation returns ctx with an updated envelope conversation.

func WithRoute added in v0.2.1

func WithRoute(ctx context.Context, route agentkit.RouteRef) context.Context

WithRoute returns ctx with an updated envelope route.

func WithWorkspace added in v0.2.1

func WithWorkspace(ctx context.Context, workspace string) context.Context

WithWorkspace returns ctx with an updated envelope workspace.

func WorkspaceDirName added in v0.2.1

func WorkspaceDirName(key string) string

WorkspaceDirName maps a workspace key to a single safe path segment.

func WorkspaceFromContext added in v0.2.1

func WorkspaceFromContext(ctx context.Context) string

WorkspaceFromContext reports the tenant workspace key for the current turn. Runner should set TurnEnvelope.Workspace explicitly; fallback derivation logs a warning.

func WorkspaceKey added in v0.2.1

func WorkspaceKey(sessionID string) string

WorkspaceKey derives the workspace isolation key from an opaque SessionID by a fixed rule: the platform segment plus the first routing segment.

slack:C123ABC              -> slack:C123ABC
slack:C123ABC:U456         -> slack:C123ABC
slack:C123ABC:t:171234.56  -> slack:C123ABC
cli:default                -> cli:default
                           -> "" (no session, no workspace key)

Every Slack session scope therefore lands on the same workspace key for a given channel, which is why session granularity and workdir granularity can be chosen independently.

This is the only place the rule lives. Platforms stay free to encode whatever they like after the second segment; nothing here parses further.

func WorkspaceLocalDirName added in v0.2.1

func WorkspaceLocalDirName(key string, omitPlatform bool) string

WorkspaceLocalDirName maps a workspace key to a single safe path segment under localBase. When omitPlatform is true, only the first routing segment is used.

Types

type ActiveEntryMode added in v0.2.1

type ActiveEntryMode string

ActiveEntryMode selects which key active-session mapping uses.

const (
	ActiveEntryEffective ActiveEntryMode = "effective"
	ActiveEntryDelivery  ActiveEntryMode = "delivery"
)

type ActiveSessionData added in v0.1.6

type ActiveSessionData struct {
	SessionID agentkit.SessionID `json:"sessionId"`
}

type AgentBindData added in v0.1.6

type AgentBindData struct {
	AgentID agentkit.AgentID `json:"agentId"`
}

AgentBindData is stored in each session work dir as agent.json.

type AutoRetryEndData

type AutoRetryEndData struct {
	Success    bool   `json:"success"`
	Attempt    int    `json:"attempt"`
	FinalError string `json:"finalError,omitempty"`
}

type AutoRetryStartData

type AutoRetryStartData struct {
	Attempt      int    `json:"attempt"`
	MaxAttempts  int    `json:"maxAttempts"`
	DelayMs      int    `json:"delayMs"`
	ErrorMessage string `json:"errorMessage"`
}

type CLICurrentStore

type CLICurrentStore interface {
	ResolveCLICurrent(ctx context.Context) (agentkit.SessionID, error)
	SetCLICurrent(ctx context.Context, id agentkit.SessionID) error
}

CLICurrentStore tracks which CLI session is active across process restarts.

type DeliveryParts added in v0.1.5

type DeliveryParts struct {
	Platform string
	Channel  string
	Thread   string
	User     string
	Routable bool
}

DeliveryParts holds parsed segments of a platform delivery SessionID.

func ParseDelivery added in v0.1.5

func ParseDelivery(id agentkit.SessionID, fallbackUser string) DeliveryParts

ParseDelivery splits a delivery SessionID into routing segments. fallbackUser fills a missing :u: segment when present on the event envelope.

type FileBacked

type FileBacked interface {
	FilePath() string
}

FileBacked is implemented by sessions that persist to a file path.

type IncompleteTurn

type IncompleteTurn struct {
	TurnStartSeq agentkit.EventSeq
	AgentID      agentkit.AgentID
	StepsStarted int
	StepsEnded   int
	// OpenStep is the index of a step/start with no step/end, or -1 when the
	// last step closed cleanly.
	OpenStep int
	// OrphanCalls are tool calls in the derived history that no tool result
	// answers. Left alone they make the history unusable: providers reject an
	// assistant message whose tool calls have no replies.
	OrphanCalls []agentkit.ToolCall
}

IncompleteTurn describes a turn that never reached turn/end, which is what a crash, SIGKILL, or power loss leaves behind.

func ScanIncomplete

func ScanIncomplete(events []agentkit.SessionEvent) *IncompleteTurn

ScanIncomplete reports the trailing unterminated turn, or nil when the log ends cleanly. Only the last turn can be incomplete: every earlier turn either wrote turn/end or was repaired on a previous startup.

type IndexedMessage added in v0.1.9

type IndexedMessage = compaction.IndexedMessage

IndexedMessage is a model-visible message with its primary source event seq.

func IndexMessagesForCompaction added in v0.1.9

func IndexMessagesForCompaction(ctx context.Context, events []agentkit.SessionEvent) []IndexedMessage

IndexMessagesForCompaction rebuilds the model-visible list used for compaction, including the latest compaction summary and retained tail when present.

type JSONL

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

JSONL persists session events as append-only JSON lines.

func (*JSONL) Append

func (s *JSONL) Append(ctx context.Context, event agentkit.SessionEvent) (agentkit.EventSeq, error)

func (*JSONL) DeriveMessages

func (s *JSONL) DeriveMessages(ctx context.Context) ([]agentkit.ModelMessage, error)

func (*JSONL) FilePath

func (s *JSONL) FilePath() string

func (*JSONL) ID

func (s *JSONL) ID() agentkit.SessionID

func (*JSONL) LatestSeq added in v0.1.9

func (s *JSONL) LatestSeq() agentkit.EventSeq

LatestSeq returns the highest event sequence in the durable log.

func (*JSONL) Read

func (s *JSONL) Read(ctx context.Context, from agentkit.EventSeq) ([]agentkit.SessionEvent, error)

type JSONLConfig

type JSONLConfig struct {
	// Path is the log file itself, not a directory.
	Path string `json:"path"`
	// ID is fixed session id.
	ID agentkit.SessionID `json:"id"`
	// MaxLoadedEvents limits non-compaction events kept in memory on load. Zero loads the full file.
	MaxLoadedEvents int `json:"maxLoadedEvents"`
}

type Memory

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

Memory is an in-memory session backend for tests and ephemeral runs.

func (*Memory) Append

func (*Memory) DeriveMessages

func (s *Memory) DeriveMessages(ctx context.Context) ([]agentkit.ModelMessage, error)

func (*Memory) ID

func (s *Memory) ID() agentkit.SessionID

func (*Memory) LatestSeq added in v0.1.9

func (s *Memory) LatestSeq() agentkit.EventSeq

LatestSeq returns the highest event sequence issued by this session.

func (*Memory) Read

type MemoryConfig

type MemoryConfig struct {
	// ID is fixed session id.
	ID agentkit.SessionID `json:"id"`
	// MaxToolResultBytes truncates tool results as they are appended.
	MaxToolResultBytes int `json:"maxToolResultBytes"`
}

type OverflowRecoveryData

type OverflowRecoveryData struct {
	Applied int    `json:"applied"`
	Reason  string `json:"reason,omitempty"`
	Error   string `json:"error,omitempty"`
}

type PlatformSessionPolicy added in v0.2.1

type PlatformSessionPolicy struct {
	ActiveEntryMode ActiveEntryMode
}

PlatformSessionPolicy holds per-platform routing overrides applied on top of runner defaults.

func PlatformSessionPolicyFor added in v0.2.1

func PlatformSessionPolicyFor(platform string) PlatformSessionPolicy

PlatformSessionPolicyFor returns overrides for a platform, or zero when unset.

type RecoveryData

type RecoveryData struct {
	TurnStartSeq  agentkit.EventSeq `json:"turnStartSeq"`
	Steps         int               `json:"steps"`
	OrphanResults int               `json:"orphanResults"`
	ClosedStep    int               `json:"closedStep"`
	Reason        string            `json:"reason"`
}

RecoveryData is the audit payload of a session/recovery event.

func RepairIncomplete

func RepairIncomplete(ctx context.Context, s agentkit.Session, turn *IncompleteTurn) (RecoveryData, error)

RepairIncomplete makes an interrupted turn replayable and closes it: it answers every orphan tool call, ends the open step, writes turn/end, then records a session/recovery event for audit.

type RoutePolicy added in v0.2.1

type RoutePolicy struct {
	ConversationScope SessionScope
	WorkspaceScope    WorkspaceScope
	ActiveEntryMode   ActiveEntryMode
}

RoutePolicy configures how inbound routes map to conversation and workspace.

func DefaultRoutePolicy added in v0.2.1

func DefaultRoutePolicy(conversationScope SessionScope) RoutePolicy

DefaultRoutePolicy is runner's default: channel conversation and workspace.

func RoutePolicyForPlatform added in v0.2.1

func RoutePolicyForPlatform(platform string, base RoutePolicy) RoutePolicy

RoutePolicyForPlatform merges runner defaults with platform-specific overrides.

type RouteTarget added in v0.2.1

type RouteTarget struct {
	DeliveryID  agentkit.SessionID
	ChannelID   string
	ThreadID    string
	ReplyTo     string
	ScopeUserID string
}

RouteTarget is the decoded delivery target for a session-kind route.

func RouteTargetFromRoute added in v0.2.1

func RouteTargetFromRoute(route agentkit.RouteRef) (RouteTarget, bool)

RouteTargetFromRoute decodes structured delivery fields from a session route.

type RunFinishData

type RunFinishData struct {
	Status  string `json:"status"`
	Summary string `json:"summary,omitempty"`
}

RunFinishData is the payload of an EventRunFinish event.

func FinishAfter

func FinishAfter(events []agentkit.SessionEvent, seq agentkit.EventSeq) *RunFinishData

FinishAfter returns the run/finish event recorded after seq, or nil.

type RunState added in v0.2.1

type RunState struct {
	StartSeq agentkit.EventSeq
	Todos    []Todo
	Pending  []Todo
	Finish   *RunFinishData
	Repeats  int
	Usage    UsageData
	Context  int
}

RunState is a snapshot of autonomous-run signals from the session log.

func LoadRunState added in v0.2.1

func LoadRunState(ctx context.Context, store agentkit.SessionStore, sessionID agentkit.SessionID) (RunState, error)

LoadRunState reads autonomous-run signals for the given session.

type SessionRouteInput added in v0.2.1

type SessionRouteInput struct {
	Platform    string
	DeliveryID  agentkit.SessionID
	ChannelID   string
	ThreadID    string
	ReplyTo     string
	ScopeUserID string
}

SessionRouteInput carries structured session-kind route fields.

type SessionScope

type SessionScope string

SessionScope selects how delivery SessionIDs collapse for Loop scheduling and session history. It is configured on runner.config.sessionScope and is deliberately independent of the working directory: every scope below derives the same tenant key, so a channel keeps one workdir no matter how finely its history is split.

const (
	// ScopeChannel gives the whole channel a single session. Everyone in the
	// group shares one history and is told apart by per-message user
	// attribution, which is what makes "两个人在同一个群里接着聊" work.
	ScopeChannel SessionScope = "channel"
	// ScopeThread gives each thread its own session, with the channel's
	// top-level messages sharing one. This is the usual choice for a busy
	// channel where unrelated tasks run side by side.
	ScopeThread SessionScope = "thread"
	// ScopeUser gives each person their own session inside the channel: shared
	// working directory, private history.
	ScopeUser SessionScope = "user"
)

func ParseScope added in v0.1.3

func ParseScope(raw string) SessionScope

ParseScope normalizes runner config. Unknown values fall back to channel scope.

type StaticConfig

type StaticConfig struct{}

type StaticDeps

type StaticDeps struct {
	Session agentkit.Session `json:"session"`
}

type StaticStore

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

StaticStore returns one Session for matching IDs. Useful for CLI presets and tests where a single session instance is wired through pluginkit.

func NewStaticStore

func NewStaticStore(sess agentkit.Session) *StaticStore

func (*StaticStore) ActiveSession added in v0.1.6

func (s *StaticStore) ActiveSession(_ context.Context, id agentkit.SessionID) (agentkit.SessionID, error)

func (*StaticStore) AgentBind added in v0.1.6

func (*StaticStore) Get

func (*StaticStore) SetActiveSession added in v0.1.6

func (s *StaticStore) SetActiveSession(_ context.Context, id, active agentkit.SessionID) error

func (*StaticStore) SetAgentBind added in v0.1.6

func (s *StaticStore) SetAgentBind(_ context.Context, id agentkit.SessionID, agent agentkit.AgentID) error

type StepEndData

type StepEndData struct {
	Step int `json:"step"`
}

type StepStartData

type StepStartData struct {
	Step int `json:"step"`
}

type Store

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

Store opens one JSONL session file per SessionID under Dir. Suitable for IM platforms where each channel/thread maps to a distinct session.

func (*Store) ActiveSession added in v0.1.6

func (s *Store) ActiveSession(ctx context.Context, id agentkit.SessionID) (agentkit.SessionID, error)

func (*Store) AgentBind added in v0.1.6

func (s *Store) AgentBind(ctx context.Context, id agentkit.SessionID) (agentkit.AgentID, error)

func (*Store) Commands

func (s *Store) Commands() []agentkit.Command

func (*Store) Get

func (*Store) ResolveCLICurrent

func (s *Store) ResolveCLICurrent(ctx context.Context) (agentkit.SessionID, error)

ResolveCLICurrent returns the session id behind cli_current.jsonl, or DefaultCLISessionID when the link is missing. A missing link is also written so the default session file is discoverable without knowing the id format.

func (*Store) SetActiveSession added in v0.1.6

func (s *Store) SetActiveSession(ctx context.Context, id, active agentkit.SessionID) error

func (*Store) SetAgentBind added in v0.1.6

func (s *Store) SetAgentBind(ctx context.Context, id agentkit.SessionID, agent agentkit.AgentID) error

func (*Store) SetCLICurrent

func (s *Store) SetCLICurrent(ctx context.Context, id agentkit.SessionID) error

SetCLICurrent updates cli_current.jsonl to point at the JSONL for id.

type StoreConfig

type StoreConfig struct {
	// Dir is root directory holding one file per session, resolved through the workspace.
	Dir string `json:"dir"`
	// MaxCachedSessions limits in-memory hot sessions (LRU). Zero keeps every opened session cached.
	MaxCachedSessions int `json:"maxCachedSessions"`
	// CacheIdleTTL evicts sessions unused for this duration (for example "30m"). Empty disables idle eviction.
	CacheIdleTTL string `json:"cacheIdleTTL"`
	// MaxLoadedEvents limits non-compaction events kept in memory per session on load. Zero loads the full file.
	MaxLoadedEvents int `json:"maxLoadedEvents"`
}

type StoreDeps

type StoreDeps struct {
	Workspace workspace.Service `json:"workspace"`
}

type SubagentEndData

type SubagentEndData struct {
	Agent   string `json:"agent"`
	Session string `json:"session"`
	Status  string `json:"status"`
	Summary string `json:"summary,omitempty"`
	Steps   int    `json:"steps"`
	Error   string `json:"error,omitempty"`
	JobID   string `json:"jobId,omitempty"`
}

SubagentEndData records the outcome of a delegation. Summary duplicates what the model sees in the tool result, on purpose: reading the parent log alone should be enough to reconstruct what came back.

type SubagentStartData

type SubagentStartData struct {
	Agent   string `json:"agent"`
	Session string `json:"session"`
	Task    string `json:"task"`
	Async   bool   `json:"async,omitempty"`
	JobID   string `json:"jobId,omitempty"`
}

SubagentStartData records a delegation on the *parent* session. The child's own work lives in its own session; these two events are the audit trail linking the two logs together.

type SummarizationRetryEndData

type SummarizationRetryEndData struct {
	Success    bool   `json:"success"`
	Attempt    int    `json:"attempt"`
	FinalError string `json:"finalError,omitempty"`
}

type SummarizationRetryStartData

type SummarizationRetryStartData struct {
	Attempt      int    `json:"attempt"`
	MaxAttempts  int    `json:"maxAttempts"`
	DelayMs      int    `json:"delayMs"`
	ErrorMessage string `json:"errorMessage"`
}

type Todo

type Todo struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Status string `json:"status"`
}

Todo is one entry of the durable task list written by tool/todo.

func LatestTodos

func LatestTodos(events []agentkit.SessionEvent) []Todo

LatestTodos returns the task list from the most recent todo/update event.

func PendingTodos

func PendingTodos(items []Todo) []Todo

PendingTodos filters LatestTodos down to entries that still need work.

func (Todo) Done

func (t Todo) Done() bool

Done reports whether this entry no longer needs work.

type TodoUpdateData

type TodoUpdateData struct {
	Items []Todo `json:"items"`
}

TodoUpdateData is the payload of an EventTodoUpdate event.

type TurnContinueData

type TurnContinueData struct {
	Segment  int                     `json:"segment"`
	Reason   string                  `json:"reason"`
	Steps    int                     `json:"steps"`
	Messages []agentkit.ModelMessage `json:"messages,omitempty"`
}

TurnContinueData records one autonomous turn extension.

type TurnEndData

type TurnEndData struct {
	Steps int `json:"steps"`
}

type TurnStartData

type TurnStartData struct{}

type UsageData

type UsageData struct {
	InputTokens  int `json:"inputTokens"`
	OutputTokens int `json:"outputTokens"`
	TotalTokens  int `json:"totalTokens"`
}

UsageData records token accounting for one model step.

func LatestUsage

func LatestUsage(events []agentkit.SessionEvent) UsageData

LatestUsage returns the most recent usage event.

func TotalUsage

func TotalUsage(events []agentkit.SessionEvent, seq agentkit.EventSeq) UsageData

TotalUsage sums usage events recorded after seq.

type WorkspaceScope added in v0.2.1

type WorkspaceScope string

WorkspaceScope selects how Workspace is derived from a delivery route.

const (
	WorkspaceScopeChannel WorkspaceScope = "channel"
)

Jump to

Keyboard shortcuts

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