chat

package
v0.46.3 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 66 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 ExportBucket added in v0.43.2

func ExportBucket(ctx context.Context, records []RecordSet, format ExportFormat, output io.Writer) error

func ExportBucketFile added in v0.43.2

func ExportBucketFile(ctx context.Context, records []RecordSet, format ExportFormat, path string) error

ExportBucketFile writes atomically: a failed conversion leaves an existing target untouched. The caller selects explicit path and format.

func ExportRecordSetFile added in v0.43.2

func ExportRecordSetFile(ctx context.Context, record RecordSet, format ExportFormat, path string) error

func ExportRecordSets added in v0.43.2

func ExportRecordSets(ctx context.Context, records []RecordSet, format ExportFormat, output io.Writer) error

ExportRecordSets writes immutable snapshots, never reruns their queries. For more than one RecordSet, flat formats are zipped; XLSX and SQLite hold all RecordSets in one workbook/database. No caller supplies SQL or a model.

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.

func Interpret added in v0.42.0

func Interpret(ctx context.Context, req InterpretRequest) (string, error)

Interpret uses the same ADK conversation and run_dtql action as CLI Chat. It returns only a validated DTQL document; model prose and results are not part of the browser contract. Provider errors are deliberately sanitized.

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 AppliedJoinEdge added in v0.40.0

type AppliedJoinEdge struct {
	JoinPath     RelationInstanceID `json:"joinPath"`
	SourcePath   RelationInstanceID `json:"sourcePath"`
	ConstraintID string             `json:"constraintId"`
	Direction    string             `json:"direction"`
	CandidateID  JoinCandidateID    `json:"candidateId"`
	Fields       []JoinFieldPair    `json:"fields"`
}

AppliedJoinEdge ties an FK constraint to the exact joined relation path in immutable DTQL. It distinguishes duplicate constraints with identical ON field pairs; older RecordSets without it use conservative ON matching.

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 BrowserBridge added in v0.44.1

type BrowserBridge struct {
	URL string
	// contains filtered or unexported fields
}

BrowserBridge exposes the active CLI chat to a browser on a loopback-only port. The capability stays in the web URL fragment and is sent in a request header.

func StartBrowserBridge added in v0.44.1

func StartBrowserBridge(sessions *SessionChat) (*BrowserBridge, error)

func (*BrowserBridge) Close added in v0.44.1

func (b *BrowserBridge) Close() error

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 ChartCandidate added in v0.41.0

type ChartCandidate struct {
	Spec   ChartSpec
	Score  int
	Reason string
}

ChartCandidate records a stable ranking score and a human-readable reason.

func InferChartCandidates added in v0.41.0

func InferChartCandidates(stats secureread.RecordSetStatistics) []ChartCandidate

InferChartCandidates is pure and deterministic. It uses only the finalized RecordSet analysis, never database access, model text, or terminal state.

type ChartKind added in v0.41.0

type ChartKind string

ChartKind is independent of the current terminal renderer. Pie and donut are reserved for future adapters; Phase 6 renders bar and line only.

const (
	ChartBar     ChartKind = "bar"
	ChartLine    ChartKind = "line"
	ChartScatter ChartKind = "scatter"
	ChartPie     ChartKind = "pie"
	ChartDonut   ChartKind = "donut"
)

type ChartPoint added in v0.41.0

type ChartPoint struct {
	Label string
	Value float64
}

ChartPoint is one already-aggregated, ordered value in a ChartSpec.

type ChartSpec added in v0.41.0

type ChartSpec struct {
	Kind          ChartKind
	Title         string
	Dimension     string
	Measure       string
	Aggregation   string
	Ordering      string
	Limit         int
	SourceColumns []string
	Labels        []string
	Bucket        string
	Points        []ChartPoint
}

ChartSpec carries chart meaning and already-aggregated points, but no NTCharts, Bubble Tea, terminal width or color types.

type ChatMessage added in v0.37.0

type ChatMessage struct {
	ID             string
	Role           string
	Kind           string
	Text           string
	QueryID        string
	RecordSetID    string
	HTTPResponseID 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
	HTTPResponses map[string]HTTPResponse
	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 ExportFormat added in v0.43.2

type ExportFormat string
const (
	ExportCSV    ExportFormat = "csv"
	ExportJSON   ExportFormat = "json"
	ExportYAML   ExportFormat = "yaml"
	ExportINGR   ExportFormat = "ingr"
	ExportDBF    ExportFormat = "dbf"
	ExportSQLite ExportFormat = "sqlite"
	ExportXLSX   ExportFormat = "xlsx"
)

func ParseExportFormat added in v0.43.2

func ParseExportFormat(value string) (ExportFormat, error)

type ForeignKey added in v0.40.0

type ForeignKey struct {
	ConstraintID string
	Schema       string
	FromRelation string
	FromFields   []string
	ToSchema     string
	ToRelation   string
	ToFields     []string
}

ForeignKey is source-scoped schema evidence. Fields are paired by index and are intentionally not flattened: a composite FK remains one relationship.

type ForeignKeyJoinApplication added in v0.40.0

type ForeignKeyJoinApplication struct {
	Source   string
	Snapshot ForeignKeySnapshot
	// Refresh is called for candidate exposure and again immediately before
	// apply. It is normally LoadSQLiteForeignKeySnapshot bound to the selected
	// source; a stale edge never falls back to the startup snapshot.
	Refresh       func(context.Context) (ForeignKeySnapshot, error)
	CanReadTarget func(context.Context, RelationInstance) error
	Executor      DTQLExecutor
	Secure        bool
}

ForeignKeyJoinApplication is the production-neutral implementation. Its snapshot is source-bound and it delegates every read to the existing secure DTQL executor; it never constructs SQL or joins displayed rows locally. When Secure is true, every existing source is preflighted for unrestricted readability before a JOIN is exposed or executed.

func (ForeignKeyJoinApplication) Apply added in v0.40.0

func (ForeignKeyJoinApplication) Candidates added in v0.40.0

func (a ForeignKeyJoinApplication) Candidates(ctx context.Context, record RecordSet) ([]JoinCandidate, error)

func (ForeignKeyJoinApplication) PreviewRelated added in v0.43.2

func (a ForeignKeyJoinApplication) PreviewRelated(ctx context.Context, record RecordSet, selected string, row map[string]any) ([]relatedRecord, error)

PreviewRelated resolves only an authoritative outgoing FK and reads up to five matching records through the same DTQL/policy executor as chat queries.

type ForeignKeySnapshot added in v0.40.0

type ForeignKeySnapshot struct {
	Source string
	Keys   []ForeignKey
	// Columns contains the source's ordered physical columns, keyed by
	// lowercase schema.relation. It is used to expand wildcards before a JOIN.
	Columns map[string][]string
}

func LoadSQLiteForeignKeySnapshot added in v0.40.0

func LoadSQLiteForeignKeySnapshot(ctx context.Context, source string, db *sql.DB) (ForeignKeySnapshot, error)

LoadSQLiteForeignKeySnapshot reads SQLite's authoritative PRAGMA metadata. It retains PRAGMA id/seq rather than fabricating names, and groups every composite constraint atomically in deterministic table/id/sequence order.

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 HTTPRedirect added in v0.45.0

type HTTPRedirect struct {
	URL        string        `json:"url"`
	StatusCode int           `json:"statusCode"`
	Elapsed    time.Duration `json:"elapsed"`
}

HTTPRedirect is one completed HTTP hop before the final response. URLs are stripped of query strings and credentials before entering session storage.

type HTTPRequestSettings added in v0.45.0

type HTTPRequestSettings struct {
	Headers       map[string]string
	Cookies       map[string]string
	HeaderScopes  map[string]string
	CookieScopes  map[string]string
	HeaderOrigins map[string]string
}

HTTPRequestSettings are local DataTug project defaults. They never enter chat messages, model context, or persisted HTTP response metadata.

type HTTPResponse added in v0.45.0

type HTTPResponse struct {
	ID              string
	Method          string
	SessionID       string
	OriginMessageID string
	URL             string
	StatusCode      int
	ContentType     string
	Headers         map[string][]string
	RequestHeaders  map[string][]string
	TimeToResponse  time.Duration
	DownloadTime    time.Duration
	FinalURL        string
	Redirects       []HTTPRedirect
	RequestHasQuery bool
	Body            []byte
	RefreshParentID string
	CreatedAt       time.Time
}

HTTPResponse is the immutable original download behind an HTTP chat result. Body is stored verbatim, while URL is stripped of query parameters before persistence.

type InterpretProvider added in v0.42.0

type InterpretProvider struct {
	Protocol string `json:"protocol"`
	BaseURL  string `json:"baseUrl"`
	Model    string `json:"model"`
	APIKey   string `json:"apiKey"`
}

InterpretProvider is supplied by the browser for one ADK turn. The key is never retained by the agent or passed to the ADK session.

type InterpretRequest added in v0.42.0

type InterpretRequest struct {
	Question string            `json:"question"`
	Schema   string            `json:"schema"`
	Provider InterpretProvider `json:"provider"`
}

InterpretRequest contains only the question and the browser's compact schema. Query execution and all database rows stay in the browser.

func (InterpretRequest) Validate added in v0.42.0

func (r InterpretRequest) Validate() error

type InterpretResult added in v0.42.0

type InterpretResult struct {
	DTQL  string      `json:"dtql"`
	Usage *TokenUsage `json:"usage,omitempty"`
}

InterpretResult contains the DTQL action and provider-reported token usage.

func InterpretDetailed added in v0.42.0

func InterpretDetailed(ctx context.Context, req InterpretRequest) (InterpretResult, error)

InterpretDetailed also returns model usage when the provider reports it.

type JoinApplication added in v0.40.0

type JoinApplication interface {
	Candidates(context.Context, RecordSet) ([]JoinCandidate, error)
	Apply(context.Context, RecordSet, JoinCandidateID) (QueryResult, error)
}

JoinApplication is the single domain seam used by terminal and agent code. It keeps candidate discovery and execution out of UI/model code.

type JoinCandidate added in v0.40.0

type JoinCandidate struct {
	ID           JoinCandidateID
	Source       RelationInstance
	Target       RelationInstance
	ConstraintID string
	Direction    string // outgoing or incoming, relative to Source
	Cardinality  string // many-to-one or one-to-many, relative to Source
	Fields       []JoinFieldPair
	Evidence     string // foreign-key
}

func DeriveJoinDTQL added in v0.40.0

func DeriveJoinDTQL(parent []byte, snapshot ForeignKeySnapshot, id JoinCandidateID, applied ...AppliedJoinEdge) ([]byte, JoinCandidate, error)

DeriveJoinDTQL derives a real AST join. It refuses a stale candidate rather than accepting caller-provided field names or a replacement relation.

func DiscoverJoinCandidates added in v0.40.0

func DiscoverJoinCandidates(doc []byte, snapshot ForeignKeySnapshot, applied ...AppliedJoinEdge) ([]JoinCandidate, error)

DiscoverJoinCandidates walks only the query's actual relation tree. It does not recursively walk metadata targets, so cyclic schemas cannot recurse.

type JoinCandidateID added in v0.40.0

type JoinCandidateID string

JoinCandidateID is opaque. Callers must pass the value selected from the catalog back to ApplyJoinCandidate instead of reconstructing an edge.

type JoinFieldPair added in v0.40.0

type JoinFieldPair struct{ SourceField, TargetField string }

type JoinLineage added in v0.40.0

type JoinLineage struct {
	ParentRecordSetID string            `json:"parentRecordSetId"`
	CandidateID       JoinCandidateID   `json:"candidateId"`
	AppliedEdges      []AppliedJoinEdge `json:"appliedEdges,omitempty"`
}

JoinLineage preserves the exact user-selected edge without making a saved RecordSet depend on live schema metadata.

type Option

type Option func(*conversationConfig) error

Option configures the constrained ADK conversation.

func WithBrowserInterpretation added in v0.42.0

func WithBrowserInterpretation() Option

WithBrowserInterpretation keeps the CLI's ADK action/tool lifecycle while asking for the subset the browser DALgo parser can execute locally.

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
	ColumnTypes map[string]string
	Issue       string // local metadata load error; never included in agent context
}

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
	HTTPResponseID  string
	RefreshParentID string
	Result          secureread.Result
	Parameters      map[string]any
	Source          string
	SourceID        string
	// Lineage is DataTug-owned execution provenance, never model supplied.
	Lineage *JoinLineage
	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
	HTTPResponseID  string
	RefreshParentID string
	Lineage         *JoinLineage
}

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 RelationInstance added in v0.40.0

type RelationInstance struct {
	ID       RelationInstanceID
	Schema   string
	Relation string
	Alias    string
}

type RelationInstanceID added in v0.40.0

type RelationInstanceID string

RelationInstanceID identifies a node in the DTQL source tree. It is stable for a given document: root is "root" and child joins append their index.

type SavedQuery added in v0.45.0

type SavedQuery struct {
	ID         string
	Title      string
	Type       string
	Tags       []string
	Parameters []SavedQueryParameter
}

SavedQuery is the small, presentation-only shape used by the command picker. The project store remains authoritative for query definitions and execution.

type SavedQueryLookup added in v0.45.0

type SavedQueryLookup struct {
	Key    string
	Multi  bool
	Result secureread.Result
}

type SavedQueryLookupPlan added in v0.45.0

type SavedQueryLookupPlan struct {
	Relation string
	Key      string
	Columns  []string
	Multi    bool
}

SavedQueryLookupPlan is derived only from source-scoped SQLite FK evidence.

func DiscoverSavedQueryLookup added in v0.45.0

func DiscoverSavedQueryLookup(snapshot ForeignKeySnapshot, entity, field string) *SavedQueryLookupPlan

DiscoverSavedQueryLookup declines ambiguous and composite relationships; these cannot safely fill one scalar parameter.

func DiscoverSavedQueryParameterLookup added in v0.45.0

func DiscoverSavedQueryParameterLookup(doc []byte, snapshot ForeignKeySnapshot, parameterID, entity, field string) *SavedQueryLookupPlan

DiscoverSavedQueryParameterLookup uses the saved DTQL equality predicate to locate the parameter's source column, then checks Meta against the target of that exact FK. ID is accepted as a semantic shorthand only for a real target key named <Entity>Id in the FK snapshot.

func DiscoverSavedQueryParameterLookupWithMode added in v0.45.0

func DiscoverSavedQueryParameterLookupWithMode(doc []byte, snapshot ForeignKeySnapshot, parameterID, entity, field string, multi bool) *SavedQueryLookupPlan

func (SavedQueryLookupPlan) Document added in v0.45.0

func (p SavedQueryLookupPlan) Document() []byte

type SavedQueryLookupService added in v0.45.0

type SavedQueryLookupService interface {
	LookupParameter(context.Context, string, string) (*SavedQueryLookup, error)
}

SavedQueryLookupService resolves a parameter against the saved query's own source and returns policy-filtered rows. A nil result means no scalar FK.

type SavedQueryParameter added in v0.45.0

type SavedQueryParameter struct {
	ID           string
	Title        string
	Type         string
	Required     bool
	Multi        bool
	DefaultValue string
	Entity       string
	Field        string
}

type SavedQueryParameterizedRunner added in v0.45.0

type SavedQueryParameterizedRunner interface {
	RunWithVariables(context.Context, string, map[string]string) (QueryResult, error)
}

type SavedQuerySaveRequest added in v0.45.0

type SavedQuerySaveRequest struct {
	Title    string
	Tags     []string
	Type     string
	Text     string
	Database string
}

type SavedQueryService added in v0.45.0

type SavedQueryService interface {
	List(context.Context) ([]SavedQuery, error)
	Run(context.Context, string) (QueryResult, error)
}

type SavedQueryWriter added in v0.45.0

type SavedQueryWriter interface {
	Save(context.Context, SavedQuerySaveRequest) (SavedQuery, error)
}

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) ApplyJoinCandidate added in v0.40.0

func (c *SessionChat) ApplyJoinCandidate(ctx context.Context, recordSetID string, candidateID JoinCandidateID) (RecordSet, error)

ApplyJoinCandidate is the shared UI/agent operation. It records an action message and persists the execution as the ordinary immutable query/grid sequence, so restarts never re-execute historic joins.

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) AskActive added in v0.44.1

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

AskActive refuses a browser submission if the terminal switched sessions after the browser read its snapshot.

func (*SessionChat) Clear added in v0.37.0

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

func (*SessionChat) ConfigureJoinApplication added in v0.40.0

func (c *SessionChat) ConfigureJoinApplication(application JoinApplication)

ConfigureJoinApplication installs the DataTug-owned join boundary. It is a separate setup step because existing chat construction deliberately knows nothing about database adapters; callers may leave it unset when a source has no FK capability.

func (*SessionChat) ConfigureQueryExecutor added in v0.45.0

func (c *SessionChat) ConfigureQueryExecutor(executor DTQLExecutor)

ConfigureQueryExecutor enables deterministic refresh of stored DTQL without another model call. The caller supplies the same policy-bound executor used for ordinary agent queries.

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) JoinCandidates added in v0.40.0

func (c *SessionChat) JoinCandidates(ctx context.Context, recordSetID string) ([]JoinCandidate, error)

JoinCandidates resolves candidates for a persisted immutable RecordSet. The returned IDs are opaque and must be supplied unchanged to ApplyJoinCandidate.

func (*SessionChat) List added in v0.37.0

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

func (*SessionChat) RefreshRecordSet added in v0.45.0

func (c *SessionChat) RefreshRecordSet(ctx context.Context, sessionID, recordSetID string) (ChatSession, error)

RefreshRecordSet re-executes the exact stored DTQL through the normal, policy-bound DataTug executor and appends an immutable result version.

func (*SessionChat) Rename added in v0.37.0

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

func (*SessionChat) SetTableStyle added in v0.43.1

func (c *SessionChat) SetTableStyle(ctx context.Context, name string) error

func (*SessionChat) Snapshot added in v0.37.0

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

func (*SessionChat) SubscribeChanges added in v0.44.1

func (c *SessionChat) SubscribeChanges() (<-chan struct{}, func())

SubscribeChanges reports committed changes without sending session data over the notification channel. Call stop when the UI or socket closes.

func (*SessionChat) Switch added in v0.37.0

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

func (*SessionChat) TableStyle added in v0.43.1

func (c *SessionChat) TableStyle(ctx context.Context) (string, 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) AppendHTTPResponse added in v0.45.0

func (s *SessionStore) AppendHTTPResponse(ctx context.Context, sessionID, originID string, response HTTPResponse, query *QueryResult) (HTTPResponse, error)

AppendHTTPResponse owns the original downloaded bytes and, when tabular, links a derived immutable RecordSet to that exact response in one transaction.

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) HTTPRequestSettings added in v0.45.0

func (s *SessionStore) HTTPRequestSettings(ctx context.Context, origin string) (HTTPRequestSettings, error)

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) RemoveHTTPRequestSetting added in v0.45.0

func (s *SessionStore) RemoveHTTPRequestSetting(ctx context.Context, scope, kind, origin, name string) 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) ResultVersionsToKeep added in v0.45.0

func (s *SessionStore) ResultVersionsToKeep(ctx context.Context) (int, error)

ResultVersionsToKeep is a DataTug-owned preference, shared by chat sessions in the same project/database/access scope. Immutable snapshots are retained independently; this controls how many versions a result card exposes.

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.

func (*SessionStore) SetHTTPRequestSetting added in v0.45.0

func (s *SessionStore) SetHTTPRequestSetting(ctx context.Context, scope, kind, origin, name, value string) error

func (*SessionStore) SetResultVersionsToKeep added in v0.45.0

func (s *SessionStore) SetResultVersionsToKeep(ctx context.Context, count int) error

func (*SessionStore) SetTableStyle added in v0.43.1

func (s *SessionStore) SetTableStyle(ctx context.Context, name string) error

func (*SessionStore) TableStyle added in v0.43.1

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

TableStyle is a scope-level presentation preference shared by every chat session for the same project, environment, database and role.

type TokenUsage added in v0.42.0

type TokenUsage struct {
	InputTokens  int64 `json:"inputTokens"`
	OutputTokens int64 `json:"outputTokens"`
	TotalTokens  int64 `json:"totalTokens"`
}

TokenUsage is the usage reported by the model provider for a turn. A nil value means the provider did not report usage.

type Turn

type Turn struct {
	Text string
	// TextFormat marks trusted DataTug-rendered text, such as an HTTP Markdown document.
	TextFormat string
	Queries    []QueryResult
	Actions    []WorkspaceActionResult
	Usage      *TokenUsage
}

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) SetBrowserURL added in v0.44.1

func (u *UI) SetBrowserURL(url string)

SetBrowserURL enables F5 to reveal the active CLI session link.

func (*UI) SetProjectChoices added in v0.38.0

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

func (*UI) SetSavedQueryService added in v0.45.0

func (u *UI) SetSavedQueryService(service SavedQueryService) error

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"`
	ExportBucket       []string                 `json:"exportBucket,omitempty"`
}

Jump to

Keyboard shortcuts

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