feat: ingest Kagi Assistant threads
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.
This commit is contained in:
@@ -0,0 +1,510 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// kagiServer stands in for the Assistant v2 API: a paged conversation list and
|
||||
// an init call whose oldest page is behind a branch-pagination cursor.
|
||||
type kagiServer struct {
|
||||
mu sync.Mutex
|
||||
baseURL string
|
||||
token string
|
||||
updatedAt string
|
||||
listCalls int
|
||||
afterIDs []string
|
||||
initCalls int
|
||||
}
|
||||
|
||||
func newKagiServer(t *testing.T, token string) *kagiServer {
|
||||
t.Helper()
|
||||
// The updated_at cache is process-wide; isolate each test's fixture.
|
||||
kagiSeen.Lock()
|
||||
kagiSeen.m = map[string]string{}
|
||||
kagiSeen.Unlock()
|
||||
ks := &kagiServer{token: token, updatedAt: "2026-11-01T10:00:00Z"}
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/api/conversations", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Cookie") != "kagi_session="+ks.token {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
ks.mu.Lock()
|
||||
ks.listCalls++
|
||||
ks.afterIDs = append(ks.afterIDs, r.URL.Query().Get("after_id"))
|
||||
updated := ks.updatedAt
|
||||
ks.mu.Unlock()
|
||||
|
||||
if r.URL.Query().Get("after_id") == "" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"items": []any{map[string]any{
|
||||
"conversation": map[string]any{
|
||||
"uuid": "conv-1", "title": "ESP32 clocks", "created_at": "2026-10-30T09:00:00Z",
|
||||
"updated_at": updated, "is_saved": true, "model_name": "claude",
|
||||
},
|
||||
"snippet": "a stable list snippet",
|
||||
}},
|
||||
"has_more": true,
|
||||
})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"items": []any{map[string]any{
|
||||
"uuid": "conv-2", "title": "Idle thought", "created_at": "2026-10-31T09:00:00Z",
|
||||
"updated_at": "2026-10-31T09:00:00Z",
|
||||
}},
|
||||
"has_more": false,
|
||||
})
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/v2/conversations/conv-1/init", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Cookie") != "kagi_session="+ks.token {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
ks.mu.Lock()
|
||||
ks.initCalls++
|
||||
ks.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"conversation": map[string]any{
|
||||
"uuid": "conv-1", "title": "ESP32 clocks", "created_at": "2026-10-30T09:00:00Z",
|
||||
"updated_at": ks.updatedAt, "is_saved": true, "model_name": "claude",
|
||||
},
|
||||
"active_branch": map[string]any{"uuid": "branch-1", "is_default": true},
|
||||
"turns": []any{
|
||||
map[string]any{"uuid": "turn-2", "role": "assistant", "content": "Use the GT911 stub.", "created_at": "2026-10-30T09:01:00Z"},
|
||||
},
|
||||
"turns_has_more": true,
|
||||
})
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/v2/conversations/conv-2/init", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"conversation": map[string]any{
|
||||
"uuid": "conv-2", "title": "Idle thought", "created_at": "2026-10-31T09:00:00Z",
|
||||
"updated_at": "2026-10-31T09:00:00Z",
|
||||
},
|
||||
"turns": []any{
|
||||
map[string]any{"uuid": "turn-3", "role": "user", "content": "a half-formed idea"},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
mux.HandleFunc("/api/v2/branches/branch-1/turns", func(w http.ResponseWriter, r *http.Request) {
|
||||
ks.mu.Lock()
|
||||
ks.afterIDs = append(ks.afterIDs, "before="+r.URL.Query().Get("before"))
|
||||
ks.mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"turns": []any{
|
||||
map[string]any{"uuid": "turn-1", "role": "user", "content": "How do I initialize the touch panel?", "created_at": "2026-10-30T09:00:00Z"},
|
||||
},
|
||||
"has_more": false,
|
||||
})
|
||||
})
|
||||
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
ks.baseURL = srv.URL
|
||||
return ks
|
||||
}
|
||||
|
||||
func (ks *kagiServer) ingester() *KagiIngester {
|
||||
return &KagiIngester{
|
||||
Version: "kagi/v1",
|
||||
BaseURL: ks.baseURL,
|
||||
Token: ks.token,
|
||||
MaxThreads: 500,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
func TestKagiIngestsThreadsWithOlderTurns(t *testing.T) {
|
||||
ks := newKagiServer(t, "token-1")
|
||||
results, err := ks.ingester().IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("IngestAll: %v", err)
|
||||
}
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("want 2 threads, got %d", len(results))
|
||||
}
|
||||
|
||||
var conv1 *IngestResult
|
||||
for _, r := range results {
|
||||
if r.Provenance["conversation_id"] == "conv-1" {
|
||||
conv1 = r
|
||||
}
|
||||
}
|
||||
if conv1 == nil {
|
||||
t.Fatal("conv-1 not ingested")
|
||||
}
|
||||
if !strings.Contains(conv1.Content, "## User") || !strings.Contains(conv1.Content, "How do I initialize the touch panel?") {
|
||||
t.Fatalf("older user turn missing from body:\n%s", conv1.Content)
|
||||
}
|
||||
if !strings.Contains(conv1.Content, "## Assistant") || !strings.Contains(conv1.Content, "GT911 stub") {
|
||||
t.Fatalf("assistant turn missing from body:\n%s", conv1.Content)
|
||||
}
|
||||
if conv1.Title != "ESP32 clocks" {
|
||||
t.Fatalf("title = %q", conv1.Title)
|
||||
}
|
||||
if conv1.Summary != "a stable list snippet" {
|
||||
t.Fatalf("summary = %q", conv1.Summary)
|
||||
}
|
||||
if conv1.Confidence != 0.9 {
|
||||
t.Fatalf("saved thread confidence = %v", conv1.Confidence)
|
||||
}
|
||||
if conv1.SourceID != "kagi" || conv1.ContentType != "assistant/thread" {
|
||||
t.Fatalf("source = %s/%s", conv1.SourceID, conv1.ContentType)
|
||||
}
|
||||
if !strings.HasSuffix(conv1.SourcePath, "/chat/conv-1") {
|
||||
t.Fatalf("source path = %q", conv1.SourcePath)
|
||||
}
|
||||
if conv1.SourceUpdated == 0 {
|
||||
t.Fatal("updated_at was not parsed")
|
||||
}
|
||||
|
||||
// The list must have followed after_id once, and turns pagination once.
|
||||
if len(ks.afterIDs) < 3 {
|
||||
t.Fatalf("expected list pagination and turn pagination, got %v", ks.afterIDs)
|
||||
}
|
||||
if ks.afterIDs[1] != "conv-1" {
|
||||
t.Fatalf("after_id = %q", ks.afterIDs[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestKagiSkipsUnchangedButFollowsEdits(t *testing.T) {
|
||||
ks := newKagiServer(t, "token-2")
|
||||
ing := ks.ingester()
|
||||
|
||||
first, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("first sweep: %v", err)
|
||||
}
|
||||
if len(first) != 2 {
|
||||
t.Fatalf("first sweep: want 2, got %d", len(first))
|
||||
}
|
||||
before := ks.initCalls
|
||||
|
||||
second, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("second sweep: %v", err)
|
||||
}
|
||||
if len(second) != 0 {
|
||||
t.Fatalf("second sweep: everything was cached, got %d", len(second))
|
||||
}
|
||||
if ks.initCalls != before {
|
||||
t.Fatalf("unchanged thread was re-fetched (%d -> %d)", before, ks.initCalls)
|
||||
}
|
||||
|
||||
// A new turn bumps updated_at: the thread must be re-read and versioned.
|
||||
ks.mu.Lock()
|
||||
ks.updatedAt = "2026-11-02T12:00:00Z"
|
||||
ks.mu.Unlock()
|
||||
third, err := ing.IngestAll()
|
||||
if err != nil {
|
||||
t.Fatalf("third sweep: %v", err)
|
||||
}
|
||||
var edited *IngestResult
|
||||
for _, r := range third {
|
||||
if r.Provenance["conversation_id"] == "conv-1" {
|
||||
edited = r
|
||||
}
|
||||
}
|
||||
if edited == nil {
|
||||
t.Fatal("edited thread was skipped")
|
||||
}
|
||||
if edited.Fingerprint != first[0].Fingerprint && edited.Fingerprint != first[1].Fingerprint {
|
||||
t.Fatal("fingerprint changed for the same conversation")
|
||||
}
|
||||
var sameFP bool
|
||||
for _, r := range first {
|
||||
if r.Fingerprint == edited.Fingerprint && r.ContentHash == edited.ContentHash {
|
||||
sameFP = true
|
||||
}
|
||||
}
|
||||
if sameFP {
|
||||
t.Fatal("content hash did not change after an edit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKagiAuthFailureIsExplicit(t *testing.T) {
|
||||
ks := newKagiServer(t, "token-3")
|
||||
ing := ks.ingester()
|
||||
ing.Token = "expired"
|
||||
_, err := ing.IngestAll()
|
||||
if err == nil || !strings.Contains(err.Error(), "session token") {
|
||||
t.Fatalf("want session-token error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKagiLongThreadKeepsNewestTurns(t *testing.T) {
|
||||
turns := make([]kagiTurn, 0, 16)
|
||||
for i := 0; i < 16; i++ {
|
||||
role := "user"
|
||||
marker := ""
|
||||
if i == 0 {
|
||||
marker = "OLDEST-MARKER "
|
||||
}
|
||||
if i%2 == 1 {
|
||||
role = "assistant"
|
||||
}
|
||||
turns = append(turns, kagiTurn{UUID: "t", Role: role, Content: marker + strings.Repeat("x", 9000)})
|
||||
}
|
||||
turns[len(turns)-1].Content = "NEWEST-MARKER " + strings.Repeat("y", 9000)
|
||||
|
||||
out := renderKagiThread(kagiConversation{Title: "long thread"}, turns)
|
||||
if !strings.Contains(out, "NEWEST-MARKER") {
|
||||
t.Fatal("newest turn was dropped")
|
||||
}
|
||||
if strings.Contains(out, "OLDEST-MARKER") {
|
||||
t.Fatal("oldest turn survived truncation")
|
||||
}
|
||||
if !strings.Contains(out, "older turns truncated") {
|
||||
t.Fatal("truncation marker missing")
|
||||
}
|
||||
if n := len([]rune(out)); n > kagiMaxBodyRunes+200 {
|
||||
t.Fatalf("body not bounded: %d runes", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKagiNormalizesSessionLink(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"abc123": "abc123",
|
||||
"https://kagi.com/search?token=abc123": "abc123",
|
||||
"https://kagi.com/search?token=abc%2F123&x=1": "abc/123",
|
||||
" wrapped ": "wrapped",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := normalizeKagiToken(in); got != want {
|
||||
t.Errorf("normalizeKagiToken(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKagiTokenFromCLIConfig(t *testing.T) {
|
||||
body := `# kagi-cli config
|
||||
[mail]
|
||||
session_token = "not-this"
|
||||
|
||||
[auth]
|
||||
api_key = "key"
|
||||
session_token = "the-session"
|
||||
|
||||
[profiles.work.auth]
|
||||
session_token = "profile-session"
|
||||
`
|
||||
if got := kagiTokenFromTOML(body); got != "the-session" {
|
||||
t.Fatalf("token = %q", got)
|
||||
}
|
||||
if got := kagiTokenFromTOML("[profiles.work.auth]\nsession_token = \"x\"\n"); got != "" {
|
||||
t.Fatalf("profile token leaked: %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user