How Agentsview Session Export Works for HTML, Markdown, and GitHub Gist
Agentsview's session export feature converts chat sessions into self-contained HTML pages, structured Markdown documents, or GitHub Gists by processing SQLite-stored messages through format-specific generators in internal/server/export.go and internal/server/export_markdown.go.
The kenn-io/agentsview repository provides a Go-based session management system for AI agent interactions. Its session export functionality operates entirely server-side, transforming conversation data from a SQLite backend into portable formats via HTTP handlers or the CLI's agentsview export command. The implementation spans the server's export handlers, format-specific generators, and CLI frontend components.
Export Architecture and Data Flow
The export pipeline follows a consistent sequence across all formats, beginning with database retrieval and ending with format-specific serialization.
Session Data Retrieval
Every export request triggers database queries in internal/server/export.go. The ExportHandler calls s.db.GetSession(ctx, sessionID) to fetch session metadata, followed by s.db.GetAllMessages(ctx, sessionID) to retrieve the complete message history. These functions are defined in internal/db/session_export.go and provide the raw data required for all subsequent formatting operations.
Format Selection
The handler routes requests based on the format query parameter using a switch statement that supports three values: html, md (Markdown), or gist. This routing logic resides in internal/server/export.go and determines whether to invoke generateExportHTML, generateExportMarkdown, or the Gist publishing workflow.
HTML Export Implementation
The HTML export produces a standalone, self-contained document that replicates the application's transcript view.
Template-Based Generation
generateExportHTML constructs the output by applying the exportTemplateStr template to a filtered message set. This template bundles CSS and JavaScript toggles, ensuring the exported file renders identically to the on-screen view without external dependencies.
Message Filtering and Content Processing
Before template application, filterExportHTMLMessages strips internal "goal-context" messages that should not appear in exported transcripts. Each remaining message is transformed into an exportMessage struct containing the role, timestamp, and HTML-escaped content. This escaping prevents XSS vulnerabilities while preserving text formatting.
Markdown Export Implementation
The Markdown export generates a deterministic, structured document capable of representing complex conversation trees, including child sessions spawned by tool calls.
Recursive Session Tree Loading
Unlike HTML export, Markdown generation supports hierarchical session structures. generateExportMarkdown in internal/server/export_markdown.go calls loadExportSessionTree to recursively fetch parent and child sessions based on the requested depth. The CLI accepts --depth all for complete trees or --depth 1 for direct children only.
Segment Parsing and Semantic Preservation
Each message undergoes processing by parseMarkdownSegments, which decomposes content into typed segments including plain text, thinking blocks, code blocks, and tool calls. Rather than emitting raw Markdown immediately, the generator wraps these segments in XML-style tags (<message>, <tool_call>, <code_block>). This intermediate representation preserves semantic structure for frontend re-importation while rendering as clean Markdown in standard viewers.
GitHub Gist Publishing
The Gist export combines HTML generation with GitHub API integration to create hosted, shareable transcripts.
Token Resolution Strategy
When processing gist format requests, resolveGitHubToken implements a hierarchical authentication strategy. The system first checks the --token CLI flag, then falls back to the AGENTSVIEW_GITHUB_TOKEN environment variable. For localhost deployments specifically, it executes gh auth token to extract credentials from the GitHub CLI.
API Integration and Response Generation
createGist constructs a JSON payload containing the HTML content, description, and public/private status, then POSTs to https://api.github.com/gists. The publishExportHTML function orchestrates this process, returning a structured response that includes the gist_url, raw_url, and an HTML preview URL via https://htmlpreview.github.io/?.
Command-Line Usage Examples
The cmd/agentsview/export.go CLI frontend exposes these formats through the agentsview export command.
Export to HTML
Generate a standalone HTML file suitable for offline viewing:
agentsview export --session-id 12345 --format html > session.html
This invokes generateExportHTML and writes the templated output to stdout.
Export to Markdown with Depth Control
Capture complete conversation trees including tool-spawned sub-sessions:
agentsview export --session-id 12345 --format md --depth all > session.md
The --depth flag controls recursion levels, accepting all or specific integers.
Publish to GitHub Gist
Create a public Gist containing the HTML representation:
agentsview export \
--session-id 12345 \
--format gist \
--description "Agentsview session export" \
--public
The command returns a JSON response:
{
"gist_id": "abcd1234",
"gist_url": "https://gist.github.com/user/abcd1234",
"view_url": "https://htmlpreview.github.io/?https://gist.githubusercontent.com/user/abcd1234/raw/session.html",
"raw_url": "https://gist.githubusercontent.com/user/abcd1234/raw/session.html"
}
Programmatic Integration
Developers can invoke export functions directly from Go applications:
import (
"context"
"go.kenn.io/agentsview/internal/server"
"go.kenn.io/agentsview/internal/db"
)
func exportToHTML(ctx context.Context, database *db.DB, sessionID string) (string, error) {
sess, err := database.GetSession(ctx, sessionID)
if err != nil {
return "", err
}
msgs, err := database.GetAllMessages(ctx, sessionID)
if err != nil {
return "", err
}
// Note: GenerateExportHTML may require package exposure for external use
return server.GenerateExportHTML(sess, msgs), nil
}
Summary
- Data Source: All formats retrieve data from SQLite via
GetSessionandGetAllMessagesininternal/db/session_export.go. - HTML Generation:
generateExportHTMLproduces self-contained documents using theexportTemplateStrtemplate with internal messages filtered byfilterExportHTMLMessages. - Markdown Generation:
generateExportMarkdownhandles recursive session trees vialoadExportSessionTreeand parses content into XML-tagged segments usingparseMarkdownSegmentsininternal/server/export_markdown.go. - Gist Publishing:
createGistandresolveGitHubTokenininternal/server/export.gomanage GitHub API authentication and POST operations, with token resolution supporting CLI flags, environment variables, or GitHub CLI integration. - Security: Automatic token resolution via
gh auth tokenis restricted to localhost contexts only.
Frequently Asked Questions
How does Agentsview handle authentication for GitHub Gist exports?
Agentsview's resolveGitHubToken function implements a three-tier fallback system. It first checks for an explicitly provided CLI token, then examines the AGENTSVIEW_GITHUB_TOKEN environment variable. If neither is present and the server is running on localhost, it executes gh auth token to obtain credentials from the GitHub CLI. Remote servers require explicit token provision through flags or environment variables.
What is the difference between HTML and Markdown exports in terms of session structure?
HTML exports flatten the session to a single transcript level, filtering out internal messages and producing a standalone page suitable for immediate viewing. Markdown exports preserve hierarchical session relationships through loadExportSessionTree, recursively including child sessions spawned by tool calls. The Markdown format uses XML-style tagging to preserve semantic message components like thinking blocks and tool calls, while the HTML format applies a template that mirrors the UI appearance.
Can exported Markdown files be re-imported into Agentsview?
Yes. The Markdown export format intentionally uses an intermediate XML-style representation with tags like <message> and <tool_call> rather than pure Markdown. This structure preserves the complete semantic information of the conversation, enabling the frontend to parse and re-import sessions while still rendering cleanly as standard Markdown in other viewers.
Where does the session export logic reside in the codebase?
The core export implementation is split between internal/server/export.go (HTML generation and Gist publishing) and internal/server/export_markdown.go (Markdown-specific logic). Database access functions live in internal/db/session_export.go, while the CLI frontend is implemented in cmd/agentsview/export.go. All processing occurs server-side, with the SPA or CLI merely triggering HTTP requests to the ExportHandler.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →