Documentation
¶
Overview ¶
Package chat implements DataTug Chat: an aichat agent loop produces DTQL, DataTug executes it into structured results, and session-owned RecordSets persist those results independently of the model provider's memory.
Index ¶
- Variables
- func DefaultChatStorePath(projectDir string) (string, error)
- func ExportBucket(ctx context.Context, records []RecordSet, format ExportFormat, ...) error
- func ExportBucketFile(ctx context.Context, records []RecordSet, format ExportFormat, path string) error
- func ExportRecordSetFile(ctx context.Context, record RecordSet, format ExportFormat, path string) error
- func ExportRecordSets(ctx context.Context, records []RecordSet, format ExportFormat, ...) error
- func FormatSchemaContext(schema *api.CatalogSchema) string
- func Interpret(ctx context.Context, req InterpretRequest) (string, error)
- func NewLLMProvider(modelName, baseURL, apiKey string) (ai.LLMProvider, error)
- func SetRunTeaProgramForTest(f func(p *tea.Program) (tea.Model, error)) (restore func())
- type AIConversation
- func (c *AIConversation) Ask(ctx context.Context, prompt string) (Turn, error)
- func (c *AIConversation) AskWithContext(ctx context.Context, prompt, priorContext string) (Turn, error)
- func (c *AIConversation) LastStreamTurn() Turn
- func (c *AIConversation) StreamAskWithContext(ctx context.Context, prompt, priorContext string) iter.Seq2[ai.Event, error]
- type AppliedJoinEdge
- type Bookmark
- type BookmarkSnapshot
- type BrowserBridge
- type BrowserCellDetail
- type BrowserHTTPRequest
- type BrowserHTTPSetting
- type BrowserRelatedRecords
- type CellRange
- type ChartCandidate
- type ChartKind
- type ChartPoint
- type ChartSpec
- type ChatMessage
- type ChatScope
- type ChatSession
- type ChatUI
- func (u *ChatUI) OnChipsChange(chips []chatshell.Chip) tea.Cmd
- func (u *ChatUI) OnMsg(msg tea.Msg) tea.Cmd
- func (u *ChatUI) OnStreamDone(id string, _ error) tea.Cmd
- func (u *ChatUI) OnStreamEvent(string, ai.Event) tea.Cmd
- func (u *ChatUI) Run() error
- func (u *ChatUI) SelectedProject() string
- func (u *ChatUI) SetBrowserURL(url string)
- func (u *ChatUI) SetProjectChoices(choices []ProjectChoice)
- func (u *ChatUI) SetSavedQueryService(service SavedQueryService) error
- func (u *ChatUI) Submit(text string) tea.Cmd
- type ContextReference
- type ContextualConversation
- type Conversation
- type DTQLExecutor
- type Dock
- type ExecutedQuery
- type ExportFormat
- type ForeignKey
- type ForeignKeyJoinApplication
- func (a ForeignKeyJoinApplication) Apply(ctx context.Context, record RecordSet, id JoinCandidateID) (QueryResult, error)
- func (a ForeignKeyJoinApplication) ApplyAttached(ctx context.Context, record RecordSet, id JoinCandidateID) (QueryResult, error)
- func (a ForeignKeyJoinApplication) Candidates(ctx context.Context, record RecordSet) ([]JoinCandidate, error)
- func (a ForeignKeyJoinApplication) PreviewRelated(ctx context.Context, record RecordSet, selected string, row map[string]any) ([]relatedRecord, error)
- type ForeignKeySnapshot
- type GridColumn
- type GridModel
- type HTTPRedirect
- type HTTPRequestSettings
- type HTTPResponse
- type InterpretProvider
- type InterpretRequest
- type InterpretResult
- type JoinApplication
- type JoinAppliedMsg
- type JoinBlock
- type JoinCandidate
- type JoinCandidateID
- type JoinFieldPair
- type JoinLineage
- type Option
- type ProjectCatalog
- type ProjectChoice
- type ProjectObject
- type QueryResult
- type RecordSet
- type RecordSetView
- type RelationInstance
- type RelationInstanceID
- type SavedDTQLRunner
- type SavedHTTPRunner
- type SavedQuery
- type SavedQueryLookup
- type SavedQueryLookupPlan
- func DiscoverSavedQueryLookup(snapshot ForeignKeySnapshot, entity, field string) *SavedQueryLookupPlan
- func DiscoverSavedQueryParameterLookup(doc []byte, snapshot ForeignKeySnapshot, parameterID, entity, field string) *SavedQueryLookupPlan
- func DiscoverSavedQueryParameterLookupWithMode(doc []byte, snapshot ForeignKeySnapshot, parameterID, entity, field string, ...) *SavedQueryLookupPlan
- type SavedQueryLookupService
- type SavedQueryParameter
- type SavedQueryParameterizedRunner
- type SavedQuerySaveRequest
- type SavedQueryService
- type SavedQueryWriter
- type Selection
- type SessionChat
- func (c *SessionChat) ApplyJoinCandidate(ctx context.Context, recordSetID string, candidateID JoinCandidateID) (RecordSet, error)
- func (c *SessionChat) ApplyJoinCandidateActive(ctx context.Context, sessionID, recordSetID string, ...) (RecordSet, error)
- func (c *SessionChat) ApplyWorkspaceAction(ctx context.Context, action WorkspaceAction) (ContextReference, error)
- func (c *SessionChat) ApplyWorkspaceActionActive(ctx context.Context, sessionID string, action WorkspaceAction) (ContextReference, error)
- func (c *SessionChat) Ask(ctx context.Context, prompt string) (Turn, error)
- func (c *SessionChat) AskActive(ctx context.Context, sessionID, prompt string) (Turn, error)
- func (c *SessionChat) BrowserHTTPSettings(ctx context.Context, sessionID, rawURL string) ([]BrowserHTTPSetting, error)
- func (c *SessionChat) BrowserSessionAction(ctx context.Context, expectedID, action, value string) error
- func (c *SessionChat) BrowserSettings(ctx context.Context, sessionID string) (int, string, string, error)
- func (c *SessionChat) CellDetailActive(ctx context.Context, sessionID, recordSetID string, rowIndex int, ...) (BrowserCellDetail, error)
- func (c *SessionChat) ChangeBrowserHTTPSetting(ctx context.Context, ...) error
- func (c *SessionChat) Clear(ctx context.Context) (ChatSession, error)
- func (c *SessionChat) ConfigureJoinApplication(application JoinApplication)
- func (c *SessionChat) ConfigureQueryExecutor(executor DTQLExecutor)
- func (c *SessionChat) ConfigureSavedQueryService(service SavedQueryService)
- func (c *SessionChat) Create(ctx context.Context) (ChatSession, error)
- func (c *SessionChat) Delete(ctx context.Context) (ChatSession, error)
- func (c *SessionChat) ExportRecordsActive(ctx context.Context, sessionID, recordSetID string, format ExportFormat, ...) error
- func (c *SessionChat) FindBookmarks(ctx context.Context, search string, tags []string) ([]Bookmark, error)
- func (c *SessionChat) JoinCandidates(ctx context.Context, recordSetID string) ([]JoinCandidate, error)
- func (c *SessionChat) JoinCandidatesActive(ctx context.Context, sessionID, recordSetID string) ([]JoinCandidate, error)
- func (c *SessionChat) List(ctx context.Context) ([]ChatSession, error)
- func (c *SessionChat) ListSavedQueries(ctx context.Context) ([]SavedQuery, error)
- func (c *SessionChat) RefreshRecordSet(ctx context.Context, sessionID, recordSetID string) (ChatSession, error)
- func (c *SessionChat) Rename(ctx context.Context, title string) (ChatSession, error)
- func (c *SessionChat) RunSavedDTQLActive(ctx context.Context, sessionID, queryID string, variables map[string]string) error
- func (c *SessionChat) RunSavedHTTPActive(ctx context.Context, sessionID, queryID string, variables map[string]string) error
- func (c *SessionChat) SaveQueryActive(ctx context.Context, sessionID string, request SavedQuerySaveRequest) error
- func (c *SessionChat) SendHTTPRequestActive(ctx context.Context, sessionID string, request BrowserHTTPRequest) error
- func (c *SessionChat) SetBrowserVersions(ctx context.Context, sessionID string, count int) error
- func (c *SessionChat) SetTableStyle(ctx context.Context, name string) error
- func (c *SessionChat) Snapshot(ctx context.Context) (ChatSession, error)
- func (c *SessionChat) StreamAsk(ctx context.Context, prompt string) (iter.Seq2[ai.Event, error], func() (Turn, error))
- func (c *SessionChat) StreamAskActive(ctx context.Context, sessionID, prompt string) (iter.Seq2[ai.Event, error], func() (Turn, error))
- func (c *SessionChat) SubscribeChanges() (<-chan struct{}, func())
- func (c *SessionChat) Switch(ctx context.Context, prefix string) (ChatSession, error)
- func (c *SessionChat) TableStyle(ctx context.Context) (string, error)
- type SessionStore
- func (s *SessionStore) Activate(ctx context.Context, id string) error
- func (s *SessionStore) AddBookmarkTag(ctx context.Context, id, tag string) (Bookmark, error)
- func (s *SessionStore) AppendHTTPResponse(ctx context.Context, sessionID, originID string, response HTTPResponse, ...) (HTTPResponse, error)
- func (s *SessionStore) AppendQuery(ctx context.Context, sessionID, originID, source string, query QueryResult) (QueryResult, error)
- func (s *SessionStore) AppendTurn(ctx context.Context, sessionID, originID, source string, turn Turn) (Turn, error)
- func (s *SessionStore) AppendUser(ctx context.Context, sessionID, prompt string) (ChatMessage, error)
- func (s *SessionStore) Clear(ctx context.Context, id string) error
- func (s *SessionStore) Close() error
- func (s *SessionStore) Create(ctx context.Context, title string) (ChatSession, error)
- func (s *SessionStore) CreateBookmark(ctx context.Context, sessionID string, ref ContextReference, title string) (Bookmark, error)
- func (s *SessionStore) Delete(ctx context.Context, id string) error
- func (s *SessionStore) DeleteBookmark(ctx context.Context, id string) error
- func (s *SessionStore) FindBookmarks(ctx context.Context, search string, tags []string) ([]Bookmark, error)
- func (s *SessionStore) HTTPRequestSettings(ctx context.Context, origin string) (HTTPRequestSettings, error)
- func (s *SessionStore) LatestOrCreate(ctx context.Context) (ChatSession, error)
- func (s *SessionStore) List(ctx context.Context) ([]ChatSession, error)
- func (s *SessionStore) ListBookmarks(ctx context.Context) ([]Bookmark, error)
- func (s *SessionStore) Load(ctx context.Context, id string) (ChatSession, error)
- func (s *SessionStore) RemoveBookmarkTag(ctx context.Context, id, tag string) (Bookmark, error)
- func (s *SessionStore) RemoveHTTPRequestSetting(ctx context.Context, scope, kind, origin, name string) error
- func (s *SessionStore) Rename(ctx context.Context, id, title string) error
- func (s *SessionStore) RenameBookmark(ctx context.Context, id, title string) (Bookmark, error)
- func (s *SessionStore) ResultVersionsToKeep(ctx context.Context) (int, error)
- func (s *SessionStore) SaveWorkspace(ctx context.Context, sessionID string, state WorkspaceState) error
- func (s *SessionStore) SetHTTPRequestSetting(ctx context.Context, scope, kind, origin, name, value string) error
- func (s *SessionStore) SetResultVersionsToKeep(ctx context.Context, count int) error
- func (s *SessionStore) SetTableStyle(ctx context.Context, name string) error
- func (s *SessionStore) TableStyle(ctx context.Context) (string, error)
- type StreamingConversation
- type TokenUsage
- type Turn
- type WorkspaceAction
- type WorkspaceActionResult
- type WorkspaceState
Constants ¶
This section is empty.
Variables ¶
var ErrActiveSessionChanged = errors.New("session changed; refresh chat")
var FormatValue = grid.FormatValue
FormatValue applies basic terminal-safe value formatting. It is strongo/aichat's tui/grid.FormatValue: DataTug and Sneat Chat format grid values identically rather than each keeping its own copy.
Functions ¶
func DefaultChatStorePath ¶ added in v0.37.0
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 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 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 Interpret ¶ added in v0.42.0
func Interpret(ctx context.Context, req InterpretRequest) (string, error)
Interpret uses the same agent 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.
func NewLLMProvider ¶ added in v0.48.0
func NewLLMProvider(modelName, baseURL, apiKey string) (ai.LLMProvider, error)
NewLLMProvider builds the ai.LLMProvider for one chat turn from the resolved --model/--base-url/--ai-profile inputs. baseURL and apiKey, when non-empty, always override the family default (and, for baseURL, any OPENAI_BASE_URL/ANTHROPIC_BASE_URL/AZURE_OPENAI_ENDPOINT environment fallback) -- matching the previous pimodels.WithBaseURL/WithAPIKey override behaviour.
An unrecognized model name (no "family/" prefix, no ":cloud"/"-cloud" tag, no known bare prefix) is an error UNLESS an explicit baseURL was given, in which case -- like pi-go's ResolveWithBaseURL -- it is treated as an intentional custom OpenAI-compatible endpoint rather than silently defaulted to OpenAI's own API, which would send the caller's model name and credential to the wrong host.
func SetRunTeaProgramForTest ¶ added in v0.48.0
SetRunTeaProgramForTest overrides runTeaProgram for the duration of a test, returning a func that restores the previous value — call it via t.Cleanup. It exists purely so pkg/chat's own tests and apps/datatugapp/commands' integration tests (which drive ChatUI.Run only transitively, through runChatProject) can intercept the Bubble Tea program run without ever starting a real one against a TTY.
Types ¶
type AIConversation ¶ added in v0.48.0
type AIConversation struct {
// contains filtered or unexported fields
}
AIConversation uses an ephemeral aichat agent.Loop for each turn. DataTug's durable ChatSession, not provider-side memory, owns conversation history.
func NewAIConversation ¶ added in v0.48.0
func NewAIConversation(provider ai.LLMProvider, executor DTQLExecutor, sourceURL, schemaContext string, options ...Option) (*AIConversation, error)
NewAIConversation builds the constrained chat agent. schemaContext is a compact description derived from DataTug's stored dbmodel.
func (*AIConversation) Ask ¶ added in v0.48.0
Ask runs one chat turn and returns model text separately from every structured query result captured by the tool callback.
func (*AIConversation) AskWithContext ¶ added in v0.48.0
func (c *AIConversation) 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.
It is StreamAskWithContext drained to completion, discarding the progressive events and keeping only the final Turn: both share one implementation of the agent.Loop/usage-accumulation/finalQueries logic, so there is nothing here to fall out of sync with the streaming path.
func (*AIConversation) LastStreamTurn ¶ added in v0.48.0
func (c *AIConversation) LastStreamTurn() Turn
LastStreamTurn returns the structured Turn captured by the most recently completed StreamAskWithContext call on this conversation. It is only meaningful after that call's sequence has finished (or its range loop has returned); AIConversation serializes turns via turnMu, so there is never more than one in flight.
func (*AIConversation) StreamAskWithContext ¶ added in v0.48.0
func (c *AIConversation) StreamAskWithContext(ctx context.Context, prompt, priorContext string) iter.Seq2[ai.Event, error]
StreamAskWithContext runs one turn like AskWithContext but yields normalised ai.Event values (ai.EventTextDelta, ai.EventToolCall, ai.EventToolResult, ai.EventUsage, ai.EventCompleted / a fatal ai.EventError, per the ai.LLMProvider streaming contract) progressively as they arrive from the provider/agent loop, instead of buffering the whole turn before returning. DataTug had no streaming turn before this -- it is a pure feature gain, so non-UI callers and tests keep using the unchanged Ask/AskWithContext, which still return one buffered Turn.
Once the returned sequence has been fully ranged over (or abandoned by breaking out of the range), LastStreamTurn returns the same structured Turn -- Queries/Actions/Usage/Text -- that AskWithContext would have returned for the equivalent call; the same query/workspace observers installed on ctx (see withQueryObserver et al.) still fire exactly once per tool call either way, so a session persists results identically whether it streams or not.
StreamingConversation is the capability interface UI code should type-assert for; not every Conversation/ContextualConversation implementation streams.
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 BrowserCellDetail ¶ added in v0.49.0
type BrowserHTTPRequest ¶ added in v0.49.0
type BrowserHTTPRequest struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
ReplaceHeaders bool `json:"replaceHeaders"`
Body string `json:"body"`
}
BrowserHTTPRequest uses the same request engine and origin-scoped settings as the TUI's /http command. The caller must hold the browser capability.
type BrowserHTTPSetting ¶ added in v0.49.0
type BrowserRelatedRecords ¶ added in v0.49.0
type BrowserRelatedRecords struct {
ConstraintID string
Target string
Columns []string
Rows []secureread.Row
}
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
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.
type ChartPoint ¶ added in v0.41.0
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 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 ChatUI ¶ added in v0.48.0
type ChatUI struct {
// contains filtered or unexported fields
}
ChatUI is the tui/chatshell-based replacement for the old, monolithic UI Bubble Tea model. That legacy UI (ui.go and its supporting files) has been fully retired; apps/datatugapp/commands/cmd_chat.go runs ChatUI exclusively.
ChatUI owns no chat state chatshell.Model already owns (transcript, composer, focus, busy/streaming); it holds only DataTug-specific state: the durable session, its rendered grid/join blocks, and per-turn bookkeeping needed to answer follow-up actions (Ctrl+G, join apply, export).
func NewChatUI ¶ added in v0.48.0
func NewChatUI(ctx context.Context, conversation Conversation, modelName string) *ChatUI
NewChatUI constructs the chatshell-based chat screen. ctx must not be nil (callers pass context.Background() as NewUI does); conversation may be nil only for tests that never call Submit.
func NewSessionChatUI ¶ added in v0.48.0
func NewSessionChatUI(ctx context.Context, sessions *SessionChat, modelName string) (*ChatUI, error)
NewSessionChatUI restores the selected durable session before the terminal starts — the ChatUI analogue of NewSessionUI. Historical grids are rebuilt from stored RecordSets, never re-executed.
func (*ChatUI) OnChipsChange ¶ added in v0.48.0
OnChipsChange satisfies chatshell.ChipObserver: chatshell calls it after IT changes the chip list on its own (Backspace/Delete/Ctrl+D/mouse-× removal, or a Shift+Esc/Ctrl+Y restore) so ChatUI's own attachment state (the durable, persisted source of truth) stays in sync. A chip present before but missing now is detached; a chip present now that wasn't attached a moment ago (a restore bringing one back) is re-attached. applyWorkspaceAction's own u.snapshot assignment re-enters syncChips, which is a no-op here since it rebuilds the exact same chip list chatshell already has (SetChips doesn't itself trigger another OnChipsChange).
func (*ChatUI) OnStreamDone ¶ added in v0.48.0
OnStreamDone satisfies chatshell.StreamObserver. The placeholder streamed entry may hold raw text chatshell rendered live as it arrived -- a model's hidden <think> reasoning before stripThinkTags ran (see agent.go), or plain prose that the final Turn deliberately drops when a query/grid result is the answer (AskWithContext/StreamAskWithContext: "the grid is the answer" clears turnText once len(turn.Queries) > 0). Left alone, that stream-time text would keep showing beside the grid in the live view even though a session reload never persists it (store.go's AppendTurn only inserts a message row when turn.Text != ""; see M3, r1 adversarial review). ReplaceBlock swaps the placeholder entry for a block that reflects the FINAL, resolved Turn.Text before appendTurnResults appends the query/action results below it, so the live view matches what a reload will show.
func (*ChatUI) OnStreamEvent ¶ added in v0.48.0
OnStreamEvent satisfies chatshell.StreamObserver; ChatUI has nothing to add beyond chatshell's own built-in text-delta rendering.
func (*ChatUI) Run ¶ added in v0.48.0
Run starts the Bubble Tea program and blocks until it exits. Unlike ui.go's Init-batched awaitBridgeChange/re-arm loop (chatshell.Model.Init is fixed and offers no hook to inject an extra startup command), the browser-bridge change channel is forwarded straight into the running program from a goroutine — simpler, and Handler has no Init capability to plug into.
func (*ChatUI) SelectedProject ¶ added in v0.48.0
SelectedProject mirrors UI.SelectedProject.
func (*ChatUI) SetBrowserURL ¶ added in v0.48.0
SetBrowserURL mirrors UI.SetBrowserURL.
func (*ChatUI) SetProjectChoices ¶ added in v0.48.0
func (u *ChatUI) SetProjectChoices(choices []ProjectChoice)
SetProjectChoices mirrors UI.SetProjectChoices.
func (*ChatUI) SetSavedQueryService ¶ added in v0.48.0
func (u *ChatUI) SetSavedQueryService(service SavedQueryService) error
SetSavedQueryService mirrors UI.SetSavedQueryService.
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 ¶
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 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 (a ForeignKeyJoinApplication) Apply(ctx context.Context, record RecordSet, id JoinCandidateID) (QueryResult, error)
func (ForeignKeyJoinApplication) ApplyAttached ¶ added in v0.47.2
func (a ForeignKeyJoinApplication) ApplyAttached(ctx context.Context, record RecordSet, id JoinCandidateID) (QueryResult, error)
ApplyAttached preserves rows from a fresh root query when optional attached metadata is joined. Interactive JOIN actions keep their existing semantics.
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 ¶
GridColumn is the UI-ready description of a structured result column. It is an alias for strongo/aichat's tui/grid.Column: DataTug and Sneat Chat share the same generic grid, so a result column has one definition, not two.
type GridModel ¶
type GridModel struct {
Columns []GridColumn
Rows [][]string
// RawRows preserves the structured source values, indexed by the
// RecordSet's own (never reordered) row order, alongside formatted cells
// for typed interactions (FK lookups, saved-query parameter values, cell
// detail) without leaking database types into the table itself.
RawRows [][]any
}
GridModel is the secureread → grid adapter: the terminal-grid boundary where structured query results are formatted into display cells. It is pure data — sorting, column selection, the table itself and its chrome all live in the shared strongo/aichat tui/grid.Model that gridState (ui.go) wraps; newGridState converts a GridModel into that Model's Columns/Rows once, and grid.Model owns everything from there (including its own display-order permutation on Sort — RawRows below stays fixed in the RecordSet's own row order, since gridState resolves a display row back to it via grid.Row.Key, not a parallel-sorted slice).
func NewGridModel ¶
func NewGridModel(result secureread.Result) GridModel
NewGridModel converts a structured query result into display cells while preserving explicit result-column order.
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 agent turn. The key is never retained by the agent or passed to session storage.
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 JoinAppliedMsg ¶ added in v0.48.0
type JoinAppliedMsg struct {
RecordSetID string
CandidateID JoinCandidateID
Err error
}
JoinAppliedMsg reports the outcome of applying a join candidate started by JoinBlock.Update on "space" — the ported joinMessage from ui.go.
type JoinBlock ¶ added in v0.48.0
type JoinBlock struct {
Grid *grid.Model
RecordSetID string
Candidates []JoinCandidate
Apply func(recordSetID string, candidateID JoinCandidateID) tea.Cmd
// contains filtered or unexported fields
}
JoinBlock is a transcript.Block that pairs a query-result grid with DataTug's inline FK-join candidate selector (the old ui.go's "press j" join mode). It ports historyEntry.joinGroups/selectedJoin, joinAreaView and the u.joinFocused branch of updateGrid (pkg/chat/ui.go) onto the tui/transcript.Block/EntityBlock contract so it can sit directly in a tui/chatshell transcript once the shell cutover lands — see checklist item #3 in the Lane C acceptance list.
Applying a candidate (space) runs Apply, whose result — success or error — is delivered as a JoinAppliedMsg the way every other chatshell message is: through the transcript/Handler message flow, not through a direct callback, so JoinBlock stays testable without a live session.
func (*JoinBlock) CapturesEsc ¶ added in v0.48.0
CapturesEsc satisfies transcript.EscCapturer: while the join selector has focus, Esc should return to the grid (handled in Update) rather than bubbling to chatshell's "return focus to composer" default — matching ui.go's updateGrid comment on g.CapturesEsc().
func (*JoinBlock) Current ¶ added in v0.48.0
Current satisfies transcript.EntityBlock, delegating to the wrapped grid.
func (*JoinBlock) JoinFocused ¶ added in v0.48.0
JoinFocused reports whether "j" has switched this block into its inline JOIN candidate selector (ui.go's u.joinFocused) -- statusBar's ZoneTranscript branch (r1b item 5a) reads it, via ChatUI's own gridsByRecordSetID/activeJoinBlock lookup, to show ui.go's "JOIN candidates ↑↓ source ←→ relationship ..." hint set instead of the plain grid one while the selector has focus.
func (*JoinBlock) Update ¶ added in v0.48.0
Update satisfies transcript.Block: "j" toggles the join selector on (when there are candidates); while it has focus, up/down/k/j pick the source group, left/right/h/l pick the candidate, enter toggles the FK-fields detail line, space applies the selected candidate, tab and esc return focus to the grid — ported from ui.go's updateGrid u.joinFocused branch. Any other key, or no join focus, is delegated to the wrapped grid.
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 aichat conversation.
func WithBrowserInterpretation ¶ added in v0.42.0
func WithBrowserInterpretation() Option
WithBrowserInterpretation keeps the CLI's tool-call lifecycle while asking for the subset the browser DALgo parser can execute locally.
func WithSources ¶ added in v0.38.0
WithSources limits model-requested source IDs to the project's resolved source registry. The model cannot supply an arbitrary URL.
func WithThinkingLevel ¶
WithThinkingLevel maps the CLI's provider-neutral effort onto ai.ChatRequest.Reasoning; adapters translate it to their own knob and ignore it where unsupported.
type ProjectCatalog ¶ added in v0.38.0
type ProjectCatalog struct {
ID string
Title string
Objects []ProjectObject
}
type ProjectChoice ¶ added in v0.38.0
ProjectChoice identifies a configured DataTug project, not a database. It is ui.go's original type, moved here unchanged: ChatUI's SetProjectChoices/chatui_pickers.go's projectPickerOverlay still use it.
type ProjectObject ¶ added in v0.38.0
type ProjectObject struct {
Reference ContextReference
Columns []string
ColumnTypes map[string]string
QueryType string // saved query metadata, shown locally in Project explorer
QueryText string // loaded query document, not included in model context
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 SavedDTQLRunner ¶ added in v0.49.0
type SavedDTQLRunner interface {
RunDTQLWithVariables(context.Context, string, map[string]string) (QueryResult, error)
}
SavedDTQLRunner verifies the saved definition's type at execution time. Browser chat requires it so an HTTP query cannot be swapped in after listing.
type SavedHTTPRunner ¶ added in v0.49.0
type SavedHTTPRunner interface {
RunHTTPWithVariables(context.Context, string, map[string]string) (QueryResult, error)
}
SavedHTTPRunner verifies the saved definition's type at execution time.
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
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 SavedQueryParameterizedRunner ¶ added in v0.45.0
type SavedQuerySaveRequest ¶ added in v0.45.0
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 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) ApplyJoinCandidateActive ¶ added in v0.49.0
func (c *SessionChat) ApplyJoinCandidateActive(ctx context.Context, sessionID, recordSetID string, candidateID JoinCandidateID) (RecordSet, 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) ApplyWorkspaceActionActive ¶ added in v0.49.0
func (c *SessionChat) ApplyWorkspaceActionActive(ctx context.Context, sessionID string, action WorkspaceAction) (ContextReference, error)
ApplyWorkspaceActionActive keeps the browser's session check and mutation under one lock. A terminal session switch cannot slip between them.
func (*SessionChat) Ask ¶ added in v0.37.0
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
AskActive refuses a browser submission if the terminal switched sessions after the browser read its snapshot.
func (*SessionChat) BrowserHTTPSettings ¶ added in v0.49.0
func (c *SessionChat) BrowserHTTPSettings(ctx context.Context, sessionID, rawURL string) ([]BrowserHTTPSetting, error)
func (*SessionChat) BrowserSessionAction ¶ added in v0.49.0
func (c *SessionChat) BrowserSessionAction(ctx context.Context, expectedID, action, value string) error
BrowserSessionAction applies session controls to the exact session the browser displayed. The check and mutation share one lock.
func (*SessionChat) BrowserSettings ¶ added in v0.49.0
func (c *SessionChat) BrowserSettings(ctx context.Context, sessionID string) (int, string, string, error)
BrowserSettings exposes only non-secret connection identity and the TUI's result-retention setting for the active session.
func (*SessionChat) CellDetailActive ¶ added in v0.49.0
func (c *SessionChat) CellDetailActive(ctx context.Context, sessionID, recordSetID string, rowIndex int, column string) (BrowserCellDetail, error)
func (*SessionChat) ChangeBrowserHTTPSetting ¶ added in v0.49.0
func (c *SessionChat) ChangeBrowserHTTPSetting(ctx context.Context, sessionID, action, scope, kind, rawURL, name, value string) error
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) ConfigureSavedQueryService ¶ added in v0.49.0
func (c *SessionChat) ConfigureSavedQueryService(service SavedQueryService)
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) ExportRecordsActive ¶ added in v0.49.0
func (c *SessionChat) ExportRecordsActive(ctx context.Context, sessionID, recordSetID string, format ExportFormat, output io.Writer) error
ExportRecordsActive exports immutable snapshots from the active session. The browser selects either one result or the session's explicit export bucket.
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) JoinCandidatesActive ¶ added in v0.49.0
func (c *SessionChat) JoinCandidatesActive(ctx context.Context, sessionID, recordSetID string) ([]JoinCandidate, error)
func (*SessionChat) List ¶ added in v0.37.0
func (c *SessionChat) List(ctx context.Context) ([]ChatSession, error)
func (*SessionChat) ListSavedQueries ¶ added in v0.49.0
func (c *SessionChat) ListSavedQueries(ctx context.Context) ([]SavedQuery, 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) RunSavedDTQLActive ¶ added in v0.49.0
func (*SessionChat) RunSavedHTTPActive ¶ added in v0.49.0
func (*SessionChat) SaveQueryActive ¶ added in v0.49.0
func (c *SessionChat) SaveQueryActive(ctx context.Context, sessionID string, request SavedQuerySaveRequest) error
func (*SessionChat) SendHTTPRequestActive ¶ added in v0.49.0
func (c *SessionChat) SendHTTPRequestActive(ctx context.Context, sessionID string, request BrowserHTTPRequest) error
func (*SessionChat) SetBrowserVersions ¶ added in v0.49.0
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) StreamAsk ¶ added in v0.48.0
func (c *SessionChat) StreamAsk(ctx context.Context, prompt string) (iter.Seq2[ai.Event, error], func() (Turn, error))
StreamAsk runs one turn like Ask, but through the agent's StreamAskWithContext when it implements StreamingConversation, forwarding its ai.Event sequence live instead of buffering the whole turn. It shares the exact same persistence path as ask() -- context rebuild, AppendUser, the query/workspace/bookmark/join observers installed on ctx, and a final AppendTurn -- because those observers fire from inside the agent's tool Handlers regardless of whether the turn streams. When the configured agent does not implement StreamingConversation (a test fake, or unavailableSchemaConversation), StreamAsk falls back to running the ordinary buffered Ask and replays its Turn as one synthetic EventTextDelta + EventCompleted pair, so callers see a uniform contract either way.
StreamAsk holds SessionChat's lock for the whole stream, exactly as Ask does, so a concurrent Switch/Create/Delete waits for it to finish. Call the returned func once the sequence has been fully ranged over (or abandoned) to get the Turn StreamAsk persisted -- the same Turn Ask would have returned for an equivalent call.
func (*SessionChat) StreamAskActive ¶ added in v0.48.0
func (c *SessionChat) StreamAskActive(ctx context.Context, sessionID, prompt string) (iter.Seq2[ai.Event, error], func() (Turn, error))
StreamAskActive is the streaming counterpart to AskActive: it refuses a browser submission if the terminal switched sessions after the browser read its snapshot.
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 (*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 (*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 (*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 (*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 StreamingConversation ¶ added in v0.48.0
type StreamingConversation interface {
ContextualConversation
StreamAskWithContext(ctx context.Context, prompt, priorContext string) iter.Seq2[ai.Event, error]
// LastStreamTurn returns the structured Turn (Queries/Actions/Usage/Text)
// captured by the most recently completed
// StreamAskWithContext call, once its sequence has finished draining (or
// its range loop returned early). SessionChat.StreamAsk uses this to
// persist the same Turn Ask would have committed for an equivalent call.
LastStreamTurn() Turn
}
StreamingConversation is implemented by conversations that can stream progressive ai.Event values instead of buffering a whole turn (currently *AIConversation). Callers type-assert for it and fall back to ContextualConversation.AskWithContext when a conversation doesn't implement it (for example the fixed unavailableSchemaConversation, or a test fake). See AIConversation.StreamAskWithContext for the exact event contract and how to recover the structured Turn once the stream drains.
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 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"`
}
Source Files
¶
- agent.go
- attached_join.go
- bookmark.go
- bookmark_projection.go
- bridge.go
- browser_cell_detail.go
- cell_detail.go
- chart_ntcharts.go
- charts.go
- chatui.go
- chatui_chips.go
- chatui_connect_overlay.go
- chatui_export_overlay.go
- chatui_http_overlay.go
- chatui_http_settings.go
- chatui_inspector.go
- chatui_pickers.go
- chatui_query_overlay.go
- chatui_sidepanel.go
- export.go
- export_dialog.go
- grid.go
- grid_state.go
- http_command.go
- http_document_block.go
- http_request_ui.go
- http_settings.go
- http_settings_ui.go
- http_store.go
- inspector_ui.go
- interpret.go
- join.go
- join_block.go
- provider.go
- query_parameters_dialog.go
- recordset_ui.go
- refresh.go
- saved_queries.go
- saved_query_lookup.go
- schema.go
- session_chat.go
- session_chat_http.go
- session_chat_settings.go
- store.go
- toolschema.go
- ui_shared.go
- user_message_block.go
- workspace.go
- workspace_shared.go