session

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const FileSnapshotVersion = 1

Variables

This section is empty.

Functions

func ApplySnapshotToSession added in v1.8.11

func ApplySnapshotToSession(ctx context.Context, s *Session, snap *FileSnapshot) error

func SaveFileSnapshot added in v1.8.11

func SaveFileSnapshot(path string, snap *FileSnapshot) error

Types

type Budget

type Budget interface {
	CanExecute(sessionID string) bool
}

type Config

type Config struct {
	InputBufferSize    int
	OutputBufferSize   int
	EnableQueue        bool
	QueueSize          int
	MaxPending         int
	PlannerEnabled     bool
	PlannerPrompt      string
	PlannerAutoApprove bool
	// UserID 显式归属的 user;空 = 未显式指定(回退配置 DefaultUserID,再回退 "default")。
	// P3.2 user 全局合并:归属在 session 创建时固化(INSERT OR IGNORE),不动态变更。
	UserID string
}

func DefaultConfig

func DefaultConfig() *Config

type Event

type Event struct {
	Type       EventType      `json:"type"`
	SessionID  string         `json:"session_id"`
	Content    string         `json:"content,omitempty"`
	Thinking   string         `json:"thinking,omitempty"`
	ToolCallID string         `json:"tool_call_id,omitempty"`
	ToolName   string         `json:"tool_name,omitempty"`
	ToolInput  map[string]any `json:"tool_input,omitempty"`
	ToolOutput any            `json:"tool_output,omitempty"`
	Error      string         `json:"error,omitempty"`
	Approved   bool           `json:"approved,omitempty"`
	Usage      *Usage         `json:"usage,omitempty"`
	Plan       *Plan          `json:"plan,omitempty"`
	StopCause  string         `json:"stop_cause,omitempty"`
	// Question question 工具向用户提问的内容(P2.1)。配套 QuestionID 供回答注入。
	QuestionID string `json:"question_id,omitempty"`
	Question   string `json:"question,omitempty"`
	// Source 事件来源(S4/B2,subagent-s3s4 §7.7)。默认 "user"(向后兼容,
	// 缺失字段 = user)。唤醒注入 turn = "subagent",供消费方(client.go /
	// turn_observe.go)识别并折叠,避免"幽灵用户消息"喷到 UI 与 assistant-text。
	Source    EventSource `json:"source,omitempty"`
	Timestamp time.Time   `json:"timestamp"`
}

func (*Event) IsApproval

func (e *Event) IsApproval() bool

func (*Event) IsDone

func (e *Event) IsDone() bool

func (*Event) IsError

func (e *Event) IsError() bool

func (*Event) IsMessage

func (e *Event) IsMessage() bool

func (*Event) IsPlan

func (e *Event) IsPlan() bool

func (*Event) IsThinking

func (e *Event) IsThinking() bool

func (*Event) IsTokenUsage

func (e *Event) IsTokenUsage() bool

func (*Event) IsToolCall

func (e *Event) IsToolCall() bool

func (*Event) IsToolResult

func (e *Event) IsToolResult() bool

func (*Event) String

func (e *Event) String() string

type EventSource added in v1.10.0

type EventSource string

EventSource 事件来源标记(S4/B2)。默认 user 保持现有行为。

const (
	// EventSourceUser 用户输入触发的 turn(默认)。
	EventSourceUser EventSource = "user"
	// EventSourceSubagent 子代理完成唤醒注入的 turn。
	EventSourceSubagent EventSource = "subagent"
)

type EventType

type EventType string
const (
	EventTypeMessage    EventType = "message"
	EventTypeThinking   EventType = "thinking"
	EventTypeToolCall   EventType = "tool_call"
	EventTypeToolResult EventType = "tool_result"
	EventTypeToolStart  EventType = "tool_start"
	EventTypeTokenUsage EventType = "token_usage"
	EventTypeError      EventType = "error"
	EventTypeDone       EventType = "done"
	EventTypeApproved   EventType = "approved"
	EventTypeApproval   EventType = "approval"
	EventTypePlan       EventType = "plan"
	EventTypePlanStep   EventType = "plan_step"
	// EventTypeQuestion question 工具向用户提问(P2.1,异步事件模型)。
	// session 检测到 SentinelQuestionResult 时 emit;UI 经 onQuestion 回调拿到
	// 问题,随后用 AnswerQuestion 把回答注入(作为下一条 user 消息喂回)。
	EventTypeQuestion EventType = "question"
)

type ExecuteResponse

type ExecuteResponse struct {
	SessionID string
	Content   string
	ToolCalls []ToolCallInfo
	Usage     Usage
	Error     error
}

type FileSnapshot added in v1.8.11

type FileSnapshot struct {
	Version              int             `json:"version"`
	SessionID            string          `json:"session_id"`
	Messages             []types.Message `json:"messages"`
	Usage                types.Usage     `json:"usage"`
	MemoryCompletedTurns uint32          `json:"memory_completed_turns"`
}

FileSnapshot is a restart/recovery aid. Messages are whatever GetChatHistory returns (windowed LLM view), not a full dump of all rows in persistent storage.

func BuildSnapshotFromSession added in v1.8.11

func BuildSnapshotFromSession(ctx context.Context, s *Session) (*FileSnapshot, error)

func LoadFileSnapshot added in v1.8.11

func LoadFileSnapshot(path string) (*FileSnapshot, error)

type Info

type Info struct {
	ID        string    `json:"id"`
	Title     string    `json:"title"`
	Summary   *Summary  `json:"summary,omitempty"`
	Time      Time      `json:"time"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func NewInfo

func NewInfo(id, title string) *Info

func (*Info) Archive

func (s *Info) Archive()

func (*Info) SetSummary

func (s *Info) SetSummary(additions, deletions, files int, diffs string)

func (*Info) SetTitle

func (s *Info) SetTitle(title string)

func (*Info) Touch

func (s *Info) Touch()

type Observer

type Observer interface {
	OnEvent(event *Event)
}

type ObserverFunc

type ObserverFunc func(event *Event)

func (ObserverFunc) OnEvent

func (f ObserverFunc) OnEvent(event *Event)

type Option

type Option func(*Config)

func WithInputBufferSize

func WithInputBufferSize(size int) Option

func WithOutputBufferSize

func WithOutputBufferSize(size int) Option

func WithPlannerEnabled

func WithPlannerEnabled(enabled bool, prompt string, autoApprove bool) Option

func WithQueueEnabled

func WithQueueEnabled(maxSize, maxPending int) Option

func WithUserID added in v1.10.0

func WithUserID(userID string) Option

WithUserID 显式归属一个 session 到 userID(多租户隔离用)。 未传时由 factory 回退配置 DefaultUserID / 常量 "default"。

type OutputObserver added in v1.9.1

type OutputObserver = Observer

OutputObserver streams session events (same contract as Observer). Subscribe runs callbacks synchronously in the session loop; for channel fan-out, use a goroutine ranging Session.Output() so slow consumers do not block emit.

type Plan

type Plan struct {
	Goal      string     `json:"goal,omitempty"`
	Steps     []PlanStep `json:"steps"`
	Reasoning string     `json:"reasoning,omitempty"`
	Approved  bool       `json:"approved"`
}

type PlanApproval

type PlanApproval struct {
	Approved bool
	Plan     *Plan
}

type PlanMode

type PlanMode string
const (
	PlanModeAuto  PlanMode = "auto"
	PlanModeAsk   PlanMode = "ask"
	PlanModeNever PlanMode = "never"
)

type PlanStep

type PlanStep struct {
	Index     int                    `json:"index"`
	Tool      string                 `json:"tool"`
	Input     map[string]interface{} `json:"input"`
	Reasoning string                 `json:"reasoning"`
}

type PlannerHelper

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

func NewPlannerHelper

func NewPlannerHelper(enabled bool, prompt string, autoApprove bool, llmProvider types.LLMProvider, toolSchemas []map[string]interface{}) *PlannerHelper

func (*PlannerHelper) ApprovalChan

func (p *PlannerHelper) ApprovalChan() chan<- PlanApproval

func (*PlannerHelper) Approve

func (p *PlannerHelper) Approve(approved bool)

func (*PlannerHelper) CreatePlan

func (p *PlannerHelper) CreatePlan(ctx context.Context, input string) (*Plan, error)

func (*PlannerHelper) GetMode

func (p *PlannerHelper) GetMode() PlanMode

func (*PlannerHelper) IsEnabled

func (p *PlannerHelper) IsEnabled() bool

func (*PlannerHelper) RequestApproval

func (p *PlannerHelper) RequestApproval(ctx context.Context, plan *Plan) bool

func (*PlannerHelper) SetMode

func (p *PlannerHelper) SetMode(mode PlanMode)

func (*PlannerHelper) ShouldEnterPlanMode

func (p *PlannerHelper) ShouldEnterPlanMode(input string) bool

type Session

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

func NewSession

func NewSession(id string, agent *engine.AgentEngine, factory SessionFactory, ctx context.Context, cfg *Config, planner *PlannerHelper, budget interface{ CanExecute(sessionID string) bool }, wake WakeSource) *Session

func (*Session) AnswerQuestion added in v1.10.0

func (s *Session) AnswerQuestion(toolCallID, answer string) error

AnswerQuestion 把用户对 question 工具的回答注入为下一条输入(question-reflow §2.2)。toolCallID 与 EventTypeQuestion 事件的 ToolCallID 对应 (client.go onQuestion 回调)。注入走 s.input 通道,session 循环消费后作为 新 turn 执行;回答的 displayContent 标记为 questionAnswerDisplay,UI 折叠显示。

func (*Session) ApprovePlan

func (s *Session) ApprovePlan(approved bool)

func (*Session) CancelCurrentTurn added in v1.8.12

func (s *Session) CancelCurrentTurn()

func (*Session) Close

func (s *Session) Close()

func (*Session) Context

func (s *Session) Context() context.Context

func (*Session) Enqueue

func (s *Session) Enqueue(content string, priority dinoQueue.Priority) (<-chan *dinoQueue.Result, error)

func (*Session) EnqueueBatch

func (s *Session) EnqueueBatch(contents []string, priority dinoQueue.Priority) ([]<-chan *dinoQueue.Result, error)

func (*Session) GetAgent added in v1.8.1

func (s *Session) GetAgent() *engine.AgentEngine

func (*Session) GetMemory added in v1.8.1

func (s *Session) GetMemory() types.MemoryProvider

func (*Session) ID

func (s *Session) ID() string

func (*Session) Input

func (s *Session) Input() chan<- interface{}

func (*Session) IsRunning

func (s *Session) IsRunning() bool

func (*Session) Output

func (s *Session) Output() <-chan *Event

func (*Session) QueuePending

func (s *Session) QueuePending() int

func (*Session) QueueSize

func (s *Session) QueueSize() int

func (*Session) QueueStats

func (s *Session) QueueStats() dinoQueue.Stats

func (*Session) Start

func (s *Session) Start()

func (*Session) Stop

func (s *Session) Stop()

func (*Session) Subscribe

func (s *Session) Subscribe(obs Observer) string

func (*Session) Unsubscribe

func (s *Session) Unsubscribe(id string)

type SessionFactory

type SessionFactory interface {
	RecordLoop(sessionID string, action agentutils.LoopDetectAction)
	RecordTokens(ctx context.Context, sessionID string, tokens int)
	Detect(ctx context.Context, sessionID string, action agentutils.LoopDetectAction) *agentutils.LoopDetectResult
}

type Summary

type Summary struct {
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
	Files     int    `json:"files"`
	Diffs     string `json:"diffs,omitempty"`
}

type Time

type Time struct {
	Created    int64 `json:"created"`
	Updated    int64 `json:"updated"`
	Compacting int64 `json:"compacting,omitempty"`
	Archived   int64 `json:"archived,omitempty"`
}

type ToolCallInfo

type ToolCallInfo struct {
	ID    string
	Name  string
	Input map[string]interface{}
}

type TurnCanceledError added in v1.9.0

type TurnCanceledError struct {
	Err error
}

func (TurnCanceledError) Error added in v1.9.0

func (e TurnCanceledError) Error() string

func (TurnCanceledError) Unwrap added in v1.9.0

func (e TurnCanceledError) Unwrap() error

type TurnObservation added in v1.9.0

type TurnObservation struct {
	AssistantText   string
	Usage           *Usage
	HadError        bool
	ErrorMessage    string
	EngineStopCause string
}

func ObserveOneUserTurn added in v1.9.0

func ObserveOneUserTurn(ctx context.Context, s *Session, in types.AgentInput) (*TurnObservation, bool, error)

type TurnSessionClosedError added in v1.9.0

type TurnSessionClosedError struct {
	Err error
}

func (TurnSessionClosedError) Error added in v1.9.0

func (e TurnSessionClosedError) Error() string

func (TurnSessionClosedError) Unwrap added in v1.9.0

func (e TurnSessionClosedError) Unwrap() error

type Usage

type Usage = agenttypes.Usage

type WakePayload added in v1.10.0

type WakePayload struct {
	// TaskID DelegateResult.TaskID(spawn_agent 返回的 task_id)。
	TaskID string
	// Text DelegateResult.Truncated() 结果,直接注入下一 turn。
	Text string
}

WakePayload 已完成子代理的紧凑注入单元(纯数据,session 不接触 agent 类型)。

type WakeSource added in v1.10.0

type WakeSource interface {
	// Wake 有新完成通知时产出信号(不携带 payload;payload 经 Collect 获取)。
	Wake() <-chan struct{}
	// Collect 取走全部未读完成(DrainAll + Truncated)。仅 session idle 时调用
	// (onSubagentCompletion),与 wait_agent(turn 内阻塞)互斥。
	Collect() []WakePayload
}

WakeSource 有新完成通知时产出信号;session idle 时经 Collect 取走 payload。

func NoWakeSource added in v1.10.0

func NoWakeSource() WakeSource

NoWakeSource 返回永不产出的唤醒源。

Jump to

Keyboard shortcuts

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