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:
@@ -125,6 +125,14 @@ func NewIngestCmd(kdb *db.KnoxDB) *cobra.Command {
|
|||||||
record(r)
|
record(r)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
log.Printf("[knox] ingesting kagi...")
|
||||||
|
if results, err := ingest.NewKagiIngester().IngestAll(); err == nil {
|
||||||
|
for _, r := range results {
|
||||||
|
record(r)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Printf("[knox] kagi ingest failed: %v", err)
|
||||||
|
}
|
||||||
log.Printf("[knox] ingesting bookorbit...")
|
log.Printf("[knox] ingesting bookorbit...")
|
||||||
if results, err := ingest.NewBookOrbitIngester().IngestAll(); err == nil {
|
if results, err := ingest.NewBookOrbitIngester().IngestAll(); err == nil {
|
||||||
for _, r := range results {
|
for _, r := range results {
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/david/knox/internal/db"
|
||||||
|
"github.com/david/knox/internal/ingest"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewKagiCmd ingests Kagi Assistant conversations (one entry per thread) into
|
||||||
|
// the knowledge index.
|
||||||
|
func NewKagiCmd(kdb *db.KnoxDB) *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "kagi",
|
||||||
|
Short: "Ingest Kagi Assistant conversations into the index",
|
||||||
|
Long: `Reads Kagi Assistant threads with the subscriber session token
|
||||||
|
(KAGI_SESSION_TOKEN, KAGI_SESSION_TOKEN_FILE, or ~/.config/kagi-cli/config.toml)
|
||||||
|
and records one entry per conversation. Fingerprints by conversation ID so
|
||||||
|
edits version the existing entry instead of duplicating the thread.`,
|
||||||
|
RunE: func(c *cobra.Command, args []string) error {
|
||||||
|
ing := ingest.NewKagiIngester()
|
||||||
|
if ing.Token == "" {
|
||||||
|
return fmt.Errorf("kagi not configured: set KAGI_SESSION_TOKEN (or KAGI_SESSION_TOKEN_FILE, or run `kagi auth login`)")
|
||||||
|
}
|
||||||
|
log.Printf("[knox] ingesting Kagi Assistant threads from %s...", ing.BaseURL)
|
||||||
|
|
||||||
|
results, err := ing.IngestAll()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("kagi ingest: %w", err)
|
||||||
|
}
|
||||||
|
if len(results) == 0 {
|
||||||
|
fmt.Println("No new or changed Kagi threads.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var newCount, updated int
|
||||||
|
for _, result := range results {
|
||||||
|
_, isNew, err := kdb.RecordObservation(db.ObservationRecord{
|
||||||
|
Fingerprint: result.Fingerprint,
|
||||||
|
SourceID: result.SourceID,
|
||||||
|
SourcePath: result.SourcePath,
|
||||||
|
Project: result.Project,
|
||||||
|
ContentType: result.ContentType,
|
||||||
|
Title: result.Title,
|
||||||
|
Summary: result.Summary,
|
||||||
|
Content: result.Content,
|
||||||
|
CreatedAt: result.CreatedAt,
|
||||||
|
Confidence: result.Confidence,
|
||||||
|
IngesterVersion: result.IngesterVersion,
|
||||||
|
Trigger: "kagi_ingest",
|
||||||
|
Provenance: ingest.ProvenanceJSON(result.Provenance),
|
||||||
|
ContentHash: result.ContentHash,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[knox] db error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isNew {
|
||||||
|
newCount++
|
||||||
|
} else {
|
||||||
|
updated++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Kagi: %d threads (%d new, %d updated)\n", len(results), newCount, updated)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
+4
-2
@@ -44,7 +44,7 @@ func NewMCPServer(kdb *db.KnoxDB) *mcp.Server {
|
|||||||
Query string `json:"query,omitempty" jsonschema:"Search query"`
|
Query string `json:"query,omitempty" jsonschema:"Search query"`
|
||||||
Limit int `json:"limit,omitempty" jsonschema:"Max results (default 10)"`
|
Limit int `json:"limit,omitempty" jsonschema:"Max results (default 10)"`
|
||||||
Detail string `json:"detail,omitempty" jsonschema:"Zoom level: brief, normal, or full (default normal)"`
|
Detail string `json:"detail,omitempty" jsonschema:"Zoom level: brief, normal, or full (default normal)"`
|
||||||
Scope string `json:"scope,omitempty" jsonschema:"Source scope: all, skills, sessions, logs, snippets, code, notes, browser, karakeep, gitea, repos (default all)"`
|
Scope string `json:"scope,omitempty" jsonschema:"Source scope: all, skills, sessions, logs, snippets, code, notes, browser, karakeep, kagi, gitea, repos (default all)"`
|
||||||
}
|
}
|
||||||
|
|
||||||
mcp.AddTool(s, &mcp.Tool{Name: "knox_search", Description: "Search the knowledge index. Supports zoom levels: brief (lean), normal (default), full (verbose). Scope filters: all, skills, sessions, logs, snippets, code. A scope of all also appends the best-matching code snippets/techniques (separate index); scope 'snippets' returns only those."},
|
mcp.AddTool(s, &mcp.Tool{Name: "knox_search", Description: "Search the knowledge index. Supports zoom levels: brief (lean), normal (default), full (verbose). Scope filters: all, skills, sessions, logs, snippets, code. A scope of all also appends the best-matching code snippets/techniques (separate index); scope 'snippets' returns only those."},
|
||||||
@@ -98,7 +98,7 @@ func NewMCPServer(kdb *db.KnoxDB) *mcp.Server {
|
|||||||
type recentInput struct {
|
type recentInput struct {
|
||||||
Limit int `json:"limit,omitempty" jsonschema:"Max results (default 10)"`
|
Limit int `json:"limit,omitempty" jsonschema:"Max results (default 10)"`
|
||||||
Detail string `json:"detail,omitempty" jsonschema:"Zoom level: brief, normal, or full (default normal)"`
|
Detail string `json:"detail,omitempty" jsonschema:"Zoom level: brief, normal, or full (default normal)"`
|
||||||
Scope string `json:"scope,omitempty" jsonschema:"Source scope: all, skills, sessions, logs, notes, browser, karakeep, gitea, repos (default all)"`
|
Scope string `json:"scope,omitempty" jsonschema:"Source scope: all, skills, sessions, logs, notes, browser, karakeep, kagi, gitea, repos (default all)"`
|
||||||
}
|
}
|
||||||
|
|
||||||
mcp.AddTool(s, &mcp.Tool{Name: "knox_recent", Description: "Show recent knowledge entries with zoom levels: brief, normal (default), full."},
|
mcp.AddTool(s, &mcp.Tool{Name: "knox_recent", Description: "Show recent knowledge entries with zoom levels: brief, normal (default), full."},
|
||||||
@@ -1266,6 +1266,8 @@ func filterByScope(entries []db.Entry, scope string) []db.Entry {
|
|||||||
return filterSource(entries, "obsidian")
|
return filterSource(entries, "obsidian")
|
||||||
case "karakeep", "bookmarks":
|
case "karakeep", "bookmarks":
|
||||||
return filterSource(entries, "karakeep")
|
return filterSource(entries, "karakeep")
|
||||||
|
case "kagi", "assistant":
|
||||||
|
return filterSource(entries, "kagi")
|
||||||
case "gitea":
|
case "gitea":
|
||||||
return filterSource(entries, "gitea")
|
return filterSource(entries, "gitea")
|
||||||
case "repos", "git":
|
case "repos", "git":
|
||||||
|
|||||||
+4
-3
@@ -1112,6 +1112,7 @@ var sourceWeight = map[string]float64{
|
|||||||
"opencode-session": 1.0,
|
"opencode-session": 1.0,
|
||||||
"obsidian": 1.0,
|
"obsidian": 1.0,
|
||||||
"karakeep": 1.0,
|
"karakeep": 1.0,
|
||||||
|
"kagi": 0.8,
|
||||||
"git": 0.35,
|
"git": 0.35,
|
||||||
"gitea": 0.35,
|
"gitea": 0.35,
|
||||||
"browser-history": 0.35,
|
"browser-history": 0.35,
|
||||||
@@ -2354,7 +2355,7 @@ func (k *KnoxDB) RescanThread(threadID int64) (int, error) {
|
|||||||
// workSources imply active intent (vs passive browsing) when judging whether a
|
// workSources imply active intent (vs passive browsing) when judging whether a
|
||||||
// thread has a real anchor.
|
// thread has a real anchor.
|
||||||
var workSources = map[string]bool{
|
var workSources = map[string]bool{
|
||||||
"git": true, "gitea": true, "opencode-session": true, "obsidian": true, "filesystem": true, "karakeep": true,
|
"git": true, "gitea": true, "opencode-session": true, "obsidian": true, "filesystem": true, "karakeep": true, "kagi": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ThreadAssessment is a per-thread snapshot for agent-driven grooming: value,
|
// ThreadAssessment is a per-thread snapshot for agent-driven grooming: value,
|
||||||
@@ -2648,7 +2649,7 @@ func (k *KnoxDB) MergeSuggestions(minShared int, minRatio float64) ([]ThreadMerg
|
|||||||
JOIN thread_observations tos ON tos.thread_id = t.id
|
JOIN thread_observations tos ON tos.thread_id = t.id
|
||||||
JOIN observations o ON o.id = tos.observation_id
|
JOIN observations o ON o.id = tos.observation_id
|
||||||
WHERE t.status='active' AND COALESCE(o.fingerprint,'') != ''
|
WHERE t.status='active' AND COALESCE(o.fingerprint,'') != ''
|
||||||
AND o.source_id IN ('git','gitea','opencode-session','obsidian','karakeep','filesystem')`)
|
AND o.source_id IN ('git','gitea','opencode-session','obsidian','karakeep','kagi','filesystem')`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -2845,7 +2846,7 @@ func (k *KnoxDB) DenyThreadNoise(dryRun bool) (removed int, closed []int64, err
|
|||||||
if err := k.db.QueryRow(
|
if err := k.db.QueryRow(
|
||||||
`SELECT COUNT(*) FROM thread_observations to2 JOIN observations o ON o.id = to2.observation_id
|
`SELECT COUNT(*) FROM thread_observations to2 JOIN observations o ON o.id = to2.observation_id
|
||||||
WHERE to2.thread_id = ?
|
WHERE to2.thread_id = ?
|
||||||
AND o.source_id IN ('git','gitea','opencode-session','obsidian','filesystem','karakeep')`,
|
AND o.source_id IN ('git','gitea','opencode-session','obsidian','filesystem','karakeep','kagi')`,
|
||||||
t.id,
|
t.id,
|
||||||
).Scan(&workLinks); err != nil {
|
).Scan(&workLinks); err != nil {
|
||||||
return removed, nil, err
|
return removed, nil, err
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -287,7 +287,7 @@ func skillsRepo() string {
|
|||||||
// - git : the repo's origin remote (SSH→HTTPS, creds stripped).
|
// - git : the repo's origin remote (SSH→HTTPS, creds stripped).
|
||||||
func webURL(sourceID, sourcePath, contentType string) string {
|
func webURL(sourceID, sourcePath, contentType string) string {
|
||||||
switch sourceID {
|
switch sourceID {
|
||||||
case "karakeep", "browser-history":
|
case "karakeep", "browser-history", "kagi":
|
||||||
if strings.HasPrefix(sourcePath, "http://") || strings.HasPrefix(sourcePath, "https://") {
|
if strings.HasPrefix(sourcePath, "http://") || strings.HasPrefix(sourcePath, "https://") {
|
||||||
return sourcePath
|
return sourcePath
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ var workSources = map[string]bool{
|
|||||||
"obsidian": true,
|
"obsidian": true,
|
||||||
"filesystem": true,
|
"filesystem": true,
|
||||||
"karakeep": true,
|
"karakeep": true,
|
||||||
|
"kagi": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewAutoThreader reads the tuning knobs from the environment. All have
|
// NewAutoThreader reads the tuning knobs from the environment. All have
|
||||||
|
|||||||
+68
-4
@@ -28,6 +28,7 @@ const (
|
|||||||
// is not fully re-parsed every couple of seconds.
|
// is not fully re-parsed every couple of seconds.
|
||||||
logDebounce = 30 * time.Second
|
logDebounce = 30 * time.Second
|
||||||
karakeepInterval = 30 * time.Minute
|
karakeepInterval = 30 * time.Minute
|
||||||
|
kagiInterval = 30 * time.Minute
|
||||||
bookorbitInterval = 30 * time.Minute
|
bookorbitInterval = 30 * time.Minute
|
||||||
// Brevier's archive changes only when a page is read, so an hour is plenty.
|
// Brevier's archive changes only when a page is read, so an hour is plenty.
|
||||||
brevierInterval = 1 * time.Hour
|
brevierInterval = 1 * time.Hour
|
||||||
@@ -233,6 +234,7 @@ func (w *Watcher) Start() error {
|
|||||||
gitTicker := time.NewTicker(gitInterval)
|
gitTicker := time.NewTicker(gitInterval)
|
||||||
opencodeTicker := time.NewTicker(opencodeInterval)
|
opencodeTicker := time.NewTicker(opencodeInterval)
|
||||||
karakeepTicker := time.NewTicker(karakeepInterval)
|
karakeepTicker := time.NewTicker(karakeepInterval)
|
||||||
|
kagiTicker := time.NewTicker(kagiInterval)
|
||||||
bookorbitTicker := time.NewTicker(bookorbitInterval)
|
bookorbitTicker := time.NewTicker(bookorbitInterval)
|
||||||
brevierTicker := time.NewTicker(brevierInterval)
|
brevierTicker := time.NewTicker(brevierInterval)
|
||||||
healthTicker := time.NewTicker(healthInterval)
|
healthTicker := time.NewTicker(healthInterval)
|
||||||
@@ -249,16 +251,16 @@ func (w *Watcher) Start() error {
|
|||||||
// Ingestion only runs where the sources exist. A node with no local
|
// Ingestion only runs where the sources exist. A node with no local
|
||||||
// sources (KNOX_LOCAL_SOURCES=none) leaves these nil: nil channels block
|
// sources (KNOX_LOCAL_SOURCES=none) leaves these nil: nil channels block
|
||||||
// forever, so the select never fires for them.
|
// forever, so the select never fires for them.
|
||||||
var browserC, giteaC, gitC, opencodeC, karakeepC, bookorbitC, brevierC, healthC <-chan time.Time
|
var browserC, giteaC, gitC, opencodeC, karakeepC, kagiC, bookorbitC, brevierC, healthC <-chan time.Time
|
||||||
if LocalSourcesEnabled() {
|
if LocalSourcesEnabled() {
|
||||||
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
|
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
|
||||||
opencodeC, karakeepC, bookorbitC = opencodeTicker.C, karakeepTicker.C, bookorbitTicker.C
|
opencodeC, karakeepC, kagiC = opencodeTicker.C, karakeepTicker.C, kagiTicker.C
|
||||||
brevierC, healthC = brevierTicker.C, healthTicker.C
|
bookorbitC, brevierC, healthC = bookorbitTicker.C, brevierTicker.C, healthTicker.C
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: local ingest disabled, derivation still active")
|
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: local ingest disabled, derivation still active")
|
||||||
}
|
}
|
||||||
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
|
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
|
||||||
var opencodeRunning, karakeepRunning, bookorbitRunning, brevierRunning, healthRunning, snippetRunning atomic.Bool
|
var opencodeRunning, karakeepRunning, kagiRunning, bookorbitRunning, brevierRunning, healthRunning, snippetRunning atomic.Bool
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -344,6 +346,14 @@ func (w *Watcher) Start() error {
|
|||||||
defer karakeepRunning.Store(false)
|
defer karakeepRunning.Store(false)
|
||||||
w.ingestKarakeep()
|
w.ingestKarakeep()
|
||||||
}()
|
}()
|
||||||
|
case <-kagiC:
|
||||||
|
if !kagiRunning.CompareAndSwap(false, true) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
defer kagiRunning.Store(false)
|
||||||
|
w.ingestKagi()
|
||||||
|
}()
|
||||||
case <-bookorbitC:
|
case <-bookorbitC:
|
||||||
if !bookorbitRunning.CompareAndSwap(false, true) {
|
if !bookorbitRunning.CompareAndSwap(false, true) {
|
||||||
continue
|
continue
|
||||||
@@ -805,6 +815,60 @@ func (w *Watcher) ingestKarakeep() {
|
|||||||
w.recordSync("karakeep", karakeepInterval, db.SyncOK, newCount, 0, skipped, len(results), nil)
|
w.recordSync("karakeep", karakeepInterval, db.SyncOK, newCount, 0, skipped, len(results), nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ingestKagi pulls Kagi Assistant conversations, one entry per thread, using a
|
||||||
|
// subscriber session token (KAGI_SESSION_TOKEN, or the kagi-cli config).
|
||||||
|
func (w *Watcher) ingestKagi() {
|
||||||
|
ing := ingest.NewKagiIngester()
|
||||||
|
if ing.Token == "" {
|
||||||
|
w.recordSync("kagi", kagiInterval, db.SyncUnconfigured, 0, 0, 0, 0, nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
results, err := ing.IngestAll()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[knox] kagi ingest error: %v", err)
|
||||||
|
w.recordSync("kagi", kagiInterval, db.SyncError, 0, 0, 0, 0, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(results) == 0 {
|
||||||
|
w.recordSync("kagi", kagiInterval, db.SyncOK, 0, 0, 0, 0, nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The ingester already skips conversations whose updated_at has not moved
|
||||||
|
// since this process last read them; the content hash in RecordObservation
|
||||||
|
// still decides whether a re-read is a new version or a no-op.
|
||||||
|
var newCount, updated int
|
||||||
|
for _, result := range results {
|
||||||
|
_, isNew, err := w.knoxDB.RecordObservation(db.ObservationRecord{
|
||||||
|
Fingerprint: result.Fingerprint,
|
||||||
|
SourceID: result.SourceID,
|
||||||
|
SourcePath: result.SourcePath,
|
||||||
|
Project: result.Project,
|
||||||
|
ContentType: result.ContentType,
|
||||||
|
Title: result.Title,
|
||||||
|
Summary: result.Summary,
|
||||||
|
Content: result.Content,
|
||||||
|
CreatedAt: result.CreatedAt,
|
||||||
|
Confidence: result.Confidence,
|
||||||
|
IngesterVersion: result.IngesterVersion,
|
||||||
|
Trigger: "kagi_timer",
|
||||||
|
Provenance: ingest.ProvenanceJSON(result.Provenance),
|
||||||
|
ContentHash: result.ContentHash,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isNew {
|
||||||
|
newCount++
|
||||||
|
} else {
|
||||||
|
updated++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if newCount > 0 || updated > 0 {
|
||||||
|
log.Printf("[knox] kagi: %d new, %d updated", newCount, updated)
|
||||||
|
}
|
||||||
|
w.recordSync("kagi", kagiInterval, db.SyncOK, newCount, updated, 0, len(results), nil)
|
||||||
|
}
|
||||||
|
|
||||||
// ingestBookOrbit pulls reading highlights (one entry per book chapter) from a
|
// ingestBookOrbit pulls reading highlights (one entry per book chapter) from a
|
||||||
// self-hosted BookOrbit instance configured via BOOKORBIT_URL,
|
// self-hosted BookOrbit instance configured via BOOKORBIT_URL,
|
||||||
// BOOKORBIT_USERNAME and BOOKORBIT_PASSWORD.
|
// BOOKORBIT_USERNAME and BOOKORBIT_PASSWORD.
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ and maintains a searchable index. Use 'knox watch' for daemon mode.`,
|
|||||||
root.AddCommand(knoxcmd.NewTopicsCmd(kdb))
|
root.AddCommand(knoxcmd.NewTopicsCmd(kdb))
|
||||||
root.AddCommand(knoxcmd.NewGiteaCmd(kdb))
|
root.AddCommand(knoxcmd.NewGiteaCmd(kdb))
|
||||||
root.AddCommand(knoxcmd.NewKarakeepCmd(kdb))
|
root.AddCommand(knoxcmd.NewKarakeepCmd(kdb))
|
||||||
|
root.AddCommand(knoxcmd.NewKagiCmd(kdb))
|
||||||
root.AddCommand(knoxcmd.NewBookOrbitCmd(kdb))
|
root.AddCommand(knoxcmd.NewBookOrbitCmd(kdb))
|
||||||
root.AddCommand(knoxcmd.NewBrevierCmd(kdb))
|
root.AddCommand(knoxcmd.NewBrevierCmd(kdb))
|
||||||
root.AddCommand(knoxcmd.NewSkillsHealthCmd())
|
root.AddCommand(knoxcmd.NewSkillsHealthCmd())
|
||||||
|
|||||||
Reference in New Issue
Block a user