@promptev/context-engine 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5790,15 +5790,16 @@ function parseDocumentId(documentId) {
5790
5790
  }
5791
5791
  return raw;
5792
5792
  }
5793
- function scopeSql(sourceIds, principals, params) {
5793
+ function scopeSql(sourceIds, principals, params, alias = "") {
5794
+ const col = alias ? `${alias}.` : "";
5794
5795
  const where = [];
5795
5796
  if (sourceIds != null) {
5796
5797
  params.push(sourceIds);
5797
- where.push(`source_id = ANY($${params.length}::text[])`);
5798
+ where.push(`${col}source_id = ANY($${params.length}::text[])`);
5798
5799
  }
5799
5800
  if (principals != null) {
5800
5801
  params.push(principals);
5801
- where.push(`(acl IS NULL OR acl && $${params.length}::text[])`);
5802
+ where.push(`(${col}acl IS NULL OR ${col}acl && $${params.length}::text[])`);
5802
5803
  }
5803
5804
  return where.length ? `WHERE ${where.join(" AND ")}` : "";
5804
5805
  }
@@ -6057,6 +6058,19 @@ async function listDocuments(opts) {
6057
6058
  const principals = opts.principals ?? null;
6058
6059
  const params = [];
6059
6060
  let where = scopeSql(sourceIds, principals, params);
6061
+ if (opts.documentIds != null) {
6062
+ const parsedIds = [];
6063
+ for (const did of opts.documentIds) {
6064
+ try {
6065
+ parsedIds.push(parseDocumentId(did));
6066
+ } catch {
6067
+ console.warn("listDocuments: skipping invalid document id %s", did);
6068
+ }
6069
+ }
6070
+ params.push(parsedIds);
6071
+ const clause = `id = ANY($${params.length}::uuid[])`;
6072
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6073
+ }
6060
6074
  const cursorTime = parsedCursor?.time ?? parsedCursor?.created_at;
6061
6075
  const cursorId = parsedCursor?.id;
6062
6076
  if (cursorTime && cursorId && UUID_RE2.test(String(cursorId))) {
@@ -6116,6 +6130,350 @@ async function listDocuments(opts) {
6116
6130
  }
6117
6131
  return result;
6118
6132
  }
6133
+ async function spreadsheetSchema(opts) {
6134
+ const ids = [];
6135
+ for (const did of opts.documentIds ?? []) {
6136
+ try {
6137
+ ids.push(parseDocumentId(did));
6138
+ } catch {
6139
+ console.warn("spreadsheetSchema: skipping invalid document id %s", did);
6140
+ }
6141
+ }
6142
+ if (!ids.length) return [];
6143
+ const principals = opts.principals ?? null;
6144
+ const budget = opts.budget ?? MAX_SCHEMA_TEXT_CHARS;
6145
+ const params = [];
6146
+ let where = scopeSql(opts.sourceIds ?? null, principals, params);
6147
+ const mimeClause = TABULAR_MIME_PATTERNS.map((pattern) => {
6148
+ params.push(pattern);
6149
+ return `mime_type ILIKE $${params.length}`;
6150
+ }).join(" OR ");
6151
+ where = where ? `${where} AND (${mimeClause})` : `WHERE (${mimeClause})`;
6152
+ params.push(ids);
6153
+ where += ` AND id = ANY($${params.length}::uuid[])`;
6154
+ const sized = await opts.pool.query(
6155
+ `SELECT id, name, source_id, mime_type, COALESCE(LENGTH(text), 0) AS text_len
6156
+ FROM context_engine_documents
6157
+ ${where}`,
6158
+ params
6159
+ );
6160
+ const byId = /* @__PURE__ */ new Map();
6161
+ for (const row of sized.rows) {
6162
+ if (isTabularMime(row.mime_type)) byId.set(String(row.id), row);
6163
+ }
6164
+ const rows = ids.map((id) => byId.get(id)).filter((r) => r != null);
6165
+ const chosen = [];
6166
+ let spent = 0;
6167
+ for (const row of rows) {
6168
+ const len = Number(row.text_len ?? 0);
6169
+ if (chosen.length && spent + len > budget) break;
6170
+ chosen.push(String(row.id));
6171
+ spent += len;
6172
+ }
6173
+ const texts = /* @__PURE__ */ new Map();
6174
+ if (chosen.length) {
6175
+ const bodyParams = [];
6176
+ const bodyWhere = scopeSql(opts.sourceIds ?? null, principals, bodyParams);
6177
+ bodyParams.push(chosen);
6178
+ const clause = `id = ANY($${bodyParams.length}::uuid[])`;
6179
+ const { rows: bodies } = await opts.pool.query(
6180
+ `SELECT id, text FROM context_engine_documents
6181
+ ${bodyWhere ? `${bodyWhere} AND ${clause}` : `WHERE ${clause}`}`,
6182
+ bodyParams
6183
+ );
6184
+ for (const row of bodies) texts.set(String(row.id), row.text ?? null);
6185
+ }
6186
+ return rows.map((row) => {
6187
+ const id = String(row.id);
6188
+ if (!texts.has(id)) {
6189
+ return {
6190
+ document_id: id,
6191
+ name: row.name,
6192
+ source_id: row.source_id,
6193
+ sheets: null,
6194
+ schema_unavailable: "not read: this page of spreadsheets is past the text budget \u2014 narrow with sourceIds, or ask for a smaller limit"
6195
+ };
6196
+ }
6197
+ return {
6198
+ document_id: id,
6199
+ name: row.name,
6200
+ source_id: row.source_id,
6201
+ sheets: redactValueRecursive(spreadsheetSchemaFromText(texts.get(id)), opts.redaction, {
6202
+ principals,
6203
+ secretKey: opts.secretKey ?? null,
6204
+ hooks: opts.hooks
6205
+ })
6206
+ };
6207
+ });
6208
+ }
6209
+ function remainder(structure) {
6210
+ let total = 0;
6211
+ for (const [key, value] of Object.entries(structure)) {
6212
+ if (key.startsWith("more_") && typeof value === "number") total += value;
6213
+ }
6214
+ const sheets = structure.sheets;
6215
+ if (Array.isArray(sheets)) {
6216
+ for (const sheet of sheets) {
6217
+ if (sheet && typeof sheet === "object" && typeof sheet.more_columns === "number") {
6218
+ total += sheet.more_columns;
6219
+ }
6220
+ }
6221
+ }
6222
+ return total;
6223
+ }
6224
+ function boundedSheets(sheets) {
6225
+ if (!sheets?.length) return sheets;
6226
+ return sheets.slice(0, MAX_STRUCTURE_ITEMS).map((sheet) => {
6227
+ const columns = sheet.columns ?? [];
6228
+ const trimmed = {
6229
+ ...sheet,
6230
+ columns: columns.slice(0, MAX_STRUCTURE_ITEMS)
6231
+ };
6232
+ if (columns.length > MAX_STRUCTURE_ITEMS) {
6233
+ trimmed.more_columns = columns.length - MAX_STRUCTURE_ITEMS;
6234
+ }
6235
+ return trimmed;
6236
+ });
6237
+ }
6238
+ async function documentStructure(opts) {
6239
+ const ids = [];
6240
+ for (const did of opts.documentIds ?? []) {
6241
+ try {
6242
+ ids.push(parseDocumentId(did));
6243
+ } catch {
6244
+ console.warn("documentStructure: skipping invalid document id %s", did);
6245
+ }
6246
+ }
6247
+ if (!ids.length) return {};
6248
+ const principals = opts.principals ?? null;
6249
+ const bounded = opts.bounded ?? true;
6250
+ const described2 = await spreadsheetSchema({
6251
+ pool: opts.pool,
6252
+ documentIds: ids,
6253
+ sourceIds: opts.sourceIds,
6254
+ principals,
6255
+ budget: opts.budget,
6256
+ redaction: opts.redaction,
6257
+ secretKey: opts.secretKey,
6258
+ hooks: opts.hooks
6259
+ });
6260
+ const tabular = new Map(described2.map((entry) => [entry.document_id, entry]));
6261
+ const params = [];
6262
+ let where = scopeSql(opts.sourceIds ?? null, principals, params, "d");
6263
+ params.push(ids);
6264
+ const clause = `c.document_id = ANY($${params.length}::uuid[])`;
6265
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6266
+ const { rows } = await opts.pool.query(
6267
+ `SELECT c.document_id AS document_id,
6268
+ c.meta_data->>'section_title' AS section,
6269
+ c.meta_data->>'top_level_key' AS key,
6270
+ MIN(c.idx) AS first_idx,
6271
+ COUNT(*) AS chunks,
6272
+ -- Only the page-marker pass writes the page number, and it writes an int
6273
+ -- \u2014 but a cast that meets anything else raises for the whole
6274
+ -- query, so the type is checked in SQL rather than assumed.
6275
+ MAX(CASE WHEN jsonb_typeof(c.meta_data->'page') = 'number'
6276
+ THEN (c.meta_data->>'page')::int END) AS page
6277
+ FROM context_engine_chunks c
6278
+ JOIN context_engine_documents d ON d.id = c.document_id
6279
+ ${where}
6280
+ GROUP BY c.document_id, section, key`,
6281
+ params
6282
+ );
6283
+ const outline = /* @__PURE__ */ new Map();
6284
+ for (const row of rows) {
6285
+ const id = String(row.document_id);
6286
+ let found = outline.get(id);
6287
+ if (!found) {
6288
+ found = { chunks: 0, page: null, parts: [] };
6289
+ outline.set(id, found);
6290
+ }
6291
+ found.chunks += Number(row.chunks ?? 0);
6292
+ if (row.page != null) found.page = Math.max(found.page ?? 0, Number(row.page));
6293
+ found.parts.push([Number(row.first_idx ?? 0), row.section ?? null, row.key ?? null]);
6294
+ }
6295
+ const ordered = (parts, pick, cap) => {
6296
+ const seen = [];
6297
+ for (const part of [...parts].sort((a, b) => a[0] - b[0])) {
6298
+ const value = pick(part);
6299
+ if (value && !seen.includes(value)) seen.push(value);
6300
+ }
6301
+ return [cap === null ? seen : seen.slice(0, cap), seen.length];
6302
+ };
6303
+ const out = {};
6304
+ for (const id of ids) {
6305
+ const found = outline.get(id);
6306
+ const structure = { chunks: found ? found.chunks : 0 };
6307
+ const sheetDoc = tabular.get(id);
6308
+ if (sheetDoc) {
6309
+ const sheets = sheetDoc.sheets ?? null;
6310
+ structure.sheets = bounded ? boundedSheets(sheets) : sheets;
6311
+ if (bounded && sheets && sheets.length > MAX_STRUCTURE_ITEMS) {
6312
+ structure.more_sheets = sheets.length - MAX_STRUCTURE_ITEMS;
6313
+ }
6314
+ if (sheetDoc.schema_unavailable) structure.schema_unavailable = sheetDoc.schema_unavailable;
6315
+ out[id] = structure;
6316
+ continue;
6317
+ }
6318
+ if (found) {
6319
+ if (found.page != null) {
6320
+ structure.last_page = found.page;
6321
+ }
6322
+ const cap = bounded ? MAX_STRUCTURE_ITEMS : null;
6323
+ const [sections, totalSections] = ordered(found.parts, (p) => p[1], cap);
6324
+ if (sections.length) {
6325
+ structure.sections = sections;
6326
+ if (totalSections > sections.length) structure.more_sections = totalSections - sections.length;
6327
+ }
6328
+ const [keys, totalKeys] = ordered(found.parts, (p) => p[2], cap);
6329
+ if (keys.length) {
6330
+ structure.keys = keys;
6331
+ if (totalKeys > keys.length) structure.more_keys = totalKeys - keys.length;
6332
+ }
6333
+ }
6334
+ out[id] = structure;
6335
+ }
6336
+ for (const [id, structure] of Object.entries(out)) {
6337
+ const left = remainder(structure);
6338
+ if (!left) continue;
6339
+ if (left <= MAX_INVITED_ITEMS) {
6340
+ structure.next_action = { action: "discover", document_ids: [id] };
6341
+ } else if ("sheets" in structure) {
6342
+ structure.instead = "too many to list: a sheet this wide is one to COMPUTE over, not to read. Use action 'compute' and name the columns above, or search for a value to find the one row you want.";
6343
+ } else {
6344
+ structure.instead = "too many to list: read the document with get_chunks, or search it for the part you need.";
6345
+ }
6346
+ }
6347
+ const redactOpts = { principals, secretKey: opts.secretKey ?? null, hooks: opts.hooks };
6348
+ return Object.fromEntries(
6349
+ Object.entries(out).map(([id, structure]) => [
6350
+ id,
6351
+ redactValueRecursive(structure, opts.redaction, redactOpts)
6352
+ ])
6353
+ );
6354
+ }
6355
+ async function documentTypes(opts) {
6356
+ const principals = opts.principals ?? null;
6357
+ const params = [];
6358
+ let where = scopeSql(opts.sourceIds ?? null, principals, params);
6359
+ if (opts.documentIds != null) {
6360
+ const parsedIds = [];
6361
+ for (const did of opts.documentIds) {
6362
+ try {
6363
+ parsedIds.push(parseDocumentId(did));
6364
+ } catch {
6365
+ console.warn("documentTypes: skipping invalid document id %s", did);
6366
+ }
6367
+ }
6368
+ params.push(parsedIds);
6369
+ const clause = `id = ANY($${params.length}::uuid[])`;
6370
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6371
+ }
6372
+ params.push(MAX_CENSUS_ROWS);
6373
+ const { rows } = await opts.pool.query(
6374
+ `SELECT document_type AS doc_type,
6375
+ mime_type,
6376
+ COUNT(*) AS documents,
6377
+ COUNT(*) FILTER (
6378
+ WHERE structured_data IS NOT NULL AND structured_data::text <> '{}'
6379
+ ) AS with_fields
6380
+ FROM context_engine_documents
6381
+ ${where}
6382
+ GROUP BY document_type, mime_type
6383
+ ORDER BY COUNT(*) DESC
6384
+ LIMIT $${params.length}`,
6385
+ params
6386
+ );
6387
+ const buckets = /* @__PURE__ */ new Map();
6388
+ for (const row of rows) {
6389
+ const kind = isTabularMime(row.mime_type) ? "spreadsheet" : "text";
6390
+ const type = row.doc_type ?? null;
6391
+ const bucketKey = `${kind}\0${type ?? ""}`;
6392
+ let bucket = buckets.get(bucketKey);
6393
+ if (!bucket) {
6394
+ bucket = { kind, type, documents: 0, with_fields: 0 };
6395
+ buckets.set(bucketKey, bucket);
6396
+ }
6397
+ bucket.documents += Number(row.documents ?? 0);
6398
+ bucket.with_fields += Number(row.with_fields ?? 0);
6399
+ }
6400
+ const census = [...buckets.values()].sort(
6401
+ (a, b) => b.documents - a.documents || a.kind.localeCompare(b.kind) || (a.type ?? "").localeCompare(b.type ?? "")
6402
+ ).slice(0, opts.limit ?? MAX_DOCUMENT_TYPES);
6403
+ return redactValueRecursive(census, opts.redaction, {
6404
+ principals,
6405
+ secretKey: opts.secretKey ?? null,
6406
+ hooks: opts.hooks
6407
+ });
6408
+ }
6409
+ async function fieldSummary(opts) {
6410
+ const principals = opts.principals ?? null;
6411
+ const maxFieldsPerType = opts.maxFieldsPerType ?? MAX_FIELDS_PER_TYPE;
6412
+ const params = [];
6413
+ let where = scopeSql(opts.sourceIds ?? null, principals, params);
6414
+ if (opts.documentIds != null) {
6415
+ const parsedIds = [];
6416
+ for (const did of opts.documentIds) {
6417
+ try {
6418
+ parsedIds.push(parseDocumentId(did));
6419
+ } catch {
6420
+ console.warn("fieldSummary: skipping invalid document id %s", did);
6421
+ }
6422
+ }
6423
+ params.push(parsedIds);
6424
+ const clause = `id = ANY($${params.length}::uuid[])`;
6425
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6426
+ }
6427
+ const typed = "jsonb_typeof(structured_data) = 'object'";
6428
+ where = where ? `${where} AND ${typed}` : `WHERE ${typed}`;
6429
+ params.push(MAX_FIELD_ROWS);
6430
+ const { rows } = await opts.pool.query(
6431
+ `SELECT d.document_type AS doc_type,
6432
+ d.mime_type AS mime_type,
6433
+ kv.key AS key,
6434
+ COUNT(*) AS documents,
6435
+ MAX(kv.value::text) AS sample
6436
+ FROM context_engine_documents d
6437
+ JOIN LATERAL jsonb_each(d.structured_data) AS kv(key, value) ON TRUE
6438
+ ${where}
6439
+ GROUP BY d.document_type, d.mime_type, kv.key
6440
+ ORDER BY d.document_type, COUNT(*) DESC, kv.key
6441
+ LIMIT $${params.length}`,
6442
+ params
6443
+ );
6444
+ const groups = /* @__PURE__ */ new Map();
6445
+ for (const row of rows) {
6446
+ const kind = isTabularMime(row.mime_type) ? "spreadsheet" : "text";
6447
+ const type = row.doc_type ?? null;
6448
+ const groupKey = `${kind}\0${type ?? ""}`;
6449
+ let group = groups.get(groupKey);
6450
+ if (!group) {
6451
+ group = { kind, type, fields: [] };
6452
+ groups.set(groupKey, group);
6453
+ }
6454
+ let sample = null;
6455
+ try {
6456
+ sample = row.sample == null ? null : JSON.parse(String(row.sample));
6457
+ } catch {
6458
+ sample = row.sample;
6459
+ }
6460
+ if (group.fields.length < maxFieldsPerType) {
6461
+ group.fields.push({
6462
+ field: String(row.key),
6463
+ type: inferDataType(String(row.key), sample),
6464
+ documents: Number(row.documents)
6465
+ });
6466
+ } else {
6467
+ group.more_fields ??= [];
6468
+ group.more_fields.push(String(row.key));
6469
+ }
6470
+ }
6471
+ return redactValueRecursive([...groups.values()], opts.redaction, {
6472
+ principals,
6473
+ secretKey: opts.secretKey ?? null,
6474
+ hooks: opts.hooks
6475
+ });
6476
+ }
6119
6477
  function candidateFieldTokens(question) {
6120
6478
  const candidates = [];
6121
6479
  const seen = /* @__PURE__ */ new Set();
@@ -6196,8 +6554,7 @@ async function requireDanfo() {
6196
6554
  throw new exports.ExtraMissingError("compute", "danfojs-node", "compute() dataframes");
6197
6555
  }
6198
6556
  }
6199
- function parseSpreadsheetText(dfd, text) {
6200
- if (!text) return {};
6557
+ function splitSheets(text) {
6201
6558
  const sheets = {};
6202
6559
  let current = "sheet1";
6203
6560
  for (const line of text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n")) {
@@ -6214,6 +6571,34 @@ function parseSpreadsheetText(dfd, text) {
6214
6571
  }
6215
6572
  bucket.push(line);
6216
6573
  }
6574
+ return sheets;
6575
+ }
6576
+ function spreadsheetSchemaFromText(text) {
6577
+ if (!text) return [];
6578
+ const out = [];
6579
+ for (const [name, lines] of Object.entries(splitSheets(text))) {
6580
+ const body = lines.join("\n").trim();
6581
+ if (!body) continue;
6582
+ let rows;
6583
+ try {
6584
+ rows = parseCsv(body);
6585
+ } catch (exc) {
6586
+ console.warn("discover: sheet '%s' not parseable as CSV: %s", name, exc);
6587
+ continue;
6588
+ }
6589
+ rows = rows.filter((row) => row.some((cell) => (cell ?? "").trim()));
6590
+ if (!rows.length) continue;
6591
+ out.push({
6592
+ name,
6593
+ columns: rows[0].map((cell) => String(cell).trim()),
6594
+ row_count: rows.length - 1
6595
+ });
6596
+ }
6597
+ return out;
6598
+ }
6599
+ function parseSpreadsheetText(dfd, text) {
6600
+ if (!text) return {};
6601
+ const sheets = splitSheets(text);
6217
6602
  const out = {};
6218
6603
  for (const [name, lines] of Object.entries(sheets)) {
6219
6604
  const body = lines.join("\n").trim();
@@ -6426,7 +6811,7 @@ ${schemaLines.join("\n")}`;
6426
6811
  hooks
6427
6812
  });
6428
6813
  }
6429
- var MAX_LIST_LIMIT, MAX_COMPUTE_TEXT_CHARS, DEFAULT_COMPUTE_TIMEOUT, MAX_COMPUTE_DOCUMENTS, TABULAR_MIME_PATTERNS, UUID_RE2, WORD_RE, STOPWORDS, SHEET_MARKER_RE2, CODE_FENCE_RE, COMPUTE_SYSTEM_PROMPT, visible, MAX_CHUNKS_PER_READ, MAX_MAP_REDUCE_DOCS, DEFAULT_MAP_REDUCE_DOCS, MAX_MAP_REDUCE_CONCURRENCY;
6814
+ var MAX_LIST_LIMIT, MAX_COMPUTE_TEXT_CHARS, DEFAULT_COMPUTE_TIMEOUT, MAX_COMPUTE_DOCUMENTS, MAX_SCHEMA_TEXT_CHARS, MAX_FIELDS_PER_TYPE, MAX_FIELD_ROWS, MAX_STRUCTURE_ITEMS, MAX_INVITED_ITEMS, MAX_DOCUMENT_TYPES, MAX_CENSUS_ROWS, TABULAR_MIME_PATTERNS, UUID_RE2, WORD_RE, STOPWORDS, SHEET_MARKER_RE2, CODE_FENCE_RE, COMPUTE_SYSTEM_PROMPT, visible, MAX_CHUNKS_PER_READ, MAX_MAP_REDUCE_DOCS, DEFAULT_MAP_REDUCE_DOCS, MAX_MAP_REDUCE_CONCURRENCY;
6430
6815
  var init_actions = __esm({
6431
6816
  "src/actions.ts"() {
6432
6817
  init_chunkers();
@@ -6442,6 +6827,13 @@ var init_actions = __esm({
6442
6827
  MAX_COMPUTE_TEXT_CHARS = 2e6;
6443
6828
  DEFAULT_COMPUTE_TIMEOUT = 30;
6444
6829
  MAX_COMPUTE_DOCUMENTS = 50;
6830
+ MAX_SCHEMA_TEXT_CHARS = MAX_COMPUTE_TEXT_CHARS;
6831
+ MAX_FIELDS_PER_TYPE = 40;
6832
+ MAX_FIELD_ROWS = 2e3;
6833
+ MAX_STRUCTURE_ITEMS = 40;
6834
+ MAX_INVITED_ITEMS = 400;
6835
+ MAX_DOCUMENT_TYPES = 30;
6836
+ MAX_CENSUS_ROWS = 500;
6445
6837
  TABULAR_MIME_PATTERNS = ["%csv%", "%sheet%", "%excel%", "%spreadsheetml%", "%tab-separated%"];
6446
6838
  UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6447
6839
  WORD_RE = /[^\W\d_]+/gu;
@@ -8275,11 +8667,16 @@ function parseCursor2(cursor) {
8275
8667
  }
8276
8668
  return parsed;
8277
8669
  }
8278
- async function listPage(engine, sourceIds, principals, action, limit, cursor, ceiling, redaction) {
8670
+ async function listPage(engine, sourceIds, principals, action, limit, cursor, documentIds, ceiling, redaction) {
8279
8671
  const page = await engine.listDocuments({
8280
8672
  // `!= null`, NOT truthiness: an EMPTY array means "nothing is in scope"
8281
8673
  // and collapsing it to null would list the whole corpus.
8282
8674
  sourceIds: sourceIds != null ? [...new Set(sourceIds)] : null,
8675
+ // Already intersected with the host's ceiling by `narrowToCeiling`, and
8676
+ // filtered in SQL rather than after the page is built — three named
8677
+ // documents sitting on page four must come back as themselves, not as an
8678
+ // empty page.
8679
+ documentIds: documentIds != null ? [...new Set(documentIds)] : null,
8283
8680
  principals,
8284
8681
  cursor,
8285
8682
  limit: Math.max(1, Math.min(limit, MAX_LIST_LIMIT)),
@@ -8289,7 +8686,9 @@ async function listPage(engine, sourceIds, principals, action, limit, cursor, ce
8289
8686
  id: String(raw.id),
8290
8687
  name: raw.name,
8291
8688
  source_id: raw.sourceId ?? raw.source_id,
8292
- kind: documentKind(raw)
8689
+ kind: documentKind(raw),
8690
+ document_type: raw.documentType ?? raw.document_type ?? null,
8691
+ mode: raw.mode ?? null
8293
8692
  }));
8294
8693
  if (ceiling.documentIds != null) {
8295
8694
  const allowed = new Set(ceiling.documentIds);
@@ -8342,30 +8741,62 @@ async function callKnowledgeTool(engine, args) {
8342
8741
  action,
8343
8742
  args.limit ?? 50,
8344
8743
  parseCursor2(args.cursor),
8744
+ documentIds,
8345
8745
  ceiling,
8346
8746
  args.redaction
8347
8747
  );
8348
8748
  if (action === "list") return { success: true, ...page };
8349
- const spreadsheets = page.documents.filter((d) => d.kind === "spreadsheet").map((d) => d.name);
8749
+ const structures = await engine.documentStructure({
8750
+ documentIds: page.documents.map((d) => d.id),
8751
+ sourceIds,
8752
+ principals,
8753
+ // The cap is for the call that did NOT name its documents. A caller
8754
+ // that asked about specific documents asked for all of them, and the
8755
+ // truncated payload tells it to make exactly this call — so answering
8756
+ // it truncated again would be a loop.
8757
+ bounded: !requestedDocumentIds?.length,
8758
+ redaction: args.redaction
8759
+ });
8760
+ for (const doc of page.documents) doc.structure = structures[doc.id] ?? {};
8761
+ const hasSpreadsheet = page.documents.some((d) => d.kind === "spreadsheet");
8762
+ const fieldsByType = await engine.fieldSummary({
8763
+ sourceIds,
8764
+ documentIds,
8765
+ principals,
8766
+ redaction: args.redaction
8767
+ });
8768
+ const census = await engine.documentTypes({
8769
+ sourceIds,
8770
+ documentIds,
8771
+ principals,
8772
+ redaction: args.redaction
8773
+ });
8350
8774
  const forAFact = { action: "search", query: "<bare identifier or key words>" };
8351
8775
  const nextAction = {};
8352
- if (spreadsheets.length && available.compute) {
8776
+ if (hasSpreadsheet && available.compute) {
8353
8777
  nextAction["for a figure from a spreadsheet"] = {
8354
8778
  action: "compute",
8355
- query: "<what to compute, columns as named>"
8779
+ query: "<what to compute, columns as named above>"
8356
8780
  };
8357
8781
  }
8358
8782
  nextAction["for a clause or a fact"] = forAFact;
8783
+ if (fieldsByType.length && available.query_meta) {
8784
+ nextAction["for documents by a field value"] = {
8785
+ action: "query_meta",
8786
+ query: "<a question naming a field from fields_by_type>"
8787
+ };
8788
+ }
8359
8789
  if (available.get_neighbors) {
8360
8790
  nextAction["for how things connect"] = {
8361
8791
  action: "get_neighbors",
8362
8792
  entity: "<a name that appears in the documents>"
8363
8793
  };
8364
8794
  }
8365
- return {
8795
+ const discovered = {
8366
8796
  success: true,
8367
8797
  ...page,
8368
- spreadsheets,
8798
+ document_types: census,
8799
+ fields_by_type: fieldsByType,
8369
8800
  available_actions: Object.fromEntries(
8370
8801
  Object.keys(ACTION_HELP).map((name) => [
8371
8802
  name,
@@ -8374,6 +8805,7 @@ async function callKnowledgeTool(engine, args) {
8374
8805
  ),
8375
8806
  next_action: nextAction
8376
8807
  };
8808
+ return discovered;
8377
8809
  }
8378
8810
  if (action === "search") {
8379
8811
  if (!text) return { success: false, error: "search needs a query" };
@@ -8603,7 +9035,7 @@ var init_knowledge_tool = __esm({
8603
9035
  "get_neighbors",
8604
9036
  "community_summary"
8605
9037
  ];
8606
- exports.KNOWLEDGE_TOOL_DESCRIPTION = "The knowledge base \u2014 the ingested documents and data files (PDF, Word, Excel, CSV and the rest) \u2014 as ONE tool with actions. Nothing is searched for you: use it before answering anything that should come from those documents, and do not use it for general knowledge. Call action 'discover' FIRST when you do not already know what is there: it lists the documents, says which are spreadsheets, and says which actions this deployment can run. Then match the action to the task. 'search' finds passages by meaning or keywords \u2014 for questions answered by reading text. Looking up an identifier (an ID, code, SKU or invoice number) is the exception: search the BARE identifier alone, e.g. '2525', never the whole question. Those are CONTENT identifiers \u2014 written inside a document \u2014 and they belong in a query; a document_id is a system id (a uuid) that only discover, list or a search hit can give you, so never search a uuid as text and never hand an invoice number to get_doc. 'get_doc' reads one whole document by id, 'get_docs' reads several at once, and 'get_chunks' walks one long document in order a piece at a time when you need more of it than an excerpt; 'list' browses the documents without searching. 'map_reduce' asks the SAME question of every document in scope and answers once per document \u2014 for 'which contracts mention X', where search would return a handful of passages and miss the rest. 'query_meta' filters and aggregates documents by their structured fields (dates, amounts, categories) \u2014 usually the right action for a question about spreadsheet data. 'compute' runs code over the spreadsheets for any figure DERIVED from them \u2014 a total, average, count, ranking, margin or comparison across rows \u2014 AND for finding the exact row matching one id or value. In a large table, search cannot reliably locate an individual row; compute can. When the question is about how things are CONNECTED rather than what a document says \u2014 who works with whom, what belongs to what, what a change touches \u2014 use the graph actions: 'get_neighbors' for what is one step from one thing, 'traverse' for everything within a few steps of it, 'find_related' for connections of a kind across the corpus, and 'community_summary' for the themes the corpus groups into. They are available only where a graph was built; discover says so. Searching with mode='graph' ranks passages by those same connections instead of by wording alone, which finds a passage that never repeats your words. Rules that decide answers: search returns EXCERPTS, and rows of a spreadsheet are not arithmetic \u2014 never add up, average or rank rows yourself from what search returned, and never say a figure is not available before computing over the sheet that holds it. A listing that says has_more has MORE: send its next_cursor back as 'cursor' for the next page, and never conclude a document is absent from a first page that was truncated. Search again with different words before saying a document is missing. A result may carry a next_action (or next_page): it is the call to make next, already filled in \u2014 follow it rather than guessing the next step. Cite document names.";
9038
+ exports.KNOWLEDGE_TOOL_DESCRIPTION = "The knowledge base \u2014 the ingested documents and data files (PDF, Word, Excel, CSV and the rest) \u2014 as ONE tool with actions. Nothing is searched for you: use it before answering anything that should come from those documents, and do not use it for general knowledge. Call action 'discover' FIRST when you do not already know what is there: it lists the documents and says what is INSIDE each one \u2014 a spreadsheet's sheet names, column headers and row counts; a document's section titles and last page; a JSON file's top-level keys \u2014 plus the extracted field names grouped by document type with each field's data type and how many documents carry it, a census of the whole corpus, and which actions this deployment can run. Use those names verbatim: they are what compute, query_meta and get_chunks match on, so one discover is enough and you never have to go looking for a column, a section or a field name. A long list is shortened there, with the rest reported as a count and, when it is worth the trip, the exact call that returns it in full \u2014 discover again with document_ids set to that one document, which answers whole. When it is not worth the trip the payload says so and says what to do instead: a sheet with hundreds of columns is one to compute over, never one to read back. Then match the action to the task. 'search' finds passages by meaning or keywords \u2014 for questions answered by reading text. Looking up an identifier (an ID, code, SKU or invoice number) is the exception: search the BARE identifier alone, e.g. '2525', never the whole question. Those are CONTENT identifiers \u2014 written inside a document \u2014 and they belong in a query; a document_id is a system id (a uuid) that only discover, list or a search hit can give you, so never search a uuid as text and never hand an invoice number to get_doc. 'get_doc' reads one whole document by id, 'get_docs' reads several at once, and 'get_chunks' walks one long document in order a piece at a time when you need more of it than an excerpt; 'list' browses the documents without searching. 'map_reduce' asks the SAME question of every document in scope and answers once per document \u2014 for 'which contracts mention X', where search would return a handful of passages and miss the rest. 'query_meta' filters and aggregates documents by their structured fields (dates, amounts, categories) \u2014 usually the right action for a question about spreadsheet data. 'compute' runs code over the spreadsheets for any figure DERIVED from them \u2014 a total, average, count, ranking, margin or comparison across rows \u2014 AND for finding the exact row matching one id or value. In a large table, search cannot reliably locate an individual row; compute can. When the question is about how things are CONNECTED rather than what a document says \u2014 who works with whom, what belongs to what, what a change touches \u2014 use the graph actions: 'get_neighbors' for what is one step from one thing, 'traverse' for everything within a few steps of it, 'find_related' for connections of a kind across the corpus, and 'community_summary' for the themes the corpus groups into. They are available only where a graph was built; discover says so. Searching with mode='graph' ranks passages by those same connections instead of by wording alone, which finds a passage that never repeats your words. Rules that decide answers: search returns EXCERPTS, and rows of a spreadsheet are not arithmetic \u2014 never add up, average or rank rows yourself from what search returned, and never say a figure is not available before computing over the sheet that holds it. A listing that says has_more has MORE: send its next_cursor back as 'cursor' for the next page, and never conclude a document is absent from a first page that was truncated. Search again with different words before saying a document is missing. A result may carry a next_action (or next_page): it is the call to make next, already filled in \u2014 follow it rather than guessing the next step. Cite document names.";
8607
9039
  ACTION_PARAM_DESCRIPTION = "Match it to the task: reading questions -> search (a bare identifier for an ID or code); spreadsheet analysis, or the exact row for one id or value -> query_meta or compute; how things connect -> get_neighbors, traverse, find_related or community_summary; browse everything -> list; unsure what exists -> discover first.";
8608
9040
  ACTION_HELP = {
8609
9041
  search: "passages by meaning or keywords; an ID, code or number as the BARE identifier",
@@ -8626,7 +9058,7 @@ var init_knowledge_tool = __esm({
8626
9058
  graph: "the graph actions are off: this deployment has no graph configured, so nothing has been linked up. Use search, get_doc or list instead."
8627
9059
  };
8628
9060
  GRAPH_ACTIONS = ["traverse", "find_related", "get_neighbors", "community_summary"];
8629
- DOCUMENT_ID_ACTIONS = ["search", "compute", "get_docs", "map_reduce"];
9061
+ DOCUMENT_ID_ACTIONS = ["search", "compute", "get_docs", "map_reduce", "discover", "list"];
8630
9062
  DEFAULT_GET_DOCS_CHARS = 2e5;
8631
9063
  INPUT_PROPERTIES = {
8632
9064
  action: { type: "string", enum: [...exports.KNOWLEDGE_ACTIONS], description: ACTION_PARAM_DESCRIPTION },
@@ -8646,7 +9078,7 @@ var init_knowledge_tool = __esm({
8646
9078
  document_ids: {
8647
9079
  type: "array",
8648
9080
  items: { type: "string" },
8649
- description: "Narrows to these documents, using ids from discover, list or a search hit. It INTERSECTS with source_ids, so a document outside the sources you named returns nothing. (for search, compute)"
9081
+ description: "Narrows to these documents, using ids from discover, list or a search hit. It INTERSECTS with source_ids, so a document outside the sources you named returns nothing. On discover it also asks for those documents' structure IN FULL, past the shortening a whole-page discover applies. (for search, compute, get_docs, map_reduce, discover, list)"
8650
9082
  },
8651
9083
  entity: {
8652
9084
  type: "string",
@@ -13679,6 +14111,7 @@ var ContextEngine = class _ContextEngine {
13679
14111
  pool,
13680
14112
  sourceId: opts.sourceId,
13681
14113
  sourceIds: opts.sourceIds,
14114
+ documentIds: opts.documentIds,
13682
14115
  principals: resolvePrincipals(opts.principals, "listDocuments"),
13683
14116
  cursor: opts.cursor,
13684
14117
  limit: opts.limit,
@@ -13687,6 +14120,84 @@ var ContextEngine = class _ContextEngine {
13687
14120
  hooks: this.hooks
13688
14121
  });
13689
14122
  }
14123
+ /**
14124
+ * Sheet names, columns and row counts for the named spreadsheets.
14125
+ *
14126
+ * See `actions.spreadsheetSchema`. This is the half of `discover` that lets
14127
+ * a model write ONE `compute` call: sheet names here are the keys it will
14128
+ * index `dfs` by, and columns are the names it will use inside the code it
14129
+ * writes.
14130
+ */
14131
+ async spreadsheetSchema(opts) {
14132
+ const pool = await this.ensurePool();
14133
+ return spreadsheetSchema({
14134
+ pool,
14135
+ documentIds: opts.documentIds,
14136
+ sourceIds: opts.sourceIds,
14137
+ principals: resolvePrincipals(opts.principals, "spreadsheetSchema"),
14138
+ redaction: opts.redaction ?? this.config.redaction,
14139
+ secretKey: this.config.secretKey,
14140
+ hooks: this.hooks
14141
+ });
14142
+ }
14143
+ /**
14144
+ * What is inside each of the named documents, whatever its type.
14145
+ *
14146
+ * See `actions.documentStructure`. Sheets and columns for a workbook,
14147
+ * sections and the last page for a document with headings, top-level keys
14148
+ * for JSON, and a chunk count for everything — so `discover` describes the
14149
+ * whole corpus rather than only the spreadsheets in it.
14150
+ */
14151
+ async documentStructure(opts) {
14152
+ const pool = await this.ensurePool();
14153
+ return documentStructure({
14154
+ pool,
14155
+ documentIds: opts.documentIds,
14156
+ sourceIds: opts.sourceIds,
14157
+ bounded: opts.bounded,
14158
+ principals: resolvePrincipals(opts.principals, "documentStructure"),
14159
+ redaction: opts.redaction ?? this.config.redaction,
14160
+ secretKey: this.config.secretKey,
14161
+ hooks: this.hooks
14162
+ });
14163
+ }
14164
+ /**
14165
+ * The corpus census — `[{kind, type, documents, with_fields}]`.
14166
+ *
14167
+ * See `actions.documentTypes`. `kind` comes from the mime and is always
14168
+ * known; `type` is the LLM-written document type and exists only where
14169
+ * structured extraction was opted into.
14170
+ */
14171
+ async documentTypes(opts = {}) {
14172
+ const pool = await this.ensurePool();
14173
+ return documentTypes({
14174
+ pool,
14175
+ sourceIds: opts.sourceIds,
14176
+ documentIds: opts.documentIds,
14177
+ principals: resolvePrincipals(opts.principals, "documentTypes"),
14178
+ redaction: opts.redaction ?? this.config.redaction,
14179
+ secretKey: this.config.secretKey,
14180
+ hooks: this.hooks
14181
+ });
14182
+ }
14183
+ /**
14184
+ * Extracted structured field names grouped by document kind and type.
14185
+ *
14186
+ * See `actions.fieldSummary`. One row per group, keyed by the same
14187
+ * `(kind, type)` pair `documentTypes` uses.
14188
+ */
14189
+ async fieldSummary(opts = {}) {
14190
+ const pool = await this.ensurePool();
14191
+ return fieldSummary({
14192
+ pool,
14193
+ sourceIds: opts.sourceIds,
14194
+ documentIds: opts.documentIds,
14195
+ principals: resolvePrincipals(opts.principals, "fieldSummary"),
14196
+ redaction: opts.redaction ?? this.config.redaction,
14197
+ secretKey: this.config.secretKey,
14198
+ hooks: this.hooks
14199
+ });
14200
+ }
13690
14201
  async queryStructured(question, opts = {}) {
13691
14202
  const pool = await this.ensurePool();
13692
14203
  return queryStructured(question, {
@@ -14071,6 +14582,8 @@ exports.computeOverFrames = computeOverFrames;
14071
14582
  exports.configSchema = configSchema;
14072
14583
  exports.createMcpApp = createMcpApp;
14073
14584
  exports.decryptDict = decryptDict;
14585
+ exports.documentStructure = documentStructure;
14586
+ exports.documentTypes = documentTypes;
14074
14587
  exports.emitError = emitError;
14075
14588
  exports.emitProgress = emitProgress;
14076
14589
  exports.emitToolCall = emitToolCall;
@@ -14078,6 +14591,7 @@ exports.emitUsage = emitUsage;
14078
14591
  exports.encryptDict = encryptDict;
14079
14592
  exports.extract = extract2;
14080
14593
  exports.extractStructuredData = extractStructuredData;
14594
+ exports.fieldSummary = fieldSummary;
14081
14595
  exports.functionTool = functionTool;
14082
14596
  exports.getDocumentText = getDocumentText;
14083
14597
  exports.getSecretKey = getSecretKey;
@@ -14096,6 +14610,8 @@ exports.rrfFuse = rrfFuse;
14096
14610
  exports.runMigrate = runMigrate;
14097
14611
  exports.runSearch = runSearch;
14098
14612
  exports.shouldRequireApproval = shouldRequireApproval;
14613
+ exports.spreadsheetSchema = spreadsheetSchema;
14614
+ exports.spreadsheetSchemaFromText = spreadsheetSchemaFromText;
14099
14615
  exports.unitsForFile = unitsForFile;
14100
14616
  exports.upsertRegistry = upsertRegistry;
14101
14617
  //# sourceMappingURL=index.cjs.map