@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.js CHANGED
@@ -5779,15 +5779,16 @@ function parseDocumentId(documentId) {
5779
5779
  }
5780
5780
  return raw;
5781
5781
  }
5782
- function scopeSql(sourceIds, principals, params) {
5782
+ function scopeSql(sourceIds, principals, params, alias = "") {
5783
+ const col = alias ? `${alias}.` : "";
5783
5784
  const where = [];
5784
5785
  if (sourceIds != null) {
5785
5786
  params.push(sourceIds);
5786
- where.push(`source_id = ANY($${params.length}::text[])`);
5787
+ where.push(`${col}source_id = ANY($${params.length}::text[])`);
5787
5788
  }
5788
5789
  if (principals != null) {
5789
5790
  params.push(principals);
5790
- where.push(`(acl IS NULL OR acl && $${params.length}::text[])`);
5791
+ where.push(`(${col}acl IS NULL OR ${col}acl && $${params.length}::text[])`);
5791
5792
  }
5792
5793
  return where.length ? `WHERE ${where.join(" AND ")}` : "";
5793
5794
  }
@@ -6046,6 +6047,19 @@ async function listDocuments(opts) {
6046
6047
  const principals = opts.principals ?? null;
6047
6048
  const params = [];
6048
6049
  let where = scopeSql(sourceIds, principals, params);
6050
+ if (opts.documentIds != null) {
6051
+ const parsedIds = [];
6052
+ for (const did of opts.documentIds) {
6053
+ try {
6054
+ parsedIds.push(parseDocumentId(did));
6055
+ } catch {
6056
+ console.warn("listDocuments: skipping invalid document id %s", did);
6057
+ }
6058
+ }
6059
+ params.push(parsedIds);
6060
+ const clause = `id = ANY($${params.length}::uuid[])`;
6061
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6062
+ }
6049
6063
  const cursorTime = parsedCursor?.time ?? parsedCursor?.created_at;
6050
6064
  const cursorId = parsedCursor?.id;
6051
6065
  if (cursorTime && cursorId && UUID_RE2.test(String(cursorId))) {
@@ -6105,6 +6119,350 @@ async function listDocuments(opts) {
6105
6119
  }
6106
6120
  return result;
6107
6121
  }
6122
+ async function spreadsheetSchema(opts) {
6123
+ const ids = [];
6124
+ for (const did of opts.documentIds ?? []) {
6125
+ try {
6126
+ ids.push(parseDocumentId(did));
6127
+ } catch {
6128
+ console.warn("spreadsheetSchema: skipping invalid document id %s", did);
6129
+ }
6130
+ }
6131
+ if (!ids.length) return [];
6132
+ const principals = opts.principals ?? null;
6133
+ const budget = opts.budget ?? MAX_SCHEMA_TEXT_CHARS;
6134
+ const params = [];
6135
+ let where = scopeSql(opts.sourceIds ?? null, principals, params);
6136
+ const mimeClause = TABULAR_MIME_PATTERNS.map((pattern) => {
6137
+ params.push(pattern);
6138
+ return `mime_type ILIKE $${params.length}`;
6139
+ }).join(" OR ");
6140
+ where = where ? `${where} AND (${mimeClause})` : `WHERE (${mimeClause})`;
6141
+ params.push(ids);
6142
+ where += ` AND id = ANY($${params.length}::uuid[])`;
6143
+ const sized = await opts.pool.query(
6144
+ `SELECT id, name, source_id, mime_type, COALESCE(LENGTH(text), 0) AS text_len
6145
+ FROM context_engine_documents
6146
+ ${where}`,
6147
+ params
6148
+ );
6149
+ const byId = /* @__PURE__ */ new Map();
6150
+ for (const row of sized.rows) {
6151
+ if (isTabularMime(row.mime_type)) byId.set(String(row.id), row);
6152
+ }
6153
+ const rows = ids.map((id) => byId.get(id)).filter((r) => r != null);
6154
+ const chosen = [];
6155
+ let spent = 0;
6156
+ for (const row of rows) {
6157
+ const len = Number(row.text_len ?? 0);
6158
+ if (chosen.length && spent + len > budget) break;
6159
+ chosen.push(String(row.id));
6160
+ spent += len;
6161
+ }
6162
+ const texts = /* @__PURE__ */ new Map();
6163
+ if (chosen.length) {
6164
+ const bodyParams = [];
6165
+ const bodyWhere = scopeSql(opts.sourceIds ?? null, principals, bodyParams);
6166
+ bodyParams.push(chosen);
6167
+ const clause = `id = ANY($${bodyParams.length}::uuid[])`;
6168
+ const { rows: bodies } = await opts.pool.query(
6169
+ `SELECT id, text FROM context_engine_documents
6170
+ ${bodyWhere ? `${bodyWhere} AND ${clause}` : `WHERE ${clause}`}`,
6171
+ bodyParams
6172
+ );
6173
+ for (const row of bodies) texts.set(String(row.id), row.text ?? null);
6174
+ }
6175
+ return rows.map((row) => {
6176
+ const id = String(row.id);
6177
+ if (!texts.has(id)) {
6178
+ return {
6179
+ document_id: id,
6180
+ name: row.name,
6181
+ source_id: row.source_id,
6182
+ sheets: null,
6183
+ schema_unavailable: "not read: this page of spreadsheets is past the text budget \u2014 narrow with sourceIds, or ask for a smaller limit"
6184
+ };
6185
+ }
6186
+ return {
6187
+ document_id: id,
6188
+ name: row.name,
6189
+ source_id: row.source_id,
6190
+ sheets: redactValueRecursive(spreadsheetSchemaFromText(texts.get(id)), opts.redaction, {
6191
+ principals,
6192
+ secretKey: opts.secretKey ?? null,
6193
+ hooks: opts.hooks
6194
+ })
6195
+ };
6196
+ });
6197
+ }
6198
+ function remainder(structure) {
6199
+ let total = 0;
6200
+ for (const [key, value] of Object.entries(structure)) {
6201
+ if (key.startsWith("more_") && typeof value === "number") total += value;
6202
+ }
6203
+ const sheets = structure.sheets;
6204
+ if (Array.isArray(sheets)) {
6205
+ for (const sheet of sheets) {
6206
+ if (sheet && typeof sheet === "object" && typeof sheet.more_columns === "number") {
6207
+ total += sheet.more_columns;
6208
+ }
6209
+ }
6210
+ }
6211
+ return total;
6212
+ }
6213
+ function boundedSheets(sheets) {
6214
+ if (!sheets?.length) return sheets;
6215
+ return sheets.slice(0, MAX_STRUCTURE_ITEMS).map((sheet) => {
6216
+ const columns = sheet.columns ?? [];
6217
+ const trimmed = {
6218
+ ...sheet,
6219
+ columns: columns.slice(0, MAX_STRUCTURE_ITEMS)
6220
+ };
6221
+ if (columns.length > MAX_STRUCTURE_ITEMS) {
6222
+ trimmed.more_columns = columns.length - MAX_STRUCTURE_ITEMS;
6223
+ }
6224
+ return trimmed;
6225
+ });
6226
+ }
6227
+ async function documentStructure(opts) {
6228
+ const ids = [];
6229
+ for (const did of opts.documentIds ?? []) {
6230
+ try {
6231
+ ids.push(parseDocumentId(did));
6232
+ } catch {
6233
+ console.warn("documentStructure: skipping invalid document id %s", did);
6234
+ }
6235
+ }
6236
+ if (!ids.length) return {};
6237
+ const principals = opts.principals ?? null;
6238
+ const bounded = opts.bounded ?? true;
6239
+ const described2 = await spreadsheetSchema({
6240
+ pool: opts.pool,
6241
+ documentIds: ids,
6242
+ sourceIds: opts.sourceIds,
6243
+ principals,
6244
+ budget: opts.budget,
6245
+ redaction: opts.redaction,
6246
+ secretKey: opts.secretKey,
6247
+ hooks: opts.hooks
6248
+ });
6249
+ const tabular = new Map(described2.map((entry) => [entry.document_id, entry]));
6250
+ const params = [];
6251
+ let where = scopeSql(opts.sourceIds ?? null, principals, params, "d");
6252
+ params.push(ids);
6253
+ const clause = `c.document_id = ANY($${params.length}::uuid[])`;
6254
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6255
+ const { rows } = await opts.pool.query(
6256
+ `SELECT c.document_id AS document_id,
6257
+ c.meta_data->>'section_title' AS section,
6258
+ c.meta_data->>'top_level_key' AS key,
6259
+ MIN(c.idx) AS first_idx,
6260
+ COUNT(*) AS chunks,
6261
+ -- Only the page-marker pass writes the page number, and it writes an int
6262
+ -- \u2014 but a cast that meets anything else raises for the whole
6263
+ -- query, so the type is checked in SQL rather than assumed.
6264
+ MAX(CASE WHEN jsonb_typeof(c.meta_data->'page') = 'number'
6265
+ THEN (c.meta_data->>'page')::int END) AS page
6266
+ FROM context_engine_chunks c
6267
+ JOIN context_engine_documents d ON d.id = c.document_id
6268
+ ${where}
6269
+ GROUP BY c.document_id, section, key`,
6270
+ params
6271
+ );
6272
+ const outline = /* @__PURE__ */ new Map();
6273
+ for (const row of rows) {
6274
+ const id = String(row.document_id);
6275
+ let found = outline.get(id);
6276
+ if (!found) {
6277
+ found = { chunks: 0, page: null, parts: [] };
6278
+ outline.set(id, found);
6279
+ }
6280
+ found.chunks += Number(row.chunks ?? 0);
6281
+ if (row.page != null) found.page = Math.max(found.page ?? 0, Number(row.page));
6282
+ found.parts.push([Number(row.first_idx ?? 0), row.section ?? null, row.key ?? null]);
6283
+ }
6284
+ const ordered = (parts, pick, cap) => {
6285
+ const seen = [];
6286
+ for (const part of [...parts].sort((a, b) => a[0] - b[0])) {
6287
+ const value = pick(part);
6288
+ if (value && !seen.includes(value)) seen.push(value);
6289
+ }
6290
+ return [cap === null ? seen : seen.slice(0, cap), seen.length];
6291
+ };
6292
+ const out = {};
6293
+ for (const id of ids) {
6294
+ const found = outline.get(id);
6295
+ const structure = { chunks: found ? found.chunks : 0 };
6296
+ const sheetDoc = tabular.get(id);
6297
+ if (sheetDoc) {
6298
+ const sheets = sheetDoc.sheets ?? null;
6299
+ structure.sheets = bounded ? boundedSheets(sheets) : sheets;
6300
+ if (bounded && sheets && sheets.length > MAX_STRUCTURE_ITEMS) {
6301
+ structure.more_sheets = sheets.length - MAX_STRUCTURE_ITEMS;
6302
+ }
6303
+ if (sheetDoc.schema_unavailable) structure.schema_unavailable = sheetDoc.schema_unavailable;
6304
+ out[id] = structure;
6305
+ continue;
6306
+ }
6307
+ if (found) {
6308
+ if (found.page != null) {
6309
+ structure.last_page = found.page;
6310
+ }
6311
+ const cap = bounded ? MAX_STRUCTURE_ITEMS : null;
6312
+ const [sections, totalSections] = ordered(found.parts, (p) => p[1], cap);
6313
+ if (sections.length) {
6314
+ structure.sections = sections;
6315
+ if (totalSections > sections.length) structure.more_sections = totalSections - sections.length;
6316
+ }
6317
+ const [keys, totalKeys] = ordered(found.parts, (p) => p[2], cap);
6318
+ if (keys.length) {
6319
+ structure.keys = keys;
6320
+ if (totalKeys > keys.length) structure.more_keys = totalKeys - keys.length;
6321
+ }
6322
+ }
6323
+ out[id] = structure;
6324
+ }
6325
+ for (const [id, structure] of Object.entries(out)) {
6326
+ const left = remainder(structure);
6327
+ if (!left) continue;
6328
+ if (left <= MAX_INVITED_ITEMS) {
6329
+ structure.next_action = { action: "discover", document_ids: [id] };
6330
+ } else if ("sheets" in structure) {
6331
+ 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.";
6332
+ } else {
6333
+ structure.instead = "too many to list: read the document with get_chunks, or search it for the part you need.";
6334
+ }
6335
+ }
6336
+ const redactOpts = { principals, secretKey: opts.secretKey ?? null, hooks: opts.hooks };
6337
+ return Object.fromEntries(
6338
+ Object.entries(out).map(([id, structure]) => [
6339
+ id,
6340
+ redactValueRecursive(structure, opts.redaction, redactOpts)
6341
+ ])
6342
+ );
6343
+ }
6344
+ async function documentTypes(opts) {
6345
+ const principals = opts.principals ?? null;
6346
+ const params = [];
6347
+ let where = scopeSql(opts.sourceIds ?? null, principals, params);
6348
+ if (opts.documentIds != null) {
6349
+ const parsedIds = [];
6350
+ for (const did of opts.documentIds) {
6351
+ try {
6352
+ parsedIds.push(parseDocumentId(did));
6353
+ } catch {
6354
+ console.warn("documentTypes: skipping invalid document id %s", did);
6355
+ }
6356
+ }
6357
+ params.push(parsedIds);
6358
+ const clause = `id = ANY($${params.length}::uuid[])`;
6359
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6360
+ }
6361
+ params.push(MAX_CENSUS_ROWS);
6362
+ const { rows } = await opts.pool.query(
6363
+ `SELECT document_type AS doc_type,
6364
+ mime_type,
6365
+ COUNT(*) AS documents,
6366
+ COUNT(*) FILTER (
6367
+ WHERE structured_data IS NOT NULL AND structured_data::text <> '{}'
6368
+ ) AS with_fields
6369
+ FROM context_engine_documents
6370
+ ${where}
6371
+ GROUP BY document_type, mime_type
6372
+ ORDER BY COUNT(*) DESC
6373
+ LIMIT $${params.length}`,
6374
+ params
6375
+ );
6376
+ const buckets = /* @__PURE__ */ new Map();
6377
+ for (const row of rows) {
6378
+ const kind = isTabularMime(row.mime_type) ? "spreadsheet" : "text";
6379
+ const type = row.doc_type ?? null;
6380
+ const bucketKey = `${kind}\0${type ?? ""}`;
6381
+ let bucket = buckets.get(bucketKey);
6382
+ if (!bucket) {
6383
+ bucket = { kind, type, documents: 0, with_fields: 0 };
6384
+ buckets.set(bucketKey, bucket);
6385
+ }
6386
+ bucket.documents += Number(row.documents ?? 0);
6387
+ bucket.with_fields += Number(row.with_fields ?? 0);
6388
+ }
6389
+ const census = [...buckets.values()].sort(
6390
+ (a, b) => b.documents - a.documents || a.kind.localeCompare(b.kind) || (a.type ?? "").localeCompare(b.type ?? "")
6391
+ ).slice(0, opts.limit ?? MAX_DOCUMENT_TYPES);
6392
+ return redactValueRecursive(census, opts.redaction, {
6393
+ principals,
6394
+ secretKey: opts.secretKey ?? null,
6395
+ hooks: opts.hooks
6396
+ });
6397
+ }
6398
+ async function fieldSummary(opts) {
6399
+ const principals = opts.principals ?? null;
6400
+ const maxFieldsPerType = opts.maxFieldsPerType ?? MAX_FIELDS_PER_TYPE;
6401
+ const params = [];
6402
+ let where = scopeSql(opts.sourceIds ?? null, principals, params);
6403
+ if (opts.documentIds != null) {
6404
+ const parsedIds = [];
6405
+ for (const did of opts.documentIds) {
6406
+ try {
6407
+ parsedIds.push(parseDocumentId(did));
6408
+ } catch {
6409
+ console.warn("fieldSummary: skipping invalid document id %s", did);
6410
+ }
6411
+ }
6412
+ params.push(parsedIds);
6413
+ const clause = `id = ANY($${params.length}::uuid[])`;
6414
+ where = where ? `${where} AND ${clause}` : `WHERE ${clause}`;
6415
+ }
6416
+ const typed = "jsonb_typeof(structured_data) = 'object'";
6417
+ where = where ? `${where} AND ${typed}` : `WHERE ${typed}`;
6418
+ params.push(MAX_FIELD_ROWS);
6419
+ const { rows } = await opts.pool.query(
6420
+ `SELECT d.document_type AS doc_type,
6421
+ d.mime_type AS mime_type,
6422
+ kv.key AS key,
6423
+ COUNT(*) AS documents,
6424
+ MAX(kv.value::text) AS sample
6425
+ FROM context_engine_documents d
6426
+ JOIN LATERAL jsonb_each(d.structured_data) AS kv(key, value) ON TRUE
6427
+ ${where}
6428
+ GROUP BY d.document_type, d.mime_type, kv.key
6429
+ ORDER BY d.document_type, COUNT(*) DESC, kv.key
6430
+ LIMIT $${params.length}`,
6431
+ params
6432
+ );
6433
+ const groups = /* @__PURE__ */ new Map();
6434
+ for (const row of rows) {
6435
+ const kind = isTabularMime(row.mime_type) ? "spreadsheet" : "text";
6436
+ const type = row.doc_type ?? null;
6437
+ const groupKey = `${kind}\0${type ?? ""}`;
6438
+ let group = groups.get(groupKey);
6439
+ if (!group) {
6440
+ group = { kind, type, fields: [] };
6441
+ groups.set(groupKey, group);
6442
+ }
6443
+ let sample = null;
6444
+ try {
6445
+ sample = row.sample == null ? null : JSON.parse(String(row.sample));
6446
+ } catch {
6447
+ sample = row.sample;
6448
+ }
6449
+ if (group.fields.length < maxFieldsPerType) {
6450
+ group.fields.push({
6451
+ field: String(row.key),
6452
+ type: inferDataType(String(row.key), sample),
6453
+ documents: Number(row.documents)
6454
+ });
6455
+ } else {
6456
+ group.more_fields ??= [];
6457
+ group.more_fields.push(String(row.key));
6458
+ }
6459
+ }
6460
+ return redactValueRecursive([...groups.values()], opts.redaction, {
6461
+ principals,
6462
+ secretKey: opts.secretKey ?? null,
6463
+ hooks: opts.hooks
6464
+ });
6465
+ }
6108
6466
  function candidateFieldTokens(question) {
6109
6467
  const candidates = [];
6110
6468
  const seen = /* @__PURE__ */ new Set();
@@ -6185,8 +6543,7 @@ async function requireDanfo() {
6185
6543
  throw new ExtraMissingError("compute", "danfojs-node", "compute() dataframes");
6186
6544
  }
6187
6545
  }
6188
- function parseSpreadsheetText(dfd, text) {
6189
- if (!text) return {};
6546
+ function splitSheets(text) {
6190
6547
  const sheets = {};
6191
6548
  let current = "sheet1";
6192
6549
  for (const line of text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n")) {
@@ -6203,6 +6560,34 @@ function parseSpreadsheetText(dfd, text) {
6203
6560
  }
6204
6561
  bucket.push(line);
6205
6562
  }
6563
+ return sheets;
6564
+ }
6565
+ function spreadsheetSchemaFromText(text) {
6566
+ if (!text) return [];
6567
+ const out = [];
6568
+ for (const [name, lines] of Object.entries(splitSheets(text))) {
6569
+ const body = lines.join("\n").trim();
6570
+ if (!body) continue;
6571
+ let rows;
6572
+ try {
6573
+ rows = parseCsv(body);
6574
+ } catch (exc) {
6575
+ console.warn("discover: sheet '%s' not parseable as CSV: %s", name, exc);
6576
+ continue;
6577
+ }
6578
+ rows = rows.filter((row) => row.some((cell) => (cell ?? "").trim()));
6579
+ if (!rows.length) continue;
6580
+ out.push({
6581
+ name,
6582
+ columns: rows[0].map((cell) => String(cell).trim()),
6583
+ row_count: rows.length - 1
6584
+ });
6585
+ }
6586
+ return out;
6587
+ }
6588
+ function parseSpreadsheetText(dfd, text) {
6589
+ if (!text) return {};
6590
+ const sheets = splitSheets(text);
6206
6591
  const out = {};
6207
6592
  for (const [name, lines] of Object.entries(sheets)) {
6208
6593
  const body = lines.join("\n").trim();
@@ -6415,7 +6800,7 @@ ${schemaLines.join("\n")}`;
6415
6800
  hooks
6416
6801
  });
6417
6802
  }
6418
- 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;
6803
+ 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;
6419
6804
  var init_actions = __esm({
6420
6805
  "src/actions.ts"() {
6421
6806
  init_chunkers();
@@ -6431,6 +6816,13 @@ var init_actions = __esm({
6431
6816
  MAX_COMPUTE_TEXT_CHARS = 2e6;
6432
6817
  DEFAULT_COMPUTE_TIMEOUT = 30;
6433
6818
  MAX_COMPUTE_DOCUMENTS = 50;
6819
+ MAX_SCHEMA_TEXT_CHARS = MAX_COMPUTE_TEXT_CHARS;
6820
+ MAX_FIELDS_PER_TYPE = 40;
6821
+ MAX_FIELD_ROWS = 2e3;
6822
+ MAX_STRUCTURE_ITEMS = 40;
6823
+ MAX_INVITED_ITEMS = 400;
6824
+ MAX_DOCUMENT_TYPES = 30;
6825
+ MAX_CENSUS_ROWS = 500;
6434
6826
  TABULAR_MIME_PATTERNS = ["%csv%", "%sheet%", "%excel%", "%spreadsheetml%", "%tab-separated%"];
6435
6827
  UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6436
6828
  WORD_RE = /[^\W\d_]+/gu;
@@ -8264,11 +8656,16 @@ function parseCursor2(cursor) {
8264
8656
  }
8265
8657
  return parsed;
8266
8658
  }
8267
- async function listPage(engine, sourceIds, principals, action, limit, cursor, ceiling, redaction) {
8659
+ async function listPage(engine, sourceIds, principals, action, limit, cursor, documentIds, ceiling, redaction) {
8268
8660
  const page = await engine.listDocuments({
8269
8661
  // `!= null`, NOT truthiness: an EMPTY array means "nothing is in scope"
8270
8662
  // and collapsing it to null would list the whole corpus.
8271
8663
  sourceIds: sourceIds != null ? [...new Set(sourceIds)] : null,
8664
+ // Already intersected with the host's ceiling by `narrowToCeiling`, and
8665
+ // filtered in SQL rather than after the page is built — three named
8666
+ // documents sitting on page four must come back as themselves, not as an
8667
+ // empty page.
8668
+ documentIds: documentIds != null ? [...new Set(documentIds)] : null,
8272
8669
  principals,
8273
8670
  cursor,
8274
8671
  limit: Math.max(1, Math.min(limit, MAX_LIST_LIMIT)),
@@ -8278,7 +8675,9 @@ async function listPage(engine, sourceIds, principals, action, limit, cursor, ce
8278
8675
  id: String(raw.id),
8279
8676
  name: raw.name,
8280
8677
  source_id: raw.sourceId ?? raw.source_id,
8281
- kind: documentKind(raw)
8678
+ kind: documentKind(raw),
8679
+ document_type: raw.documentType ?? raw.document_type ?? null,
8680
+ mode: raw.mode ?? null
8282
8681
  }));
8283
8682
  if (ceiling.documentIds != null) {
8284
8683
  const allowed = new Set(ceiling.documentIds);
@@ -8331,30 +8730,62 @@ async function callKnowledgeTool(engine, args) {
8331
8730
  action,
8332
8731
  args.limit ?? 50,
8333
8732
  parseCursor2(args.cursor),
8733
+ documentIds,
8334
8734
  ceiling,
8335
8735
  args.redaction
8336
8736
  );
8337
8737
  if (action === "list") return { success: true, ...page };
8338
- const spreadsheets = page.documents.filter((d) => d.kind === "spreadsheet").map((d) => d.name);
8738
+ const structures = await engine.documentStructure({
8739
+ documentIds: page.documents.map((d) => d.id),
8740
+ sourceIds,
8741
+ principals,
8742
+ // The cap is for the call that did NOT name its documents. A caller
8743
+ // that asked about specific documents asked for all of them, and the
8744
+ // truncated payload tells it to make exactly this call — so answering
8745
+ // it truncated again would be a loop.
8746
+ bounded: !requestedDocumentIds?.length,
8747
+ redaction: args.redaction
8748
+ });
8749
+ for (const doc of page.documents) doc.structure = structures[doc.id] ?? {};
8750
+ const hasSpreadsheet = page.documents.some((d) => d.kind === "spreadsheet");
8751
+ const fieldsByType = await engine.fieldSummary({
8752
+ sourceIds,
8753
+ documentIds,
8754
+ principals,
8755
+ redaction: args.redaction
8756
+ });
8757
+ const census = await engine.documentTypes({
8758
+ sourceIds,
8759
+ documentIds,
8760
+ principals,
8761
+ redaction: args.redaction
8762
+ });
8339
8763
  const forAFact = { action: "search", query: "<bare identifier or key words>" };
8340
8764
  const nextAction = {};
8341
- if (spreadsheets.length && available.compute) {
8765
+ if (hasSpreadsheet && available.compute) {
8342
8766
  nextAction["for a figure from a spreadsheet"] = {
8343
8767
  action: "compute",
8344
- query: "<what to compute, columns as named>"
8768
+ query: "<what to compute, columns as named above>"
8345
8769
  };
8346
8770
  }
8347
8771
  nextAction["for a clause or a fact"] = forAFact;
8772
+ if (fieldsByType.length && available.query_meta) {
8773
+ nextAction["for documents by a field value"] = {
8774
+ action: "query_meta",
8775
+ query: "<a question naming a field from fields_by_type>"
8776
+ };
8777
+ }
8348
8778
  if (available.get_neighbors) {
8349
8779
  nextAction["for how things connect"] = {
8350
8780
  action: "get_neighbors",
8351
8781
  entity: "<a name that appears in the documents>"
8352
8782
  };
8353
8783
  }
8354
- return {
8784
+ const discovered = {
8355
8785
  success: true,
8356
8786
  ...page,
8357
- spreadsheets,
8787
+ document_types: census,
8788
+ fields_by_type: fieldsByType,
8358
8789
  available_actions: Object.fromEntries(
8359
8790
  Object.keys(ACTION_HELP).map((name) => [
8360
8791
  name,
@@ -8363,6 +8794,7 @@ async function callKnowledgeTool(engine, args) {
8363
8794
  ),
8364
8795
  next_action: nextAction
8365
8796
  };
8797
+ return discovered;
8366
8798
  }
8367
8799
  if (action === "search") {
8368
8800
  if (!text) return { success: false, error: "search needs a query" };
@@ -8592,7 +9024,7 @@ var init_knowledge_tool = __esm({
8592
9024
  "get_neighbors",
8593
9025
  "community_summary"
8594
9026
  ];
8595
- 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.";
9027
+ 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.";
8596
9028
  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.";
8597
9029
  ACTION_HELP = {
8598
9030
  search: "passages by meaning or keywords; an ID, code or number as the BARE identifier",
@@ -8615,7 +9047,7 @@ var init_knowledge_tool = __esm({
8615
9047
  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."
8616
9048
  };
8617
9049
  GRAPH_ACTIONS = ["traverse", "find_related", "get_neighbors", "community_summary"];
8618
- DOCUMENT_ID_ACTIONS = ["search", "compute", "get_docs", "map_reduce"];
9050
+ DOCUMENT_ID_ACTIONS = ["search", "compute", "get_docs", "map_reduce", "discover", "list"];
8619
9051
  DEFAULT_GET_DOCS_CHARS = 2e5;
8620
9052
  INPUT_PROPERTIES = {
8621
9053
  action: { type: "string", enum: [...KNOWLEDGE_ACTIONS], description: ACTION_PARAM_DESCRIPTION },
@@ -8635,7 +9067,7 @@ var init_knowledge_tool = __esm({
8635
9067
  document_ids: {
8636
9068
  type: "array",
8637
9069
  items: { type: "string" },
8638
- 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)"
9070
+ 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)"
8639
9071
  },
8640
9072
  entity: {
8641
9073
  type: "string",
@@ -13668,6 +14100,7 @@ var ContextEngine = class _ContextEngine {
13668
14100
  pool,
13669
14101
  sourceId: opts.sourceId,
13670
14102
  sourceIds: opts.sourceIds,
14103
+ documentIds: opts.documentIds,
13671
14104
  principals: resolvePrincipals(opts.principals, "listDocuments"),
13672
14105
  cursor: opts.cursor,
13673
14106
  limit: opts.limit,
@@ -13676,6 +14109,84 @@ var ContextEngine = class _ContextEngine {
13676
14109
  hooks: this.hooks
13677
14110
  });
13678
14111
  }
14112
+ /**
14113
+ * Sheet names, columns and row counts for the named spreadsheets.
14114
+ *
14115
+ * See `actions.spreadsheetSchema`. This is the half of `discover` that lets
14116
+ * a model write ONE `compute` call: sheet names here are the keys it will
14117
+ * index `dfs` by, and columns are the names it will use inside the code it
14118
+ * writes.
14119
+ */
14120
+ async spreadsheetSchema(opts) {
14121
+ const pool = await this.ensurePool();
14122
+ return spreadsheetSchema({
14123
+ pool,
14124
+ documentIds: opts.documentIds,
14125
+ sourceIds: opts.sourceIds,
14126
+ principals: resolvePrincipals(opts.principals, "spreadsheetSchema"),
14127
+ redaction: opts.redaction ?? this.config.redaction,
14128
+ secretKey: this.config.secretKey,
14129
+ hooks: this.hooks
14130
+ });
14131
+ }
14132
+ /**
14133
+ * What is inside each of the named documents, whatever its type.
14134
+ *
14135
+ * See `actions.documentStructure`. Sheets and columns for a workbook,
14136
+ * sections and the last page for a document with headings, top-level keys
14137
+ * for JSON, and a chunk count for everything — so `discover` describes the
14138
+ * whole corpus rather than only the spreadsheets in it.
14139
+ */
14140
+ async documentStructure(opts) {
14141
+ const pool = await this.ensurePool();
14142
+ return documentStructure({
14143
+ pool,
14144
+ documentIds: opts.documentIds,
14145
+ sourceIds: opts.sourceIds,
14146
+ bounded: opts.bounded,
14147
+ principals: resolvePrincipals(opts.principals, "documentStructure"),
14148
+ redaction: opts.redaction ?? this.config.redaction,
14149
+ secretKey: this.config.secretKey,
14150
+ hooks: this.hooks
14151
+ });
14152
+ }
14153
+ /**
14154
+ * The corpus census — `[{kind, type, documents, with_fields}]`.
14155
+ *
14156
+ * See `actions.documentTypes`. `kind` comes from the mime and is always
14157
+ * known; `type` is the LLM-written document type and exists only where
14158
+ * structured extraction was opted into.
14159
+ */
14160
+ async documentTypes(opts = {}) {
14161
+ const pool = await this.ensurePool();
14162
+ return documentTypes({
14163
+ pool,
14164
+ sourceIds: opts.sourceIds,
14165
+ documentIds: opts.documentIds,
14166
+ principals: resolvePrincipals(opts.principals, "documentTypes"),
14167
+ redaction: opts.redaction ?? this.config.redaction,
14168
+ secretKey: this.config.secretKey,
14169
+ hooks: this.hooks
14170
+ });
14171
+ }
14172
+ /**
14173
+ * Extracted structured field names grouped by document kind and type.
14174
+ *
14175
+ * See `actions.fieldSummary`. One row per group, keyed by the same
14176
+ * `(kind, type)` pair `documentTypes` uses.
14177
+ */
14178
+ async fieldSummary(opts = {}) {
14179
+ const pool = await this.ensurePool();
14180
+ return fieldSummary({
14181
+ pool,
14182
+ sourceIds: opts.sourceIds,
14183
+ documentIds: opts.documentIds,
14184
+ principals: resolvePrincipals(opts.principals, "fieldSummary"),
14185
+ redaction: opts.redaction ?? this.config.redaction,
14186
+ secretKey: this.config.secretKey,
14187
+ hooks: this.hooks
14188
+ });
14189
+ }
13679
14190
  async queryStructured(question, opts = {}) {
13680
14191
  const pool = await this.ensurePool();
13681
14192
  return queryStructured(question, {
@@ -14042,6 +14553,6 @@ init_sentinels();
14042
14553
  init_structured();
14043
14554
  init_usage();
14044
14555
 
14045
- export { ApprovalExpired, ApprovalNotPending, CeleryRunner, CodeExecutionError, CodeExecutionTimeout, ContextEngine, ContextEngineConfig, DEFAULT_LEG_WEIGHT, DocumentNotFoundError, EXTRACTION_VERSION, Embedder, EngineActionError, ExtraMissingError, Extracted, GraphLegUnavailable, InProcessRunner, KNOWLEDGE_ACTIONS, KNOWLEDGE_TOOL_DESCRIPTION, LLMClient, PostgresBackend, RedactionPolicy, RedactionRule, TRUSTED, ToolConfig, UNSCOPED, UNSET, __version__, applyRedaction, buildEmbedder, buildLlmClient, callKnowledgeTool, callLlm, compute, computeOverFrames, configSchema, createMcpApp, decryptDict, emitError, emitProgress, emitToolCall, emitUsage, encryptDict, extract2 as extract, extractStructuredData, functionTool, getDocumentText, getSecretKey, graphUnits, knowledgeToolDefinition, listDocuments, narrowToCeiling, queryStructured, redactHits, rerank, resolveApproval, resolveFields, resolvePrincipals, resolveScope, rrfFuse, runMigrate, runSearch, shouldRequireApproval, unitsForFile, upsertRegistry };
14556
+ export { ApprovalExpired, ApprovalNotPending, CeleryRunner, CodeExecutionError, CodeExecutionTimeout, ContextEngine, ContextEngineConfig, DEFAULT_LEG_WEIGHT, DocumentNotFoundError, EXTRACTION_VERSION, Embedder, EngineActionError, ExtraMissingError, Extracted, GraphLegUnavailable, InProcessRunner, KNOWLEDGE_ACTIONS, KNOWLEDGE_TOOL_DESCRIPTION, LLMClient, PostgresBackend, RedactionPolicy, RedactionRule, TRUSTED, ToolConfig, UNSCOPED, UNSET, __version__, applyRedaction, buildEmbedder, buildLlmClient, callKnowledgeTool, callLlm, compute, computeOverFrames, configSchema, createMcpApp, decryptDict, documentStructure, documentTypes, emitError, emitProgress, emitToolCall, emitUsage, encryptDict, extract2 as extract, extractStructuredData, fieldSummary, functionTool, getDocumentText, getSecretKey, graphUnits, knowledgeToolDefinition, listDocuments, narrowToCeiling, queryStructured, redactHits, rerank, resolveApproval, resolveFields, resolvePrincipals, resolveScope, rrfFuse, runMigrate, runSearch, shouldRequireApproval, spreadsheetSchema, spreadsheetSchemaFromText, unitsForFile, upsertRegistry };
14046
14557
  //# sourceMappingURL=index.js.map
14047
14558
  //# sourceMappingURL=index.js.map