Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

Improve long source ingest resilience

nash_su1cf0aa76e143
diff --git a/src/components/settings/llm-presets.ts b/src/components/settings/llm-presets.ts
index 766c4be8..aca9be9f 100644
--- a/src/components/settings/llm-presets.ts
+++ b/src/components/settings/llm-presets.ts
@@ -389,14 +389,24 @@ export const LLM_PRESETS: LlmPreset[] = [
provider: "custom",
baseUrl: "https://api.xiaomimimo.com/v1",
apiMode: "chat_completions",
- // Standard OpenAI-wire endpoint at api.xiaomimimo.com/v1.
- // Preflight explicitly whitelists `authorization` + `content-type`,
- // so browser fetch would work too — but all LLM calls still go
- // through the Tauri HTTP plugin for uniformity. Model list from
- // hermes-agent (hermes_cli/models.py:247-251).
- defaultModel: "mimo-v2-pro",
- suggestedModels: ["mimo-v2-pro", "mimo-v2-omni", "mimo-v2-flash"],
- suggestedContextSize: 131072,
+ baseUrlByMode: {
+ chat_completions: "https://token-plan-cn.xiaomimimo.com/v1",
+ anthropic_messages: "https://token-plan-cn.xiaomimimo.com/anthropic",
+ },
+ // Official OpenAI-compatible endpoint at api.xiaomimimo.com/v1.
+ // Token Plan users can switch API mode to the CN OpenAI/Anthropic
+ // gateways above. MiMo V2.5 Pro / Omni advertise 1M context;
+ // Flash remains the low-cost 256K option. Older v2 ids stay
+ // selectable for existing users and gateway deployments.
+ defaultModel: "mimo-v2.5-pro",
+ suggestedModels: [
+ "mimo-v2.5-pro",
+ "mimo-v2.5",
+ "mimo-v2-flash",
+ "mimo-v2-pro",
+ "mimo-v2-omni",
+ ],
+ suggestedContextSize: 1000000,
},
{
id: "volcengine-ark",
diff --git a/src/components/settings/preset-resolver.test.ts b/src/components/settings/preset-resolver.test.ts
index 0737da15..93ae399f 100644
--- a/src/components/settings/preset-resolver.test.ts
+++ b/src/components/settings/preset-resolver.test.ts
@@ -30,6 +30,25 @@ describe("resolveConfig", () => {
])
})
+ it("keeps Xiaomi MiMo presets aligned with current official and Token Plan endpoints", () => {
+ const mimo = LLM_PRESETS.find((preset) => preset.id === "xiaomi-mimo")
+
+ expect(mimo?.defaultModel).toBe("mimo-v2.5-pro")
+ expect(mimo?.suggestedContextSize).toBe(1000000)
+ expect(mimo?.baseUrl).toBe("https://api.xiaomimimo.com/v1")
+ expect(mimo?.baseUrlByMode).toEqual({
+ chat_completions: "https://token-plan-cn.xiaomimimo.com/v1",
+ anthropic_messages: "https://token-plan-cn.xiaomimimo.com/anthropic",
+ })
+ expect(mimo?.suggestedModels).toEqual([
+ "mimo-v2.5-pro",
+ "mimo-v2.5",
+ "mimo-v2-flash",
+ "mimo-v2-pro",
+ "mimo-v2-omni",
+ ])
+ })
+
it("defaults reasoning to auto instead of inheriting another preset's fallback", () => {
const preset: LlmPreset = {
id: "deepseek",
diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.ts
index 5b8e2760..a2febf28 100644
--- a/src/lib/ingest-source-path-collision.test.ts
+++ b/src/lib/ingest-source-path-collision.test.ts
@@ -11,6 +11,7 @@ import { sourceSummarySlugFromIdentity } from "./source-identity"
vi.mock("@/commands/fs", () => realFs)
let sourceMarkers: string[] = []
+let failLongChunksOnce = new Set<number>()
vi.mock("./llm-client", () => ({
streamChat: vi.fn(async (_cfg, messages, cb) => {
@@ -44,6 +45,26 @@ vi.mock("./llm-client", () => ({
return
}
+ if (systemPrompt.startsWith("You are analyzing a long source document")) {
+ const chunkMatch = userPrompt.match(/Chunk:\s*(\d+)\/(\d+)/)
+ const chunkIndex = chunkMatch?.[1] ?? "0"
+ const numericChunkIndex = Number(chunkIndex)
+ if (failLongChunksOnce.has(numericChunkIndex)) {
+ failLongChunksOnce.delete(numericChunkIndex)
+ cb.onError(new Error(`chunk ${chunkIndex} failed once`))
+ return
+ }
+ cb.onToken([
+ "## Chunk Analysis",
+ `Chunk ${chunkIndex} introduced topic ${chunkIndex}.`,
+ "",
+ "## Updated Global Digest",
+ `Digest after chunk ${chunkIndex}: stable context ${chunkIndex}.`,
+ ].join("\n"))
+ cb.onDone()
+ return
+ }
+
const targetMatch = systemPrompt.match(
/source summary page at \*\*(wiki\/sources\/[^*]+)\*\*/,
)
@@ -74,12 +95,17 @@ vi.mock("./llm-client", () => ({
}))
import { autoIngest, executeIngestWrites } from "./ingest"
+import { streamChat } from "./llm-client"
+
+const mockStreamChat = vi.mocked(streamChat)
describe("autoIngest source summary paths", () => {
let tmp: { path: string; cleanup: () => Promise<void> } | undefined
beforeEach(async () => {
sourceMarkers = []
+ failLongChunksOnce = new Set()
+ mockStreamChat.mockClear()
tmp = await createTempProject("same-basename-sources")
await writeFileRaw(`${tmp.path}/purpose.md`, "# Purpose\n\nTrack project config files.\n")
@@ -237,6 +263,114 @@ describe("autoIngest source summary paths", () => {
expect(await fs.readFile(canonicalSummaryPath, "utf8")).toContain("project-a config")
})
+ it("analyzes oversized sources in chunks before final wiki generation", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["long source"]
+ const longSourcePath = `${tmp.path}/raw/sources/project-a/long-report.md`
+ await writeFileRaw(
+ longSourcePath,
+ [
+ "# Chapter One",
+ "",
+ "A".repeat(9000),
+ "",
+ "## Chapter Two",
+ "",
+ "B".repeat(9000),
+ "",
+ "## Chapter Three",
+ "",
+ "C".repeat(9000),
+ ].join("\n"),
+ )
+
+ await autoIngest(
+ tmp.path,
+ longSourcePath,
+ { ...useWikiStore.getState().llmConfig, maxContextSize: 20_000 },
+ undefined,
+ "project-a",
+ )
+
+ const chunkCalls = mockStreamChat.mock.calls.filter(([, messages]) =>
+ String(messages?.[0]?.content ?? "").startsWith("You are analyzing a long source document"),
+ )
+ expect(chunkCalls.length).toBeGreaterThan(1)
+ expect(String(chunkCalls[0][1]?.[1]?.content ?? "")).toContain("## MAIN CHUNK TO ANALYZE")
+ expect(String(chunkCalls[1][1]?.[1]?.content ?? "")).toContain(
+ "Digest after chunk 1: stable context 1.",
+ )
+ expect(String(chunkCalls[1][1]?.[1]?.content ?? "")).not.toContain(
+ "introduced topic 1",
+ )
+
+ const generationCall = mockStreamChat.mock.calls.find(([, messages]) =>
+ String(messages?.[0]?.content ?? "").includes("Based on the analysis provided, generate wiki files"),
+ )
+ expect(generationCall).toBeTruthy()
+ const generationPrompt = String(generationCall?.[1]?.[1]?.content ?? "")
+ expect(generationPrompt).toContain("Long Source Context")
+ expect(generationPrompt).toContain(
+ `Digest after chunk ${chunkCalls.length}: stable context ${chunkCalls.length}.`,
+ )
+ const finalDigestSection = generationPrompt
+ .split("## Source Context")[1]
+ ?.split("## Chunk Analysis Notes")[0] ?? ""
+ expect(finalDigestSection).toContain(
+ `Digest after chunk ${chunkCalls.length}: stable context ${chunkCalls.length}.`,
+ )
+ expect(finalDigestSection).not.toContain(
+ `Chunk ${chunkCalls.length} introduced topic ${chunkCalls.length}.`,
+ )
+ })
+
+ it("resumes oversized source analysis from the persisted chunk checkpoint", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["long source"]
+ failLongChunksOnce = new Set([2])
+ const longSourcePath = `${tmp.path}/raw/sources/project-a/resume-report.md`
+ const llmConfig = { ...useWikiStore.getState().llmConfig, maxContextSize: 20_000 }
+ await writeFileRaw(
+ longSourcePath,
+ [
+ "# Chapter One",
+ "",
+ "A".repeat(9000),
+ "",
+ "## Chapter Two",
+ "",
+ "B".repeat(9000),
+ "",
+ "## Chapter Three",
+ "",
+ "C".repeat(9000),
+ ].join("\n"),
+ )
+
+ await expect(
+ autoIngest(tmp.path, longSourcePath, llmConfig, undefined, "project-a"),
+ ).rejects.toThrow("Chunk analysis stream failed")
+
+ const progressDir = path.join(tmp.path, ".llm-wiki", "ingest-progress")
+ expect((await fs.readdir(progressDir)).filter((name) => name.endsWith(".json"))).toHaveLength(1)
+
+ mockStreamChat.mockClear()
+ await autoIngest(tmp.path, longSourcePath, llmConfig, undefined, "project-a")
+
+ const resumedChunkCalls = mockStreamChat.mock.calls.filter(([, messages]) =>
+ String(messages?.[0]?.content ?? "").startsWith("You are analyzing a long source document"),
+ )
+ expect(resumedChunkCalls.length).toBeGreaterThan(0)
+ expect(String(resumedChunkCalls[0][1]?.[1]?.content ?? "")).toContain("Chunk: 2/3")
+ expect(String(resumedChunkCalls[0][1]?.[1]?.content ?? "")).toContain(
+ "Digest after chunk 1: stable context 1.",
+ )
+ expect(String(resumedChunkCalls[0][1]?.[1]?.content ?? "")).not.toContain(
+ "introduced topic 1",
+ )
+ await expect(fs.readdir(progressDir)).resolves.toEqual([])
+ })
+
it("canonicalizes interactive source summary paths and sources frontmatter", async () => {
if (!tmp) throw new Error("missing temp project")
diff --git a/src/lib/ingest.prompt.test.ts b/src/lib/ingest.prompt.test.ts
index fcf99718..3d29009e 100644
--- a/src/lib/ingest.prompt.test.ts
+++ b/src/lib/ingest.prompt.test.ts
@@ -1,5 +1,10 @@
import { describe, it, expect, beforeEach } from "vitest"
-import { buildAnalysisPrompt, buildGenerationPrompt } from "./ingest"
+import {
+ buildAnalysisPrompt,
+ buildGenerationPrompt,
+ computeIngestSourceBudget,
+ splitSourceIntoSemanticChunks,
+} from "./ingest"
import { useWikiStore } from "@/stores/wiki-store"
beforeEach(() => {
@@ -93,3 +98,38 @@ describe("analysis + generation prompt consistency", () => {
expect(generation).toContain("MANDATORY OUTPUT LANGUAGE: Korean")
})
})
+
+describe("long-source ingest planning", () => {
+ it("scales source budget from the configured context window instead of a fixed 50k cap", () => {
+ const small = computeIngestSourceBudget(64_000, 8_000)
+ const large = computeIngestSourceBudget(1_000_000, 8_000)
+
+ expect(small).toBeGreaterThan(20_000)
+ expect(large).toBeGreaterThan(200_000)
+ expect(large).toBeLessThanOrEqual(300_000)
+ })
+
+ it("splits long sources on heading and paragraph boundaries with overlap", () => {
+ const content = [
+ "# Chapter One",
+ "",
+ "A".repeat(1200),
+ "",
+ "B".repeat(1200),
+ "",
+ "## Section Two",
+ "",
+ "C".repeat(1200),
+ "",
+ "D".repeat(1200),
+ ].join("\n")
+
+ const chunks = splitSourceIntoSemanticChunks(content, 1800, 200)
+
+ expect(chunks.length).toBeGreaterThan(1)
+ expect(chunks[0].headingPath).toBe("Chapter One")
+ expect(chunks.some((chunk) => chunk.headingPath.includes("Section Two"))).toBe(true)
+ expect(chunks[1].overlapBefore.length).toBeGreaterThan(0)
+ expect(chunks[1].main.startsWith(chunks[0].main.slice(-200))).toBe(false)
+ })
+})
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 3557b142..65e6e020 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -1,4 +1,4 @@
-import { deleteFile, fileExists, readFile, writeFile, listDirectory } from "@/commands/fs"
+import { createDirectory, deleteFile, fileExists, readFile, writeFile, listDirectory } from "@/commands/fs"
import { streamChat } from "@/lib/llm-client"
import type { LlmConfig } from "@/stores/wiki-store"
import { useWikiStore } from "@/stores/wiki-store"
@@ -23,6 +23,45 @@ import {
import { captionMarkdownImages, loadCaptionCache } from "@/lib/image-caption-pipeline"
import type { MultimodalConfig } from "@/stores/wiki-store"
import { GENERATION_WIKI_TYPES } from "@/lib/wiki-page-types"
+import { computeContextBudget } from "@/lib/context-budget"
+
+const LONG_SOURCE_MIN_BUDGET = 8_000
+const LONG_SOURCE_MAX_SINGLE_PASS_BUDGET = 300_000
+const LONG_SOURCE_CHUNK_MIN = 12_000
+const LONG_SOURCE_CHUNK_MAX = 60_000
+const LONG_SOURCE_DIGEST_MAX = 15_000
+const LONG_SOURCE_CHUNK_ANALYSIS_MAX = 40_000
+
+interface SourceChunk {
+ id: string
+ index: number
+ total: number
+ headingPath: string
+ overlapBefore: string
+ main: string
+}
+
+interface LongSourcePlan {
+ chunked: boolean
+ analysis: string
+ sourceContext: string
+ checkpointPath?: string
+}
+
+interface LongSourceCheckpoint {
+ version: 1
+ sourceIdentity: string
+ sourceHash: string
+ sourceLength: number
+ sourceBudget: number
+ targetChars: number
+ overlapChars: number
+ chunkTotal: number
+ completedThrough: number
+ globalDigest: string
+ analyses: string[]
+ updatedAt: number
+}
/**
* Resolve the LLM config that the caption pipeline should use.
@@ -540,33 +579,63 @@ async function autoIngestImpl(
}
}
- const truncatedContent = enrichedSourceContent.length > 50000
- ? enrichedSourceContent.slice(0, 50000) + "\n\n[...truncated...]"
- : enrichedSourceContent
+ const stableContextLength = schema.length + purpose.length + index.length + overview.length
+ const sourceBudget = computeIngestSourceBudget(llmConfig.maxContextSize, stableContextLength)
+ let sourceContext = enrichedSourceContent
+ let precomputedAnalysis = ""
+ let longSourceCheckpointPath: string | undefined
+
+ if (enrichedSourceContent.length > sourceBudget) {
+ const longSourcePlan = await analyzeLongSourceInChunks(
+ pp,
+ llmConfig,
+ purpose,
+ schema,
+ index,
+ sourceIdentity,
+ sourceSummarySlug,
+ folderContext,
+ enrichedSourceContent,
+ sourceBudget,
+ activityId,
+ signal,
+ )
+ if (longSourcePlan.chunked) {
+ sourceContext = longSourcePlan.sourceContext
+ precomputedAnalysis = longSourcePlan.analysis
+ longSourceCheckpointPath = longSourcePlan.checkpointPath
+ }
+ }
// ── Step 1: Analysis ──────────────────────────────────────────
// LLM reads the source and produces a structured analysis:
// key entities, concepts, main arguments, connections to existing wiki, contradictions
- activity.updateItem(activityId, { detail: "Step 1/2: Analyzing source..." })
+ activity.updateItem(activityId, {
+ detail: precomputedAnalysis
+ ? "Step 1/2: Consolidating long-source analysis..."
+ : "Step 1/2: Analyzing source...",
+ })
- let analysis = ""
+ let analysis = precomputedAnalysis
- await streamChat(
- llmConfig,
- [
- { role: "system", content: buildAnalysisPrompt(purpose, index, truncatedContent) },
- { role: "user", content: `Analyze this source document:\n\n**File:** ${sourceIdentity}${folderContext ? `\n**Folder context:** ${folderContext}` : ""}\n\n---\n\n${truncatedContent}` },
- ],
- {
- onToken: (token) => { analysis += token },
- onDone: () => {},
- onError: (err) => {
- activity.updateItem(activityId, { status: "error", detail: `Analysis failed: ${err.message}` })
+ if (!analysis) {
+ await streamChat(
+ llmConfig,
+ [
+ { role: "system", content: buildAnalysisPrompt(purpose, index, sourceContext) },
+ { role: "user", content: `Analyze this source document:\n\n**File:** ${sourceIdentity}${folderContext ? `\n**Folder context:** ${folderContext}` : ""}\n\n---\n\n${sourceContext}` },
+ ],
+ {
+ onToken: (token) => { analysis += token },
+ onDone: () => {},
+ onError: (err) => {
+ activity.updateItem(activityId, { status: "error", detail: `Analysis failed: ${err.message}` })
+ },
},
- },
- signal,
- { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: 4096 },
- )
+ signal,
+ { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: 4096 },
+ )
+ }
// A silent `return []` here would look like success to the queue
// runner and cause the task to be filter()'d out. Throw instead so
@@ -585,7 +654,7 @@ async function autoIngestImpl(
await streamChat(
llmConfig,
[
- { role: "system", content: buildGenerationPrompt(schema, purpose, index, sourceIdentity, overview, truncatedContent, sourceSummaryPath) },
+ { role: "system", content: buildGenerationPrompt(schema, purpose, index, sourceIdentity, overview, sourceContext, sourceSummaryPath) },
{
role: "user",
content: [
@@ -599,9 +668,9 @@ async function autoIngestImpl(
"",
analysis,
"",
- "## Original Source Content",
+ "## Source Context",
"",
- truncatedContent,
+ sourceContext,
"",
"---",
"",
@@ -722,6 +791,9 @@ async function autoIngestImpl(
// safe.
if (writtenPaths.length > 0 && hardFailures.length === 0) {
await saveIngestCache(pp, sourceIdentity, sourceContent, writtenPaths)
+ if (longSourceCheckpointPath) {
+ await clearLongSourceCheckpoint(longSourceCheckpointPath)
+ }
} else if (hardFailures.length > 0) {
console.warn(
`[ingest] Skipping cache save for "${sourceIdentity}" — ${hardFailures.length} block(s) failed to write: ${hardFailures.join(", ")}`,
@@ -1342,6 +1414,426 @@ async function tryReadFile(path: string): Promise<string> {
}
}
+function clampNumber(value: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, value))
+}
+
+export function computeIngestSourceBudget(
+ maxContextSize: number | undefined,
+ stableContextLength: number,
+): number {
+ const { maxCtx, responseReserve } = computeContextBudget(maxContextSize)
+ const stableReserve = Math.min(Math.floor(maxCtx * 0.25), Math.max(12_000, stableContextLength))
+ const instructionReserve = Math.max(12_000, Math.floor(maxCtx * 0.08))
+ const available = maxCtx - responseReserve - stableReserve - instructionReserve
+ const upper = Math.min(LONG_SOURCE_MAX_SINGLE_PASS_BUDGET, Math.max(LONG_SOURCE_MIN_BUDGET, Math.floor(maxCtx * 0.6)))
+ return clampNumber(Math.floor(available), LONG_SOURCE_MIN_BUDGET, upper)
+}
+
+function splitOversizedBlock(block: string, targetChars: number): string[] {
+ if (block.length <= targetChars * 1.25) return [block]
+
+ const pieces = block.match(/[^.!?。!?\n]+[.!?。!?]?|\n+/g) ?? [block]
+ const out: string[] = []
+ let current = ""
+ for (const piece of pieces) {
+ if (current && current.length + piece.length > targetChars) {
+ out.push(current.trim())
+ current = ""
+ }
+ if (piece.length > targetChars) {
+ for (let i = 0; i < piece.length; i += targetChars) {
+ const slice = piece.slice(i, i + targetChars).trim()
+ if (slice) out.push(slice)
+ }
+ } else {
+ current += piece
+ }
+ }
+ if (current.trim()) out.push(current.trim())
+ return out
+}
+
+function semanticBlocks(content: string, targetChars: number): Array<{ text: string; headingPath: string }> {
+ const blocks: Array<{ text: string; headingPath: string }> = []
+ const headingStack: string[] = []
+ let paragraph: string[] = []
+ let paragraphHeading = ""
+
+ const currentHeadingPath = () => headingStack.filter(Boolean).join(" > ")
+ const flushParagraph = () => {
+ const text = paragraph.join("\n").trim()
+ if (text) {
+ for (const piece of splitOversizedBlock(text, targetChars)) {
+ blocks.push({ text: piece, headingPath: paragraphHeading })
+ }
+ }
+ paragraph = []
+ }
+
+ for (const line of content.replace(/\r\n/g, "\n").split("\n")) {
+ const heading = /^(#{1,6})\s+(.+?)\s*$/.exec(line)
+ if (heading) {
+ flushParagraph()
+ const depth = heading[1].length
+ headingStack.length = depth - 1
+ headingStack[depth - 1] = heading[2].trim()
+ blocks.push({ text: line.trim(), headingPath: currentHeadingPath() })
+ paragraphHeading = currentHeadingPath()
+ continue
+ }
+
+ if (line.trim() === "") {
+ flushParagraph()
+ paragraphHeading = currentHeadingPath()
+ continue
+ }
+
+ if (paragraph.length === 0) paragraphHeading = currentHeadingPath()
+ paragraph.push(line)
+ }
+ flushParagraph()
+
+ return blocks
+}
+
+function overlapSuffix(text: string, maxChars: number): string {
+ if (!text || maxChars <= 0) return ""
+ if (text.length <= maxChars) return text
+ const raw = text.slice(-maxChars)
+ const paragraphBreak = raw.search(/\n\s*\n/)
+ if (paragraphBreak > 0 && raw.length - paragraphBreak > maxChars * 0.4) {
+ return raw.slice(paragraphBreak).trim()
+ }
+ const sentenceBreak = raw.search(/[.!?。!?]\s+/)
+ if (sentenceBreak > 0 && raw.length - sentenceBreak > maxChars * 0.4) {
+ return raw.slice(sentenceBreak + 1).trim()
+ }
+ return raw.trim()
+}
+
+export function splitSourceIntoSemanticChunks(
+ content: string,
+ targetChars: number,
+ overlapChars: number,
+): SourceChunk[] {
+ const target = Math.max(1_000, targetChars)
+ const blocks = semanticBlocks(content, target)
+ if (blocks.length === 0) return []
+
+ const rawChunks: Array<{ main: string; headingPath: string }> = []
+ let current: string[] = []
+ let currentLength = 0
+ let currentHeading = blocks[0]?.headingPath ?? ""
+
+ const flush = () => {
+ const main = current.join("\n\n").trim()
+ if (main) rawChunks.push({ main, headingPath: currentHeading })
+ current = []
+ currentLength = 0
+ }
+
+ for (const block of blocks) {
+ const nextLength = currentLength + block.text.length + (current.length > 0 ? 2 : 0)
+ if (current.length > 0 && nextLength > target) {
+ flush()
+ }
+ if (current.length === 0) currentHeading = block.headingPath
+ current.push(block.text)
+ currentLength += block.text.length + (current.length > 1 ? 2 : 0)
+ }
+ flush()
+
+ return rawChunks.map((chunk, idx) => ({
+ id: `chunk-${idx + 1}`,
+ index: idx + 1,
+ total: rawChunks.length,
+ headingPath: chunk.headingPath,
+ overlapBefore: idx > 0 ? overlapSuffix(rawChunks[idx - 1].main, overlapChars) : "",
+ main: chunk.main,
+ }))
+}
+
+function trimLongText(text: string, maxChars: number): string {
+ if (text.length <= maxChars) return text
+ return `${text.slice(0, maxChars).trimEnd()}\n\n[...trimmed for prompt budget...]`
+}
+
+function hashTextHex(text: string): string {
+ // 64-bit FNV-1a over UTF-16 code units. This is a stability key, not
+ // a security primitive; validation also checks source length/chunk
+ // shape before resuming a checkpoint.
+ let hash = 0xcbf29ce484222325n
+ const prime = 0x100000001b3n
+ for (let i = 0; i < text.length; i++) {
+ hash ^= BigInt(text.charCodeAt(i))
+ hash = BigInt.asUintN(64, hash * prime)
+ }
+ return hash.toString(16).padStart(16, "0")
+}
+
+function longSourceCheckpointPath(
+ projectPath: string,
+ sourceSummarySlug: string,
+ sourceHash: string,
+): string {
+ return `${normalizePath(projectPath)}/.llm-wiki/ingest-progress/${sourceSummarySlug}-${sourceHash}.json`
+}
+
+function isCompatibleLongSourceCheckpoint(
+ checkpoint: LongSourceCheckpoint,
+ params: {
+ sourceIdentity: string
+ sourceHash: string
+ sourceLength: number
+ sourceBudget: number
+ targetChars: number
+ overlapChars: number
+ chunkTotal: number
+ },
+): boolean {
+ return checkpoint.version === 1
+ && checkpoint.sourceIdentity === params.sourceIdentity
+ && checkpoint.sourceHash === params.sourceHash
+ && checkpoint.sourceLength === params.sourceLength
+ && checkpoint.sourceBudget === params.sourceBudget
+ && checkpoint.targetChars === params.targetChars
+ && checkpoint.overlapChars === params.overlapChars
+ && checkpoint.chunkTotal === params.chunkTotal
+ && checkpoint.completedThrough >= 0
+ && checkpoint.completedThrough <= params.chunkTotal
+ && Array.isArray(checkpoint.analyses)
+ && checkpoint.analyses.length === checkpoint.completedThrough
+}
+
+async function loadLongSourceCheckpoint(
+ checkpointPath: string,
+ params: Parameters<typeof isCompatibleLongSourceCheckpoint>[1],
+): Promise<LongSourceCheckpoint | null> {
+ try {
+ const raw = await readFile(checkpointPath)
+ const parsed = JSON.parse(raw) as LongSourceCheckpoint
+ if (!isCompatibleLongSourceCheckpoint(parsed, params)) return null
+ return parsed
+ } catch {
+ return null
+ }
+}
+
+async function saveLongSourceCheckpoint(
+ checkpointPath: string,
+ checkpoint: LongSourceCheckpoint,
+): Promise<void> {
+ const dir = checkpointPath.split("/").slice(0, -1).join("/")
+ await createDirectory(dir)
+ await writeFile(checkpointPath, JSON.stringify(checkpoint, null, 2))
+}
+
+async function clearLongSourceCheckpoint(checkpointPath: string): Promise<void> {
+ try {
+ if (await fileExists(checkpointPath)) {
+ await deleteFile(checkpointPath)
+ }
+ } catch {
+ // Best-effort cleanup. A stale checkpoint is ignored if source
+ // hash / chunk shape no longer matches.
+ }
+}
+
+function extractMarkedSection(raw: string, heading: string): string {
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ const re = new RegExp(`(?:^|\\n)##\\s+${escaped}\\s*\\n([\\s\\S]*?)(?=\\n##\\s|$)`, "i")
+ return re.exec(raw)?.[1]?.trim() ?? ""
+}
+
+function buildChunkAnalysisSystemPrompt(
+ purpose: string,
+ schema: string,
+ index: string,
+ sourceContent: string,
+): string {
+ return [
+ "You are analyzing a long source document for a personal wiki.",
+ "Do not output chain-of-thought, hidden reasoning, or a thinking transcript.",
+ "Analyze only the current MAIN CHUNK. Use overlap and digest for context only.",
+ "Keep stable names consistent with the existing wiki and prior digest.",
+ "",
+ languageRule(sourceContent),
+ "",
+ "Output exactly two markdown sections:",
+ "",
+ "## Chunk Analysis",
+ "- Concise summary of the main chunk",
+ "- New or updated entities",
+ "- New or updated concepts",
+ "- Claims, findings, evidence, contradictions",
+ "- Open questions or research gaps",
+ "",
+ "## Updated Global Digest",
+ "A compact document-level digest that incorporates this chunk and preserves prior cross-chunk context.",
+ "Keep this digest structured under: Summary, Entities, Concepts, Claims, Evidence, Contradictions, Open Questions, Cross-Chunk Relations.",
+ "",
+ "Stable project context follows. It changes rarely and should be treated as background:",
+ purpose ? `## Wiki Purpose\n${purpose}` : "",
+ schema ? `## Wiki Schema\n${schema}` : "",
+ index ? `## Current Wiki Index\n${trimLongText(index, 40_000)}` : "",
+ ].filter(Boolean).join("\n")
+}
+
+function buildChunkAnalysisUserPrompt(
+ sourceIdentity: string,
+ folderContext: string | undefined,
+ chunk: SourceChunk,
+ globalDigest: string,
+): string {
+ return [
+ `Source file: ${sourceIdentity}`,
+ folderContext ? `Folder context: ${folderContext}` : "",
+ `Chunk: ${chunk.index}/${chunk.total}`,
+ chunk.headingPath ? `Heading path: ${chunk.headingPath}` : "",
+ "",
+ "## Current Global Digest",
+ globalDigest || "(No prior digest yet.)",
+ "",
+ chunk.overlapBefore ? "## Previous Overlap Context\n" + chunk.overlapBefore : "",
+ "",
+ "## MAIN CHUNK TO ANALYZE",
+ chunk.main,
+ "",
+ "Return only the two requested sections. Do not repeat overlap-only facts unless the main chunk supports them.",
+ ].filter(Boolean).join("\n")
+}
+
+async function analyzeLongSourceInChunks(
+ projectPath: string,
+ llmConfig: LlmConfig,
+ purpose: string,
+ schema: string,
+ index: string,
+ sourceIdentity: string,
+ sourceSummarySlug: string,
+ folderContext: string | undefined,
+ sourceContent: string,
+ sourceBudget: number,
+ activityId: string,
+ signal?: AbortSignal,
+): Promise<LongSourcePlan> {
+ const targetChars = clampNumber(Math.floor(sourceBudget * 0.55), LONG_SOURCE_CHUNK_MIN, LONG_SOURCE_CHUNK_MAX)
+ const overlapChars = clampNumber(Math.floor(targetChars * 0.08), 800, 3_000)
+ const chunks = splitSourceIntoSemanticChunks(sourceContent, targetChars, overlapChars)
+ if (chunks.length <= 1) {
+ return { chunked: false, analysis: "", sourceContext: sourceContent }
+ }
+
+ const activity = useActivityStore.getState()
+ const systemPrompt = buildChunkAnalysisSystemPrompt(purpose, schema, index, sourceContent)
+ const sourceHash = hashTextHex(sourceContent)
+ const checkpointPath = longSourceCheckpointPath(projectPath, sourceSummarySlug, sourceHash)
+ const checkpointParams = {
+ sourceIdentity,
+ sourceHash,
+ sourceLength: sourceContent.length,
+ sourceBudget,
+ targetChars,
+ overlapChars,
+ chunkTotal: chunks.length,
+ }
+ const checkpoint = await loadLongSourceCheckpoint(checkpointPath, checkpointParams)
+ let globalDigest = checkpoint?.globalDigest ?? ""
+ const analyses: string[] = checkpoint?.analyses ? [...checkpoint.analyses] : []
+ let completedThrough = checkpoint?.completedThrough ?? 0
+
+ if (completedThrough > 0) {
+ activity.updateItem(activityId, {
+ detail: `Resuming long source analysis from chunk ${completedThrough + 1}/${chunks.length}...`,
+ })
+ }
+
+ for (const chunk of chunks) {
+ if (chunk.index <= completedThrough) continue
+ if (signal?.aborted) throw new Error("Ingest cancelled")
+ activity.updateItem(activityId, {
+ detail: `Analyzing long source chunk ${chunk.index}/${chunk.total}...`,
+ })
+
+ let raw = ""
+ let hadError = false
+ await streamChat(
+ llmConfig,
+ [
+ { role: "system", content: systemPrompt },
+ {
+ role: "user",
+ content: buildChunkAnalysisUserPrompt(
+ sourceIdentity,
+ folderContext,
+ chunk,
+ trimLongText(globalDigest, LONG_SOURCE_DIGEST_MAX),
+ ),
+ },
+ ],
+ {
+ onToken: (token) => { raw += token },
+ onDone: () => {},
+ onError: (err) => {
+ hadError = true
+ activity.updateItem(activityId, { status: "error", detail: `Chunk analysis failed: ${err.message}` })
+ },
+ },
+ signal,
+ { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: 4096 },
+ )
+
+ if (signal?.aborted) throw new Error("Ingest cancelled")
+ if (hadError) throw new Error("Chunk analysis stream failed")
+
+ const chunkAnalysis = extractMarkedSection(raw, "Chunk Analysis") || raw.trim()
+ const nextDigest = extractMarkedSection(raw, "Updated Global Digest")
+ analyses.push([
+ `## Chunk ${chunk.index}/${chunk.total}${chunk.headingPath ? ` — ${chunk.headingPath}` : ""}`,
+ trimLongText(chunkAnalysis, LONG_SOURCE_CHUNK_ANALYSIS_MAX),
+ ].join("\n"))
+
+ globalDigest = trimLongText(
+ nextDigest || [globalDigest, chunkAnalysis].filter(Boolean).join("\n\n"),
+ LONG_SOURCE_DIGEST_MAX,
+ )
+ completedThrough = chunk.index
+ await saveLongSourceCheckpoint(checkpointPath, {
+ version: 1,
+ ...checkpointParams,
+ completedThrough,
+ globalDigest,
+ analyses,
+ updatedAt: Date.now(),
+ })
+ }
+
+ const analysis = [
+ "# Consolidated Long-Document Analysis",
+ "",
+ "## Final Global Digest",
+ globalDigest || "(No digest produced.)",
+ "",
+ "## Per-Chunk Analyses",
+ analyses.join("\n\n"),
+ ].join("\n")
+
+ const sourceContext = [
+ `# Long Source Context: ${sourceIdentity}`,
+ "",
+ `The original source was analyzed in ${chunks.length} semantic chunks with paragraph/section boundaries and overlap. Use this consolidated context instead of assuming the raw document ended early.`,
+ "",
+ "## Final Global Digest",
+ globalDigest || "(No digest produced.)",
+ "",
+ "## Chunk Analysis Notes",
+ trimLongText(analyses.join("\n\n"), Math.max(sourceBudget, LONG_SOURCE_CHUNK_ANALYSIS_MAX)),
+ ].join("\n")
+
+ return { chunked: true, analysis, sourceContext, checkpointPath }
+}
+
/**
* Build a MergeFn for a given LLM config. The returned function asks
* the model to merge two versions of the same wiki page into one.
diff --git a/src/lib/llm-providers.test.ts b/src/lib/llm-providers.test.ts
index 9b25a73c..27d560cc 100644
--- a/src/lib/llm-providers.test.ts
+++ b/src/lib/llm-providers.test.ts
@@ -314,6 +314,57 @@ describe("reasoning controls", () => {
expect(body.max_reasoning_tokens).toBeUndefined()
})
+ it("maps Xiaomi MiMo reasoning off to thinking disabled and max_completion_tokens", () => {
+ const cfg = mkConfig({
+ provider: "custom",
+ model: "mimo-v2.5-pro",
+ customEndpoint: "https://api.xiaomimimo.com/v1",
+ apiMode: "chat_completions",
+ })
+ const body = getProviderConfig(cfg).buildBody(
+ [{ role: "user", content: "hi" }],
+ { temperature: 0.1, max_tokens: 2048, reasoning: { mode: "off" } },
+ ) as Record<string, unknown>
+
+ expect(body.thinking).toEqual({ type: "disabled" })
+ expect(body.max_tokens).toBeUndefined()
+ expect(body.max_completion_tokens).toBe(2048)
+ expect(body.temperature).toBe(0.1)
+ })
+
+ it("omits custom temperature for Xiaomi MiMo thinking requests on Token Plan OpenAI wire", () => {
+ const cfg = mkConfig({
+ provider: "custom",
+ model: "custom-router-model",
+ customEndpoint: "https://token-plan-cn.xiaomimimo.com/v1",
+ apiMode: "chat_completions",
+ })
+ const provider = getProviderConfig(cfg)
+ const body = provider.buildBody(
+ [{ role: "user", content: "hi" }],
+ { temperature: 0.1, max_tokens: 4096, reasoning: { mode: "auto" } },
+ ) as Record<string, unknown>
+
+ expect(provider.url).toBe("https://token-plan-cn.xiaomimimo.com/v1/chat/completions")
+ expect(body.temperature).toBeUndefined()
+ expect(body.max_completion_tokens).toBe(4096)
+ })
+
+ it("uses Bearer auth for Xiaomi MiMo Token Plan Anthropic wire", () => {
+ const cfg = mkConfig({
+ provider: "custom",
+ apiKey: "sk-mimo",
+ model: "mimo-v2.5-pro",
+ customEndpoint: "https://token-plan-cn.xiaomimimo.com/anthropic",
+ apiMode: "anthropic_messages",
+ })
+ const provider = getProviderConfig(cfg)
+
+ expect(provider.url).toBe("https://token-plan-cn.xiaomimimo.com/anthropic/v1/messages")
+ expect(provider.headers.Authorization).toBe("Bearer sk-mimo")
+ expect(provider.headers["x-api-key"]).toBeUndefined()
+ })
+
it("disables Qwen3 thinking on OpenAI-compatible local endpoints", () => {
const cfg = mkConfig({
provider: "custom",
diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.ts
index 1478bf18..d99d80bb 100644
--- a/src/lib/llm-providers.ts
+++ b/src/lib/llm-providers.ts
@@ -250,6 +250,11 @@ function isKimiEndpoint(config: LlmConfig): boolean {
|| /api\.moonshot\.(ai|cn)/i.test(config.customEndpoint)
}
+function isXiaomiMimoEndpoint(config: LlmConfig): boolean {
+ return /(^|[/:.-])mimo([/:.-]|$)/i.test(config.model)
+ || /\.?xiaomimimo\.com(?::|\/|$)/i.test(config.customEndpoint)
+}
+
function isOpenAiStrictCompletionModel(config: LlmConfig): boolean {
if ((config.provider === "azure" || (config.provider === "custom" && isAzureOpenAiEndpoint(config.customEndpoint)))
&& config.azureModelFamily === "gpt5") {
@@ -291,6 +296,35 @@ function adaptKimiBody(config: LlmConfig, body: Record<string, unknown>): void {
delete body.temperature
}
+function adaptXiaomiMimoBody(
+ config: LlmConfig,
+ body: Record<string, unknown>,
+ reasoning: ReasoningConfig,
+): void {
+ if (!isXiaomiMimoEndpoint(config)) return
+
+ // Xiaomi MiMo's OpenAI-compatible examples use
+ // `max_completion_tokens`. Accept callers' provider-agnostic
+ // `max_tokens` override but send the documented field on the wire.
+ if (typeof body.max_tokens === "number") {
+ body.max_completion_tokens = body.max_tokens
+ delete body.max_tokens
+ }
+
+ // Official thinking-mode control documents `thinking.type=disabled`.
+ // Do not invent an enabled/budget shape here; omitting the field lets
+ // the server apply the model default.
+ if (reasoning.mode === "off") {
+ body.thinking = { type: "disabled" }
+ } else {
+ // MiMo v2.5 thinking mode forces temperature=1.0 and rejects
+ // custom temperature. Structured ingest passes temperature=0.1,
+ // but it also passes reasoning off above, so keep deterministic
+ // non-thinking requests intact while protecting thinking requests.
+ delete body.temperature
+ }
+}
+
function buildOpenAiCompatibleBody(
config: LlmConfig,
messages: ChatMessage[],
@@ -300,6 +334,7 @@ function buildOpenAiCompatibleBody(
const body: Record<string, unknown> = buildOpenAiBody(messages, stripWireAgnosticOverrides(overrides))
adaptOpenAiStrictCompletionBody(config, body)
adaptKimiBody(config, body)
+ adaptXiaomiMimoBody(config, body, reasoning)
if (isDeepSeekEndpoint(config)) {
// DeepSeek V4 thinking mode. `thinking.type=disabled` is the most
@@ -451,7 +486,10 @@ function requiresBearerAuth(url: string): boolean {
// Alibaba Bailian Coding Plan — issues sk-xxx bearer-style tokens
// on its /apps/anthropic gateway; behavior matches the other
// Chinese Anthropic-wire proxies above.
- normalized.startsWith("https://coding.dashscope.aliyuncs.com/apps/anthropic")
+ normalized.startsWith("https://coding.dashscope.aliyuncs.com/apps/anthropic") ||
+ // Xiaomi MiMo Token Plan Anthropic gateway authenticates with
+ // Authorization Bearer, matching its OpenAI-compatible gateway.
+ /(^https:\/\/|^)token-plan-cn\.xiaomimimo\.com\/anthropic(?:\/|$)/i.test(normalized)
)
}