session

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package session provides an append-only event log that records every prompt, response, tool call, and tool result for a run. The log is the source of truth and lets a run be resumed via the OpenAI Responses API's PreviousResponseID. Large tool results are spilled to disk under results/<id>.txt and replaced inline with a placeholder the model can re-fetch via the get_tool_result tool.

Index

Constants

View Source
const (
	StatusRunning   = "running"
	StatusCompleted = "completed"
	StatusError     = "error"
	StatusBudget    = "budget_exceeded"
)

Statuses returned by Logger.Finish.

View Source
const (
	EventRunStart        = "run_start"
	EventResume          = "resume"
	EventPrompt          = "prompt"
	EventResponse        = "response"
	EventToolCall        = "tool_call"
	EventToolResult      = "tool_result"
	EventLargeResult     = "large_result"
	EventIteration       = "iteration"
	EventError           = "error"
	EventRunEnd          = "run_end"
	EventSkillLoaded     = "skill_loaded"
	EventConfirmResolved = "confirm_resolved"
)

Event types written to events.jsonl.

View Source
const LargeResultThreshold = 8 * 1024

LargeResultThreshold is the byte size above which a tool result is spilled to results/<id>.txt and replaced inline with a placeholder.

View Source
const SessionsRoot = ".squad/sessions"

SessionsRoot is the directory under workingDir where sessions are stored.

Variables

This section is empty.

Functions

func WithLogger

func WithLogger(ctx context.Context, l *Logger) context.Context

WithLogger attaches a Logger to ctx so deeply nested calls (executor, responses loop, tool handlers) can record events without plumbing.

Types

type Event

type Event struct {
	Ts      time.Time       `json:"ts"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

Event is one append-only record written to events.jsonl.

type Logger

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

Logger writes events.jsonl and rewrites meta.json on update. Methods are safe to call concurrently.

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext returns the Logger attached to ctx, or nil if none.

func New

func New(workingDir, agent, provider, model, prompt string) (*Logger, error)

New creates a fresh session under <workingDir>/.squad/sessions/<id>/ and returns a Logger ready to receive events. The caller should defer Close.

func Open

func Open(workingDir, sessionID string) (*Logger, error)

Open loads an existing session for resume. The Logger appends to the same events.jsonl and rewrites meta.json in place.

func (*Logger) Append

func (l *Logger) Append(eventType string, payload any) error

Append records an event to events.jsonl. payload may be nil. Safe to call on a nil Logger (no-op).

func (*Logger) Close

func (l *Logger) Close() error

Close flushes the events file. Call after Finish.

func (*Logger) Dir

func (l *Logger) Dir() string

Dir returns the session directory.

func (*Logger) Finish

func (l *Logger) Finish(status string, errMsg string)

Finish records the terminal status (run_end event + meta.json status).

func (*Logger) LastResponseID

func (l *Logger) LastResponseID() string

LastResponseID returns the most recent OpenAI response id chained for this session, or "" if no response has been recorded yet.

func (*Logger) ReadLargeResult

func (l *Logger) ReadLargeResult(id string, offset, limit int) (string, int, error)

ReadLargeResult returns a slice of a previously stored large result. If limit <= 0 the whole content from offset is returned. The total byte length is also returned so the caller can advise the model on remaining content.

func (*Logger) SessionID

func (l *Logger) SessionID() string

SessionID returns the session identifier.

func (*Logger) SetLastResponseID

func (l *Logger) SetLastResponseID(id string)

SetLastResponseID records the most recent OpenAI response id and persists it to meta.json so a resume can pick up the chain. Safe on nil Logger.

func (*Logger) SetRoutineID

func (l *Logger) SetRoutineID(id string)

SetRoutineID stamps the meta.json with the qualified routine id that owns this session. Called by the routines daemon's fire handler before invoking the agent so `squad routine history` can filter by exact provenance.

func (*Logger) StoreLargeResult

func (l *Logger) StoreLargeResult(content string) (string, error)

StoreLargeResult writes the full content to results/<id>.txt and returns the result id. Callers replace the inline tool output with a placeholder referencing this id, and the model can re-fetch via get_tool_result.

func (*Logger) UpdateMetrics

func (l *Logger) UpdateMetrics(inputTokens, outputTokens int64, cost float64, iterations int)

UpdateMetrics overwrites the cumulative token + cost fields in meta.json. Pass the current totals from *metrics.Metrics; this is not additive.

type Meta

type Meta struct {
	SessionID      string    `json:"session_id"`
	Created        time.Time `json:"created"`
	Updated        time.Time `json:"updated"`
	Agent          string    `json:"agent"`
	Provider       string    `json:"provider"`
	Model          string    `json:"model"`
	WorkingDir     string    `json:"working_dir"`
	Prompt         string    `json:"prompt"`
	LastResponseID string    `json:"last_response_id,omitempty"`
	// RoutineID identifies the routine that produced this session (qualified
	// form: "global:nightly" / "repo:audit"). Empty for non-routine runs.
	RoutineID    string  `json:"routine_id,omitempty"`
	Status       string  `json:"status"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	Cost         float64 `json:"cost"`
	Iterations   int     `json:"iterations"`
}

Meta holds the per-session metadata kept in meta.json. It is rewritten on every update so a `--resume` can read it without scanning the event log.

Jump to

Keyboard shortcuts

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