d27c682c19
Add a Kagi source that indexes Assistant conversations with the subscriber
session token, one entry per thread.
- Read the token from KAGI_SESSION_TOKEN, KAGI_SESSION_TOKEN_FILE, or the
kagi-cli config ([auth] session_token); accept full session-link URLs.
- List conversations through /api/conversations, load each thread via
/api/v2/conversations/{id}/init, and walk older turn pages through the
branch turns endpoint.
- Render one markdown document per thread (stable fingerprint by conversation
UUID, content hash for versioning), keeping the newest turns when a thread
exceeds the body budget.
- Skip re-fetching threads whose updated_at has not moved during this process.
- Wire the 30-minute watcher ticker + sync status, the `knox kagi` command,
the full ingest sweep, MCP scope filtering, thread anchoring, and web links.
511 lines
14 KiB
Go
511 lines
14 KiB
Go
package ingest
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// KagiIngester indexes Kagi Assistant conversations using the subscriber
|
|
// session cookie (`kagi_session`). One entry is recorded per conversation:
|
|
// threads are dense and readable as a unit, and a stable fingerprint lets the
|
|
// observation log version edits instead of shredding a thread into messages.
|
|
//
|
|
// Configured entirely by environment: KAGI_SESSION_TOKEN (required; a
|
|
// `https://kagi.com/search?token=...` session link is accepted and normalized),
|
|
// optional KAGI_ASSISTANT_BASE_URL and KAGI_MAX_THREADS. When the env var is
|
|
// unset the token is read from KAGI_SESSION_TOKEN_FILE or, failing that, from
|
|
// the kagi-cli config file so a logged-in CLI keeps knox working without a
|
|
// second copy of the credential.
|
|
//
|
|
// Endpoints are Kagi Assistant's v2 conversation API:
|
|
//
|
|
// GET /api/conversations?limit=100&all=true[&after_id=…]
|
|
// GET /api/v2/conversations/{uuid}/init[?branch_uuid=…]
|
|
// GET /api/v2/branches/{branch}/turns?include=lite_events&limit=100&before=…
|
|
type KagiIngester struct {
|
|
Version string
|
|
BaseURL string
|
|
Token string
|
|
MaxThreads int
|
|
client *http.Client
|
|
}
|
|
|
|
const (
|
|
kagiDefaultBase = "https://assistant.kagi.com"
|
|
kagiMaxThreads = 500
|
|
kagiMaxPageRunes = 8000 // per message
|
|
kagiMaxBodyRunes = 96000 // per thread, keeps the DB bounded
|
|
kagiListPages = 20 // 20 * 100 conversations
|
|
)
|
|
|
|
func NewKagiIngester() *KagiIngester {
|
|
base := strings.TrimRight(strings.TrimSpace(os.Getenv("KAGI_ASSISTANT_BASE_URL")), "/")
|
|
if base == "" {
|
|
base = kagiDefaultBase
|
|
}
|
|
maxThreads := kagiMaxThreads
|
|
if v := strings.TrimSpace(os.Getenv("KAGI_MAX_THREADS")); v != "" {
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
|
maxThreads = n
|
|
}
|
|
}
|
|
return &KagiIngester{
|
|
Version: "kagi/v1",
|
|
BaseURL: base,
|
|
Token: kagiSessionToken(),
|
|
MaxThreads: maxThreads,
|
|
client: &http.Client{Timeout: 45 * time.Second},
|
|
}
|
|
}
|
|
|
|
func (k *KagiIngester) SourceID() string { return "kagi" }
|
|
|
|
// kagiSessionToken resolves the credential in priority order: explicit env,
|
|
// token file, then the kagi-cli config. All paths stay local.
|
|
func kagiSessionToken() string {
|
|
if v := strings.TrimSpace(os.Getenv("KAGI_SESSION_TOKEN")); v != "" {
|
|
return normalizeKagiToken(v)
|
|
}
|
|
path := strings.TrimSpace(os.Getenv("KAGI_SESSION_TOKEN_FILE"))
|
|
if path == "" {
|
|
if home, err := os.UserHomeDir(); err == nil {
|
|
path = filepath.Join(home, ".config", "kagi-cli", "config.toml")
|
|
}
|
|
}
|
|
body, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return normalizeKagiToken(kagiTokenFromTOML(string(body)))
|
|
}
|
|
|
|
// kagiTokenFromTOML extracts `session_token` from the [auth] table without
|
|
// pulling in a TOML dependency (the file has one writer with a fixed shape).
|
|
func kagiTokenFromTOML(body string) string {
|
|
inAuth := false
|
|
for _, line := range strings.Split(body, "\n") {
|
|
line = strings.TrimSpace(line)
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
if strings.HasPrefix(line, "[") {
|
|
inAuth = line == "[auth]"
|
|
continue
|
|
}
|
|
if !inAuth {
|
|
continue
|
|
}
|
|
key, value, ok := strings.Cut(line, "=")
|
|
if !ok || strings.TrimSpace(key) != "session_token" {
|
|
continue
|
|
}
|
|
return strings.Trim(strings.TrimSpace(value), `"'`)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// normalizeKagiToken accepts either a bare token or a full session link
|
|
// (https://kagi.com/search?token=...) and returns the token itself.
|
|
func normalizeKagiToken(raw string) string {
|
|
raw = strings.TrimSpace(raw)
|
|
if i := strings.Index(raw, "token="); i >= 0 && strings.Contains(raw, "://") {
|
|
raw = raw[i+len("token="):]
|
|
if j := strings.IndexAny(raw, "&#"); j >= 0 {
|
|
raw = raw[:j]
|
|
}
|
|
}
|
|
if decoded, err := url.QueryUnescape(raw); err == nil {
|
|
raw = decoded
|
|
}
|
|
return strings.TrimSpace(raw)
|
|
}
|
|
|
|
type kagiConversation struct {
|
|
UUID string `json:"uuid"`
|
|
Title string `json:"title"`
|
|
CreatedAt string `json:"created_at"`
|
|
UpdatedAt string `json:"updated_at"`
|
|
IsSaved bool `json:"is_saved"`
|
|
IsShared bool `json:"is_shared"`
|
|
FolderUUID string `json:"folder_uuid"`
|
|
ModelName string `json:"model_name"`
|
|
}
|
|
|
|
// kagiConversationItem accepts both list shapes the API has served: a wrapped
|
|
// {conversation,snippet} item and a raw conversation object.
|
|
type kagiConversationItem struct {
|
|
Conversation kagiConversation
|
|
Snippet string
|
|
}
|
|
|
|
func (i *kagiConversationItem) UnmarshalJSON(data []byte) error {
|
|
var wrapped struct {
|
|
Conversation *kagiConversation `json:"conversation"`
|
|
Snippet string `json:"snippet"`
|
|
}
|
|
if err := json.Unmarshal(data, &wrapped); err == nil && wrapped.Conversation != nil {
|
|
i.Conversation = *wrapped.Conversation
|
|
i.Snippet = wrapped.Snippet
|
|
return nil
|
|
}
|
|
var raw kagiConversation
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
return err
|
|
}
|
|
i.Conversation = raw
|
|
return nil
|
|
}
|
|
|
|
type kagiTurn struct {
|
|
UUID string `json:"uuid"`
|
|
Role string `json:"role"`
|
|
Content string `json:"content"`
|
|
CreatedAt string `json:"created_at"`
|
|
ModelName string `json:"model_name"`
|
|
}
|
|
|
|
type kagiBranch struct {
|
|
UUID string `json:"uuid"`
|
|
IsDefault bool `json:"is_default"`
|
|
}
|
|
|
|
type kagiInitResponse struct {
|
|
Conversation kagiConversation `json:"conversation"`
|
|
ActiveBranch *kagiBranch `json:"active_branch"`
|
|
Turns []kagiTurn `json:"turns"`
|
|
TurnsHasMore bool `json:"turns_has_more"`
|
|
}
|
|
|
|
type kagiTurnsPage struct {
|
|
Turns []kagiTurn `json:"turns"`
|
|
HasMore bool `json:"has_more"`
|
|
}
|
|
|
|
// kagiSeen caches uuid → updated_at for the life of the process so a sweep
|
|
// does not re-fetch every conversation when nothing changed. It is a cache, not
|
|
// a watermark: a restart re-reads everything, which is cheap enough and avoids
|
|
// a stale watermark hiding an edit.
|
|
var kagiSeen = struct {
|
|
sync.Mutex
|
|
m map[string]string
|
|
}{m: map[string]string{}}
|
|
|
|
func kagiUnchanged(uuid, updatedAt string) bool {
|
|
if updatedAt == "" {
|
|
return false
|
|
}
|
|
kagiSeen.Lock()
|
|
defer kagiSeen.Unlock()
|
|
v, ok := kagiSeen.m[uuid]
|
|
return ok && v == updatedAt
|
|
}
|
|
|
|
func kagiMarkSeen(uuid, updatedAt string) {
|
|
if updatedAt == "" {
|
|
return
|
|
}
|
|
kagiSeen.Lock()
|
|
kagiSeen.m[uuid] = updatedAt
|
|
kagiSeen.Unlock()
|
|
}
|
|
|
|
func (k *KagiIngester) IngestAll() ([]*IngestResult, error) {
|
|
if k.Token == "" {
|
|
return nil, nil // not configured
|
|
}
|
|
items, err := k.listConversations()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
results := make([]*IngestResult, 0, len(items))
|
|
failures := 0
|
|
for i, item := range items {
|
|
if k.MaxThreads > 0 && i >= k.MaxThreads {
|
|
break
|
|
}
|
|
conv := item.Conversation
|
|
if conv.UUID == "" {
|
|
continue
|
|
}
|
|
if kagiUnchanged(conv.UUID, conv.UpdatedAt) {
|
|
continue
|
|
}
|
|
init, err := k.fetchThread(conv.UUID)
|
|
if err != nil {
|
|
// A conversation deleted between list and init is expected; a
|
|
// widespread failure means the token died mid-sweep, so surface it.
|
|
failures++
|
|
continue
|
|
}
|
|
kagiMarkSeen(conv.UUID, conv.UpdatedAt)
|
|
if r := k.toResult(init, item.Snippet); r != nil {
|
|
results = append(results, r)
|
|
}
|
|
}
|
|
if len(results) == 0 && failures > 0 {
|
|
return nil, fmt.Errorf("kagi: %d of %d conversations failed to load", failures, len(items))
|
|
}
|
|
return results, nil
|
|
}
|
|
|
|
func (k *KagiIngester) listConversations() ([]kagiConversationItem, error) {
|
|
var all []kagiConversationItem
|
|
afterID := ""
|
|
for page := 0; page < kagiListPages; page++ {
|
|
u := k.BaseURL + "/api/conversations?limit=100&all=true"
|
|
if afterID != "" {
|
|
u += "&after_id=" + url.QueryEscape(afterID)
|
|
}
|
|
var resp struct {
|
|
Items []kagiConversationItem `json:"items"`
|
|
HasMore bool `json:"has_more"`
|
|
}
|
|
if err := k.getJSON(u, &resp); err != nil {
|
|
return all, err
|
|
}
|
|
all = append(all, resp.Items...)
|
|
if !resp.HasMore || len(resp.Items) == 0 {
|
|
break
|
|
}
|
|
afterID = resp.Items[len(resp.Items)-1].Conversation.UUID
|
|
if afterID == "" {
|
|
break
|
|
}
|
|
}
|
|
return all, nil
|
|
}
|
|
|
|
// fetchThread reads a conversation and walks older turn pages backwards until
|
|
// the branch start. The init call returns the newest page first.
|
|
func (k *KagiIngester) fetchThread(uuid string) (*kagiInitResponse, error) {
|
|
var init kagiInitResponse
|
|
if err := k.getJSON(k.BaseURL+"/api/v2/conversations/"+url.PathEscape(uuid)+"/init", &init); err != nil {
|
|
return nil, err
|
|
}
|
|
turns := init.Turns
|
|
hasMore := init.TurnsHasMore
|
|
seen := map[string]bool{}
|
|
for hasMore && init.ActiveBranch != nil && len(turns) > 0 {
|
|
cursor := turns[0].UUID
|
|
if cursor == "" || seen[cursor] {
|
|
break
|
|
}
|
|
seen[cursor] = true
|
|
u := k.BaseURL + "/api/v2/branches/" + url.PathEscape(init.ActiveBranch.UUID) +
|
|
"/turns?include=lite_events&limit=100&before=" + url.QueryEscape(cursor)
|
|
var page kagiTurnsPage
|
|
if err := k.getJSON(u, &page); err != nil {
|
|
return nil, err
|
|
}
|
|
existing := make(map[string]bool, len(turns))
|
|
for _, t := range turns {
|
|
if t.UUID != "" {
|
|
existing[t.UUID] = true
|
|
}
|
|
}
|
|
older := make([]kagiTurn, 0, len(page.Turns))
|
|
for _, t := range page.Turns {
|
|
if t.UUID == "" || !existing[t.UUID] {
|
|
older = append(older, t)
|
|
}
|
|
}
|
|
if page.HasMore && len(older) == 0 {
|
|
break // pagination made no progress; don't loop forever
|
|
}
|
|
turns = append(older, turns...)
|
|
hasMore = page.HasMore
|
|
}
|
|
init.Turns = turns
|
|
return &init, nil
|
|
}
|
|
|
|
func (k *KagiIngester) getJSON(u string, v any) error {
|
|
req, err := http.NewRequest(http.MethodGet, u, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Cookie", "kagi_session="+k.Token)
|
|
req.Header.Set("Accept", "application/json")
|
|
req.Header.Set("User-Agent", "knox/kagi-adapter")
|
|
resp, err := k.client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
|
return fmt.Errorf("kagi: invalid or expired Kagi session token (HTTP %d)", resp.StatusCode)
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return fmt.Errorf("kagi: GET %s: status %d", kagiAPIPath(u), resp.StatusCode)
|
|
}
|
|
// A logged-out webview answers with HTML instead of JSON; treat it as auth.
|
|
if trimmed := bytes.TrimSpace(body); len(trimmed) > 0 && trimmed[0] == '<' {
|
|
return fmt.Errorf("kagi: unexpected HTML response (session token expired?)")
|
|
}
|
|
if err := json.Unmarshal(body, v); err != nil {
|
|
return fmt.Errorf("kagi: decode %s: %w", kagiAPIPath(u), err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// kagiAPIPath drops the origin so error text cannot echo the base URL query.
|
|
func kagiAPIPath(raw string) string {
|
|
if u, err := url.Parse(raw); err == nil {
|
|
return u.Path
|
|
}
|
|
return raw
|
|
}
|
|
|
|
func (k *KagiIngester) toResult(init *kagiInitResponse, snippet string) *IngestResult {
|
|
conv := init.Conversation
|
|
if conv.UUID == "" {
|
|
return nil
|
|
}
|
|
body := renderKagiThread(conv, init.Turns)
|
|
if strings.TrimSpace(body) == "" {
|
|
return nil
|
|
}
|
|
title := strings.TrimSpace(conv.Title)
|
|
if title == "" {
|
|
title = "Kagi thread " + conv.UUID
|
|
}
|
|
summary := strings.TrimSpace(snippet)
|
|
if summary == "" {
|
|
summary = kagiFirstUserTurn(init.Turns)
|
|
}
|
|
if summary == "" {
|
|
summary = title
|
|
}
|
|
summary = truncate(summary, 300)
|
|
|
|
confidence := 0.8
|
|
if conv.IsSaved {
|
|
confidence = 0.9
|
|
}
|
|
createdAt := conv.CreatedAt
|
|
if createdAt == "" {
|
|
createdAt = conv.UpdatedAt
|
|
}
|
|
|
|
return &IngestResult{
|
|
Fingerprint: FingerprintWithMeta([]byte("kagi:"+conv.UUID), map[string]string{"source": "kagi"}),
|
|
SourceID: k.SourceID(),
|
|
SourcePath: k.BaseURL + "/chat/" + conv.UUID,
|
|
ContentType: "assistant/thread",
|
|
Title: title,
|
|
Summary: summary,
|
|
Content: body,
|
|
CreatedAt: createdAt,
|
|
Confidence: confidence,
|
|
IngesterVersion: k.Version,
|
|
ContentHash: Fingerprint([]byte(body)),
|
|
SourceUpdated: kagiMillis(conv.UpdatedAt),
|
|
Provenance: map[string]any{
|
|
"conversation_id": conv.UUID,
|
|
"url": k.BaseURL + "/chat/" + conv.UUID,
|
|
"created_at": conv.CreatedAt,
|
|
"updated_at": conv.UpdatedAt,
|
|
"model": conv.ModelName,
|
|
"folder_uuid": conv.FolderUUID,
|
|
"saved": conv.IsSaved,
|
|
"shared": conv.IsShared,
|
|
"turn_count": len(init.Turns),
|
|
},
|
|
}
|
|
}
|
|
|
|
// renderKagiThread turns a conversation into one searchable markdown document.
|
|
// When a thread is longer than the body budget the oldest turns are dropped,
|
|
// keeping the header and the newest turns (the ones most likely to matter).
|
|
func renderKagiThread(conv kagiConversation, turns []kagiTurn) string {
|
|
header := "# " + firstNonEmpty(conv.Title, conv.UUID) + "\n\n"
|
|
|
|
var meta []string
|
|
if conv.CreatedAt != "" {
|
|
meta = append(meta, "created "+conv.CreatedAt)
|
|
}
|
|
if conv.UpdatedAt != "" {
|
|
meta = append(meta, "updated "+conv.UpdatedAt)
|
|
}
|
|
if conv.ModelName != "" {
|
|
meta = append(meta, "model "+conv.ModelName)
|
|
}
|
|
if conv.IsSaved {
|
|
meta = append(meta, "saved")
|
|
}
|
|
if len(meta) > 0 {
|
|
header += "_" + strings.Join(meta, " · ") + "_\n\n"
|
|
}
|
|
|
|
var body strings.Builder
|
|
for _, t := range turns {
|
|
content := strings.TrimSpace(t.Content)
|
|
if content == "" {
|
|
continue
|
|
}
|
|
role := strings.TrimSpace(t.Role)
|
|
if role == "" {
|
|
role = "message"
|
|
}
|
|
if r := []rune(role); len(r) > 0 {
|
|
role = strings.ToUpper(string(r[0])) + string(r[1:])
|
|
}
|
|
body.WriteString("## " + role)
|
|
if t.CreatedAt != "" {
|
|
body.WriteString(" (" + t.CreatedAt + ")")
|
|
}
|
|
body.WriteString("\n\n")
|
|
body.WriteString(truncate(content, kagiMaxPageRunes))
|
|
body.WriteString("\n\n")
|
|
}
|
|
rendered := strings.TrimSpace(body.String())
|
|
if rendered == "" {
|
|
return ""
|
|
}
|
|
|
|
out := header + rendered + "\n"
|
|
if r := []rune(out); len(r) > kagiMaxBodyRunes {
|
|
tail := string(r[len(r)-kagiMaxBodyRunes:])
|
|
if i := strings.Index(tail, "## "); i >= 0 {
|
|
tail = tail[i:]
|
|
}
|
|
out = header + "_[…older turns truncated]_\n\n" + tail + "\n"
|
|
}
|
|
return out
|
|
}
|
|
|
|
func kagiFirstUserTurn(turns []kagiTurn) string {
|
|
for _, t := range turns {
|
|
if strings.EqualFold(strings.TrimSpace(t.Role), "user") && strings.TrimSpace(t.Content) != "" {
|
|
return strings.TrimSpace(t.Content)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func kagiMillis(ts string) int64 {
|
|
if ts == "" {
|
|
return 0
|
|
}
|
|
t, err := time.Parse(time.RFC3339Nano, ts)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return t.UnixMilli()
|
|
}
|