Repository navigation
Expand file tree
/
Copy pathdocuments.js
More file actions
261 lines (242 loc) · 11.1 KB
/
Copy pathdocuments.js
File metadata and controls
261 lines (242 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// ── Document library module (local extraction + SQLite) ──────────────────────
//
// Ingests documents (PDF, Markdown, plain text, URL, office formats) by
// extracting text LOCALLY — no LLM calls, no indexing pipeline, no provider
// configuration. Extraction happens inside the add request: the response
// carries the terminal status (`ready` or `error`), so the UI can never
// observe a stuck "indexing" state. Document records and extracted source
// text persist to the SQLite project database (`db.js`); search infrastructure
// over the library lives in `documents-search.js` (FTS5 chunks) and the agent
// retrieves through the library MCP tools.
//
// Status transitions are broadcast over WebSocket via an injected `broadcast`
// callback as `documents_status` events (a consistency mechanism — with
// synchronous ingest the HTTP response already carries the terminal status).
import { randomUUID } from "node:crypto";
import * as db from "./db.js";
import * as readers from "./readers.js";
import * as search from "./documents-search.js";
import * as knowledge from "./knowledge-store.js";
import { fetchUrlAsText } from "./server/web-fetch.js";
import { PDFParse } from "pdf-parse";
// Supported file extensions -> document type. The single source of truth for
// what the upload route accepts; the client file-picker `accept` and drag/paste
// type inference mirror this. Unsupported extensions are rejected (HTTP 415)
// rather than silently classified as Markdown.
export const EXT_TYPE_MAP = {
".pdf": "pdf",
".md": "markdown",
".markdown": "markdown",
".txt": "text",
".text": "text",
".docx": "docx",
".xlsx": "xlsx",
".pptx": "pptx",
".csv": "csv",
".html": "html",
".htm": "html",
".json": "json",
};
export const SUPPORTED_EXTS = Object.keys(EXT_TYPE_MAP);
// Types the ingest path accepts: every extension-mapped type plus a direct URL.
const SUPPORTED_TYPES = new Set([...Object.values(EXT_TYPE_MAP), "url"]);
// Map an uploaded filename to its document type, or null if unsupported.
export function typeForFilename(filename) {
const dot = (filename || "").lastIndexOf(".");
const ext = dot >= 0 ? filename.slice(dot).toLowerCase() : "";
return EXT_TYPE_MAP[ext] || null;
}
// URL fetch caps live in server/web-fetch.js (shared with the websearch MCP).
let broadcast = () => {}; // injected WS broadcast (no-op until initStore)
let backfillTimer = null;
// One backfill pass: converge chunk rows for pre-upgrade/straggler documents,
// then fill vectors for ready docs that lack them. `backfillVectors` returns
// "disabled" when the rung is off, so calling it unconditionally is safe.
export async function runBackfillPass({ embedder = null } = {}) {
try {
search.backfillChunks();
} catch (err) {
console.warn(`[documents] chunk backfill failed: ${err?.message || err}`);
}
try {
return await search.backfillVectors({ embedder });
} catch (err) {
console.warn(`[documents] vector backfill failed: ${err?.message || err}`);
return null;
}
}
// ── Store init ────────────────────────────────────────────────────────────────
export async function initStore({ broadcast: broadcastFn }) {
if (broadcastFn) broadcast = broadcastFn;
// Reconcile rows left non-terminal by a previous process. Synchronous ingest
// makes these rare (a crash mid-request); WITH source_text the extraction is
// already the deliverable → ready; without it the ingest cannot resume.
if (db.isDbReady()) {
for (const d of db.listDocuments()) {
if (d.status !== "queued" && d.status !== "indexing") continue;
const full = db.getDocument(d.id);
if (full?.source_text?.trim()) {
db.updateDocumentStatus(d.id, "ready");
emitStatus(d, "ready");
} else {
const msg = "Ingest interrupted by server restart; please re-add the document.";
db.updateDocumentStatus(d.id, "error", msg);
emitStatus(d, "error", msg);
}
}
// Idempotent chunk backfill for pre-upgrade rows (local CPU, no LLM).
search.backfillChunks();
// Vector backfill must repeat: a transient embedding failure leaves a ready
// doc without vectors, and the one-shot pass at semantic-rung opt-in time
// would never retry it. Run once now and on a timer thereafter.
void runBackfillPass();
if (!backfillTimer) {
const everyMs = Number(process.env.LIBRARY_BACKFILL_INTERVAL_MS) || 5 * 60 * 1000;
backfillTimer = setInterval(() => void runBackfillPass(), Math.max(1000, everyMs));
if (backfillTimer.unref) backfillTimer.unref();
}
// Knowledge Source projections follow the document lifecycle. Best-effort:
// a read-only bundle must not disable the library.
try {
knowledge.reconcileSourceProjections(db.listDocuments());
} catch (err) {
console.warn(`[documents] source projection reconcile skipped: ${err?.message || err}`);
}
}
}
// ── Public API ────────────────────────────────────────────────────────────────
// Add a document: extract text locally, persist it, return the TERMINAL status.
// The row is inserted as `queued` first so a mid-extraction crash leaves
// something for startup reconciliation; callers only see `ready`/`error`.
// `payload` carries the ingestion input:
// - pdf: { buffer }
// - markdown/text: { content } or { buffer }
// - url: { url }
// - reader types (docx/csv/html/json/xlsx/pptx): { buffer }
export async function addDocument({ type, name, buffer, content, url, owner = null }) {
// Reject unsupported types here too: a JSON body can pass any `type`
// straight through, and an unknown one must be a 415, not a NOT NULL crash.
if (!SUPPORTED_TYPES.has(type)) {
const err = new Error(`Unsupported document type: ${type}`);
err.status = 415;
throw err;
}
const id = randomUUID();
const docName = name || defaultName(type, url, content);
const now = new Date().toISOString();
db.upsertDocument({ id, name: docName, type, status: "queued", added_at: now, owner });
try {
const sourceText = await extractSourceText({ type, name: docName, buffer, content, url });
if (!sourceText.trim()) throw new Error("Extraction produced empty text");
db.setDocumentSource(id, sourceText);
search.indexDocumentChunks(id, docName, sourceText);
db.updateDocumentStatus(id, "ready");
emitStatus({ id, name: docName }, "ready");
try {
knowledge.projectDocument({ id, name: docName, addedAt: now });
} catch (err) {
console.warn(`[documents] source projection failed for ${id}: ${err?.message || err}`);
}
// Semantic rung is a post-ready enhancement: it never gates the ingest, and
// a lane failure only costs this document its vector (it stays missing, so
// the next pass retries it). Deliberately not awaited.
if (search.semanticRungStatus().enabled) {
void search.scheduleEmbed(id).catch((err) => {
console.error(`[documents] embed scheduling failed for ${id}:`, err?.message || err);
});
}
return { id, name: docName, status: "ready" };
} catch (err) {
const msg = err.message || "Ingest failed";
db.updateDocumentStatus(id, "error", msg);
emitStatus({ id, name: docName }, "error", msg);
console.error(`[documents] ingest failed for "${docName}":`, msg);
return { id, name: docName, status: "error", error: msg };
}
}
export function listDocuments(owner = null) {
return db.listDocuments(owner); // [{ id, name, type, status, addedAt, error }]
}
// Return the extracted source text for a document (for the "view content" UI).
export async function getDocumentContent(id, owner = null) {
const doc = db.getDocument(id, owner);
return doc?.source_text ?? null;
}
// Delete a document (record + source text + index rows, via ON DELETE CASCADE).
// Idempotent: a missing id succeeds. With an owner, a document owned by someone
// else is reported as not removed and is left untouched.
export async function removeDocument(id, owner = null) {
const removed = db.deleteDocument(id, owner);
if (!removed) return false;
try {
knowledge.removeDocumentProjection(id);
} catch (err) {
console.warn(`[documents] source projection removal skipped for ${id}: ${err?.message || err}`);
}
return true;
}
// ── Local extraction ─────────────────────────────────────────────────────────
// Extract plain text for any supported document type. Pure-local: file buffers
// are parsed in-process, URLs are fetched (SSRF-protected). Throws with a
// specific message on failure; addDocument turns that into an `error` row.
//
// Exported for the 智语 room attachment lane (zhiyu-room-attachments): a room
// attachment needs the same extraction the library uses, and a second copy of
// "what counts as a readable file" is exactly how the two would drift.
export async function extractSourceText({ type, buffer, content, url }) {
if (url || type === "url") {
return fetchUrlAsText(url);
}
if (type === "markdown" || type === "text") {
const text = content ?? (buffer ? buffer.toString("utf8") : "");
if (!text.trim()) throw new Error(`Missing ${type} content`);
return text;
}
if (type === "pdf") {
if (!buffer) throw new Error("Missing PDF buffer");
// pdf-parse v2: one parser instance per document; destroy releases the
// worker it spins up, so the finally matters as much as the await.
const parser = new PDFParse({ data: new Uint8Array(buffer) });
try {
const result = await parser.getText();
const text = (result?.text || "").trim();
if (!text) throw new Error("PDF extraction produced empty text (scanned/image PDF?)");
return text;
} finally {
parser.destroy();
}
}
if (readers.hasReader(type)) {
// Reader-backed types extract from the buffer; a content-only payload means
// a restart re-ingest of already-extracted text — pass it through.
if (buffer) return readers.extractText(type, buffer);
const text = content || "";
if (!text.trim()) throw new Error(`Missing ${type} content`);
return text;
}
throw new Error(`Unsupported document type: ${type}`);
}
// ── Helpers ──────────────────────────────────────────────────────────────────
function defaultName(type, url, content) {
if (type === "url" && url) {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
if (type === "text") {
const preview = (content || "").trim().slice(0, 40).replace(/\n/g, " ");
return preview ? `Note: ${preview}` : `Note ${new Date().toISOString().slice(0, 16)}`;
}
return "Untitled";
}
function emitStatus(doc, status, error) {
broadcast({
type: "documents_status",
id: doc.id,
name: doc.name,
status,
error: error || undefined,
});
}