chat

package
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Overview

Package chat implements DataTug Chat: an ADK agent produces DTQL, DataTug executes it into structured results, and session-owned RecordSets persist those results independently of the model provider's memory.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultChatStorePath added in v0.37.0

func DefaultChatStorePath(projectDir string) (string, error)

DefaultChatStorePath keeps snapshots outside the project repository. The hash distinguishes projects without exposing their path in a filename.

func FormatSchemaContext

func FormatSchemaContext(schema *api.CatalogSchema) string

FormatSchemaContext converts DataTug's stored schema into a compact prompt fragment. It is deterministic so model and snapshot tests stay stable.

func FormatValue

func FormatValue(value any) string

FormatValue applies basic terminal-safe value formatting.

Types

type ADKConversation

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

ADKConversation uses an ephemeral ADK session for each turn. DataTug's durable ChatSession, not ADK memory, owns conversation history.

func NewADKConversation

func NewADKConversation(llm model.LLM, executor DTQLExecutor, sourceURL, schemaContext string, options ...Option) (*ADKConversation, error)

NewADKConversation builds the constrained chat agent. schemaContext is a compact description derived from DataTug's stored dbmodel.

func (*ADKConversation) Ask

func (c *ADKConversation) Ask(ctx context.Context, prompt string) (Turn, error)

Ask runs one chat turn and returns model text separately from every structured query result captured by the tool callback.

func (*ADKConversation) AskWithContext added in v0.37.0

func (c *ADKConversation) AskWithContext(ctx context.Context, prompt, priorContext string) (Turn, error)

AskWithContext reconstructs a fresh provider turn from DataTug-owned context. No prior provider session is needed after a restart or switch.

type Bookmark added in v0.39.0

type Bookmark struct {
	ID         string
	ProjectID  string
	SourceID   string
	TargetKind string
	Title      string
	Tags       []string
	CreatedAt  time.Time
	UpdatedAt  time.Time
	Snapshot   BookmarkSnapshot
}

Bookmark is project-owned; its snapshot has no live session relationship.

type BookmarkSnapshot added in v0.39.0

type BookmarkSnapshot struct {
	SourceID  string
	RecordSet RecordSet
	View      *RecordSetView
	Selection *Selection
}

BookmarkSnapshot contains copied identifiers only. They must never be resolved via the originating session.

type CellRange added in v0.38.0

type CellRange struct {
	FirstRow int `json:"firstRow"`
	LastRow  int `json:"lastRow"`
	FirstCol int `json:"firstCol"`
	LastCol  int `json:"lastCol"`
}

CellRange uses inclusive coordinates in the immutable RecordSet, not the current grid cursor or sorted display position.

type ChatMessage added in v0.37.0

type ChatMessage struct {
	ID          string
	Role        string
	Kind        string
	Text        string
	QueryID     string
	RecordSetID string
	CreatedAt   time.Time
}

type ChatScope added in v0.37.0

type ChatScope struct {
	// ProjectID partitions retained project artefacts. It deliberately does not
	// participate in the existing session scope hash: Phase 2 sessions retain
	// their exact historic scope identity during the Phase 4 migration.
	ProjectID         string
	Environment       string
	Database          string
	AccessFingerprint string
	Sources           map[string]string
}

ChatScope prevents a cached, policy-redacted result from being reopened under another database or principal/policy configuration.

type ChatSession added in v0.37.0

type ChatSession struct {
	ID         string
	Title      string
	CreatedAt  time.Time
	UpdatedAt  time.Time
	Messages   []ChatMessage
	Queries    []ExecutedQuery
	RecordSets map[string]RecordSet
	Bookmarks  map[string]Bookmark
	Workspace  WorkspaceState
}

type ContextReference added in v0.38.0

type ContextReference struct {
	Kind      string `json:"kind"`
	ProjectID string `json:"projectId,omitempty"`
	SourceID  string `json:"sourceId,omitempty"`
	ObjectID  string `json:"objectId"`
	Title     string `json:"title"`
}

ContextReference is an identity, never a copy of an object's data. Project objects use their source and qualified object name; session objects use ID.

type ContextualConversation added in v0.37.0

type ContextualConversation interface {
	AskWithContext(context.Context, string, string) (Turn, error)
}

ContextualConversation runs a stateless provider turn with context rebuilt from DataTug-owned state. The provider's session is never authoritative.

type Conversation

type Conversation interface {
	Ask(context.Context, string) (Turn, error)
}

Conversation is the UI-facing chat seam and is trivial to fake in tests.

type DTQLExecutor

type DTQLExecutor interface {
	RunDTQL(context.Context, string, []byte, map[string]any) (secureread.Result, error)
}

DTQLExecutor is the existing DataTug query boundary used by Chat.

type Dock added in v0.38.0

type Dock struct {
	ID        string           `json:"id"`
	Reference ContextReference `json:"reference"`
	Title     string           `json:"title"`
}

type ExecutedQuery added in v0.37.0

type ExecutedQuery struct {
	ID              string
	OriginMessageID string
	Title           string
	DTQL            string
	Source          string
	Parameters      map[string]any
	ExecutedAt      time.Time
	Error           string
}

type GridColumn

type GridColumn struct {
	Name    string
	Numeric bool
}

GridColumn is the UI-ready description of a structured result column.

type GridModel

type GridModel struct {
	Columns []GridColumn
	Rows    [][]string
	// RawRows preserves the structured source values alongside formatted cells
	// for future typed interactions without leaking database types into the UI
	// component adapter.
	RawRows [][]any
	// SourceRows maps a displayed (possibly sorted) row back to its immutable
	// RecordSet row index for durable selections.
	SourceRows []int
	// contains filtered or unexported fields
}

GridModel is the terminal-grid boundary. Values are formatted only here, after query execution has produced a structured secureread.Result.

func NewGridModel

func NewGridModel(result secureread.Result) GridModel

NewGridModel converts a structured query result into display cells while preserving explicit result-column order.

func (*GridModel) Sort

func (m *GridModel) Sort(column int)

Sort toggles ascending/descending ordering for one visible column.

type Option

type Option func(*conversationConfig) error

Option configures the constrained ADK conversation.

func WithSources added in v0.38.0

func WithSources(sources map[string]string) Option

WithSources limits model-requested source IDs to the project's resolved source registry. The model cannot supply an arbitrary URL.

func WithThinkingLevel

func WithThinkingLevel(level string) Option

WithThinkingLevel maps the CLI's provider-neutral effort onto ADK's portable thinking budget. pi-go also receives the original level so providers with their own effort controls can apply it directly.

type ProjectCatalog added in v0.38.0

type ProjectCatalog struct {
	ID      string
	Title   string
	Objects []ProjectObject
}

type ProjectChoice added in v0.38.0

type ProjectChoice struct {
	Key    string
	Title  string
	Detail string
}

ProjectChoice identifies a configured DataTug project, not a database.

type ProjectObject added in v0.38.0

type ProjectObject struct {
	Reference ContextReference
	Columns   []string
}

type QueryResult

type QueryResult struct {
	// Title is presentation metadata supplied by the same structured tool
	// action as DTQL. It is never included in, or interpreted as, executable
	// query text.
	Title       string
	DTQL        string
	QueryID     string
	RecordSetID string
	Result      secureread.Result
	Parameters  map[string]any
	Source      string
	SourceID    string
	Err         error
}

QueryResult records one structured tool execution for the UI.

type RecordSet added in v0.37.0

type RecordSet struct {
	ID              string
	SessionID       string
	QueryID         string
	OriginMessageID string
	Title           string
	DTQL            string
	Source          string
	Environment     string
	Database        string
	Parameters      map[string]any
	CreatedAt       time.Time
	Result          secureread.Result
}

RecordSet is a session-owned, immutable result snapshot. Re-execution must insert another ID, never update one of these rows.

type RecordSetView added in v0.38.0

type RecordSetView struct {
	ID          string    `json:"id"`
	RecordSetID string    `json:"recordSetId"`
	Title       string    `json:"title"`
	RowIndices  []int     `json:"rowIndices"`
	Columns     []string  `json:"columns,omitempty"`
	OrderBy     string    `json:"orderBy,omitempty"`
	Descending  bool      `json:"descending,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

type Selection added in v0.38.0

type Selection struct {
	ID        string      `json:"id"`
	ViewID    string      `json:"viewId"`
	Title     string      `json:"title"`
	Rows      []int       `json:"rows,omitempty"`
	Columns   []string    `json:"columns,omitempty"`
	Ranges    []CellRange `json:"ranges,omitempty"`
	CreatedAt time.Time   `json:"createdAt"`
}

type SessionChat added in v0.37.0

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

SessionChat composes durable state with the existing AI -> DTQL pipeline. Its lock prevents a session switch while a turn is being saved/executed.

func NewSessionChat added in v0.37.0

func NewSessionChat(ctx context.Context, store *SessionStore, agent ContextualConversation, source string, catalogs ...ProjectCatalog) (*SessionChat, error)

func (*SessionChat) ApplyWorkspaceAction added in v0.38.0

func (c *SessionChat) ApplyWorkspaceAction(ctx context.Context, action WorkspaceAction) (ContextReference, error)

ApplyWorkspaceAction is shared by terminal events and the agent tool.

func (*SessionChat) Ask added in v0.37.0

func (c *SessionChat) Ask(ctx context.Context, prompt string) (Turn, error)

Ask persists the user message before invoking the model. The tool callback commits each successful query snapshot immediately; final text follows.

func (*SessionChat) Clear added in v0.37.0

func (c *SessionChat) Clear(ctx context.Context) (ChatSession, error)

func (*SessionChat) Create added in v0.37.0

func (c *SessionChat) Create(ctx context.Context) (ChatSession, error)

func (*SessionChat) Delete added in v0.37.0

func (c *SessionChat) Delete(ctx context.Context) (ChatSession, error)

func (*SessionChat) FindBookmarks added in v0.39.0

func (c *SessionChat) FindBookmarks(ctx context.Context, search string, tags []string) ([]Bookmark, error)

FindBookmarks is the shared read path for the UI and the agent. Storage enforces project and policy visibility before any metadata is returned.

func (*SessionChat) List added in v0.37.0

func (c *SessionChat) List(ctx context.Context) ([]ChatSession, error)

func (*SessionChat) Rename added in v0.37.0

func (c *SessionChat) Rename(ctx context.Context, title string) (ChatSession, error)

func (*SessionChat) Snapshot added in v0.37.0

func (c *SessionChat) Snapshot(ctx context.Context) (ChatSession, error)

func (*SessionChat) Switch added in v0.37.0

func (c *SessionChat) Switch(ctx context.Context, prefix string) (ChatSession, error)

type SessionStore added in v0.37.0

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

func OpenSessionStore added in v0.37.0

func OpenSessionStore(path string, scope ChatScope) (*SessionStore, error)

func (*SessionStore) Activate added in v0.37.0

func (s *SessionStore) Activate(ctx context.Context, id string) error

Activate makes the selected session the one reopened by the next CLI run.

func (*SessionStore) AddBookmarkTag added in v0.39.0

func (s *SessionStore) AddBookmarkTag(ctx context.Context, id, tag string) (Bookmark, error)

func (*SessionStore) AppendQuery added in v0.37.0

func (s *SessionStore) AppendQuery(ctx context.Context, sessionID, originID, source string, query QueryResult) (QueryResult, error)

AppendQuery commits a successful execution at the tool boundary, before the model's final response. Each invocation gets a new immutable snapshot, including repeated executions of identical DTQL.

func (*SessionStore) AppendTurn added in v0.37.0

func (s *SessionStore) AppendTurn(ctx context.Context, sessionID, originID, source string, turn Turn) (Turn, error)

func (*SessionStore) AppendUser added in v0.37.0

func (s *SessionStore) AppendUser(ctx context.Context, sessionID, prompt string) (ChatMessage, error)

func (*SessionStore) Clear added in v0.37.0

func (s *SessionStore) Clear(ctx context.Context, id string) error

func (*SessionStore) Close added in v0.37.0

func (s *SessionStore) Close() error

func (*SessionStore) Create added in v0.37.0

func (s *SessionStore) Create(ctx context.Context, title string) (ChatSession, error)

func (*SessionStore) CreateBookmark added in v0.39.0

func (s *SessionStore) CreateBookmark(ctx context.Context, sessionID string, ref ContextReference, title string) (Bookmark, error)

func (*SessionStore) Delete added in v0.37.0

func (s *SessionStore) Delete(ctx context.Context, id string) error

func (*SessionStore) DeleteBookmark added in v0.39.0

func (s *SessionStore) DeleteBookmark(ctx context.Context, id string) error

DeleteBookmark scans decoded workspaces (fail-closed), then repeats the reverse-reference test in its DELETE to serialize concurrent SaveWorkspace.

func (*SessionStore) FindBookmarks added in v0.39.0

func (s *SessionStore) FindBookmarks(ctx context.Context, search string, tags []string) ([]Bookmark, error)

FindBookmarks matches title and tags case-insensitively; required tags use AND.

func (*SessionStore) LatestOrCreate added in v0.37.0

func (s *SessionStore) LatestOrCreate(ctx context.Context) (ChatSession, error)

func (*SessionStore) List added in v0.37.0

func (s *SessionStore) List(ctx context.Context) ([]ChatSession, error)

func (*SessionStore) ListBookmarks added in v0.39.0

func (s *SessionStore) ListBookmarks(ctx context.Context) ([]Bookmark, error)

func (*SessionStore) Load added in v0.37.0

func (s *SessionStore) Load(ctx context.Context, id string) (ChatSession, error)

func (*SessionStore) RemoveBookmarkTag added in v0.39.0

func (s *SessionStore) RemoveBookmarkTag(ctx context.Context, id, tag string) (Bookmark, error)

func (*SessionStore) Rename added in v0.37.0

func (s *SessionStore) Rename(ctx context.Context, id, title string) error

func (*SessionStore) RenameBookmark added in v0.39.0

func (s *SessionStore) RenameBookmark(ctx context.Context, id, title string) (Bookmark, error)

func (*SessionStore) SaveWorkspace added in v0.38.0

func (s *SessionStore) SaveWorkspace(ctx context.Context, sessionID string, state WorkspaceState) error

SaveWorkspace replaces only session-scoped presentation/context state; it never modifies an immutable RecordSet or reruns a query.

type Turn

type Turn struct {
	Text    string
	Queries []QueryResult
	Actions []WorkspaceActionResult
}

Turn is one completed agent turn. Text is model prose; Queries remain structured and are never reconstructed from Text.

type UI

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

UI is the Bubble Tea chat model: a scrollable history viewport, inline bubble-table components, and a fixed bottom input.

func NewSessionUI added in v0.37.0

func NewSessionUI(ctx context.Context, sessions *SessionChat, modelName string) (*UI, error)

NewSessionUI restores the selected durable session before the terminal starts. Historical grids are built from stored RecordSets, never re-executed.

func NewUI

func NewUI(ctx context.Context, conversation Conversation, modelName string) *UI

NewUI creates the terminal chat model without starting a real terminal.

func (*UI) Init

func (u *UI) Init() tea.Cmd

func (*UI) Run

func (u *UI) Run() error

Run starts the Bubble Tea program and blocks until it exits.

func (*UI) SelectedProject added in v0.38.0

func (u *UI) SelectedProject() string

func (*UI) SetProjectChoices added in v0.38.0

func (u *UI) SetProjectChoices(choices []ProjectChoice)

func (*UI) Update

func (u *UI) Update(message tea.Msg) (tea.Model, tea.Cmd)

func (*UI) View

func (u *UI) View() tea.View

type WorkspaceAction added in v0.38.0

type WorkspaceAction struct {
	Kind        string           `json:"kind"`
	Reference   ContextReference `json:"reference,omitempty" jsonschema:"Exact existing object reference; omit for dock to dock the current selection"`
	RecordSetID string           `json:"recordSetId,omitempty"`
	ViewID      string           `json:"viewId,omitempty"`
	Title       string           `json:"title,omitempty"`
	Column      string           `json:"column,omitempty"`
	Equals      string           `json:"equals,omitempty"`
	Contains    string           `json:"contains,omitempty"`
	OrderBy     string           `json:"orderBy,omitempty"`
	Descending  bool             `json:"descending,omitempty"`
	Limit       int              `json:"limit,omitempty"`
	RowStart    int              `json:"rowStart,omitempty"`
	RowEnd      int              `json:"rowEnd,omitempty"`
	Columns     []string         `json:"columns,omitempty"`
	Rows        []int            `json:"rows,omitempty"`
	Ranges      []CellRange      `json:"ranges,omitempty"`
	DockID      string           `json:"dockId,omitempty"`
	BookmarkID  string           `json:"bookmarkId,omitempty"`
	Tag         string           `json:"tag,omitempty"`
	Search      string           `json:"search,omitempty"`
	Tags        []string         `json:"tags,omitempty"`
}

type WorkspaceActionResult added in v0.38.0

type WorkspaceActionResult struct {
	Reference ContextReference
	Summary   string
	Error     string
	Err       error
}

type WorkspaceState added in v0.38.0

type WorkspaceState struct {
	Views              map[string]RecordSetView `json:"views,omitempty"`
	Selections         map[string]Selection     `json:"selections,omitempty"`
	Attachments        []ContextReference       `json:"attachments,omitempty"`
	Docks              []Dock                   `json:"docks,omitempty"`
	CurrentSelectionID string                   `json:"currentSelectionId,omitempty"`
	ActiveTab          string                   `json:"activeTab,omitempty"`
}

Jump to

Keyboard shortcuts

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