briyah 2.0.17 → 2.0.19

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.
Files changed (35) hide show
  1. package/dist-sdk/server/src/ai/agent-config.d.ts +4 -0
  2. package/dist-sdk/server/src/ai/agent-store.service.js +4 -0
  3. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  4. package/dist-sdk/server/src/ai/agent.js +7 -0
  5. package/dist-sdk/server/src/app/balance.service.js +1 -1
  6. package/dist-sdk/server/src/app/usage-context.d.ts +19 -1
  7. package/dist-sdk/server/src/app/usage-context.js +21 -4
  8. package/dist-sdk/server/src/app.service.d.ts +2 -0
  9. package/dist-sdk/server/src/app.service.js +2 -0
  10. package/dist-sdk/server/src/data/query-validation.d.ts +9 -1
  11. package/dist-sdk/server/src/data/query-validation.js +9 -5
  12. package/dist-sdk/server/src/data/run-query.d.ts +14 -0
  13. package/dist-sdk/server/src/data/run-query.js +39 -0
  14. package/dist-sdk/server/src/documents/document-conversion.d.ts +27 -9
  15. package/dist-sdk/server/src/documents/document-conversion.js +131 -10
  16. package/dist-sdk/server/src/documents/html-data.d.ts +49 -0
  17. package/dist-sdk/server/src/documents/html-data.js +120 -0
  18. package/dist-sdk/server/src/documents/html-template.d.ts +108 -0
  19. package/dist-sdk/server/src/documents/html-template.js +332 -0
  20. package/dist-sdk/server/src/documents/library/document.types.d.ts +64 -0
  21. package/dist-sdk/server/src/documents/library/document.types.js +6 -0
  22. package/dist-sdk/server/src/documents/library/html-template-guide.builder.d.ts +13 -0
  23. package/dist-sdk/server/src/documents/library/html-template-guide.builder.js +185 -0
  24. package/dist-sdk/server/src/documents/template-mapping.d.ts +203 -0
  25. package/dist-sdk/server/src/documents/template-mapping.js +452 -0
  26. package/dist-sdk/server/src/room/room.d.ts +2 -1
  27. package/dist-sdk/server/src/room/room.js +7 -3
  28. package/dist-sdk/server/src/sdk/index.d.ts +12 -3
  29. package/dist-sdk/server/src/sdk/index.js +28 -2
  30. package/dist-sdk/server/src/tools/core/document.tools.d.ts +22 -0
  31. package/dist-sdk/server/src/tools/core/document.tools.js +20 -6
  32. package/dist-sdk/server/src/tools/core/html-template.tools.d.ts +31 -0
  33. package/dist-sdk/server/src/tools/core/html-template.tools.js +494 -0
  34. package/dist-sdk/server/src/tools/core/index.js +2 -0
  35. package/package.json +1 -1
@@ -20,6 +20,8 @@ export interface AgentConfig {
20
20
  attachedArtifacts?: string[];
21
21
  history?: any[];
22
22
  maxHistoryMessages: number;
23
+ /** Tool calls this agent may chain in one turn, in place of the room's default. */
24
+ maxToolIterations?: number;
23
25
  totalInputTokens?: number;
24
26
  totalOutputTokens?: number;
25
27
  totalCost?: number;
@@ -36,6 +38,8 @@ export interface AgentConfig {
36
38
  usageTags?: {
37
39
  user?: string;
38
40
  feature?: string;
41
+ activity?: string;
42
+ detail?: string;
39
43
  };
40
44
  toolNames?: string[];
41
45
  useModerator?: boolean;
@@ -208,6 +208,7 @@ let AgentStoreService = class AgentStoreService {
208
208
  instance.attachedFiles = [...template.attachedFiles];
209
209
  instance.attachedArtifacts = [...template.attachedArtifacts];
210
210
  instance.maxHistoryMessages = template.maxHistoryMessages;
211
+ instance.maxToolIterations = template.maxToolIterations;
211
212
  instance.promptCacheTTL = template.promptCacheTTL;
212
213
  instance.markupRate = template.markupRate;
213
214
  instance.smallModelName = template.smallModelName;
@@ -277,6 +278,7 @@ let AgentStoreService = class AgentStoreService {
277
278
  instance.attachedArtifacts = [...template.attachedArtifacts];
278
279
  instance.beginInstruction = template.beginInstruction;
279
280
  instance.maxHistoryMessages = template.maxHistoryMessages;
281
+ instance.maxToolIterations = template.maxToolIterations;
280
282
  instance.promptCacheTTL = template.promptCacheTTL;
281
283
  instance.markupRate = template.markupRate;
282
284
  instance.toolNames = [...template.toolNames];
@@ -394,6 +396,7 @@ let AgentStoreService = class AgentStoreService {
394
396
  // Restore begin instruction
395
397
  agent.beginInstruction = config.beginInstruction || '';
396
398
  agent.maxHistoryMessages = config.maxHistoryMessages || undefined;
399
+ agent.maxToolIterations = config.maxToolIterations || undefined;
397
400
  // Restore cache keep-alive settings
398
401
  agent.promptCacheTTL = Number(config.promptCacheTTL) ?? 0;
399
402
  // Restore tool grants
@@ -488,6 +491,7 @@ let AgentStoreService = class AgentStoreService {
488
491
  attachedArtifacts: agent.attachedArtifacts,
489
492
  history: agent.history,
490
493
  maxHistoryMessages: agent.maxHistoryMessages,
494
+ ...(agent.maxToolIterations ? { maxToolIterations: agent.maxToolIterations } : {}),
491
495
  totalInputTokens: agent.totalInputTokens,
492
496
  totalOutputTokens: agent.totalOutputTokens,
493
497
  totalCost: agent.totalCost,
@@ -82,6 +82,13 @@ export declare class Agent {
82
82
  */
83
83
  enabledPacks?: () => readonly string[];
84
84
  maxHistoryMessages?: number;
85
+ /**
86
+ * Tool calls this agent may chain in one turn, in place of the room's default
87
+ * (`ROOM_MAX_TOOL_ITERATIONS`, 30). For an agent whose one job is long — read a
88
+ * template, run its queries, fill, check, fill again — where the default would
89
+ * end its turn mid-task.
90
+ */
91
+ maxToolIterations?: number;
85
92
  /**
86
93
  * Index into {@link history} below which the rolling window may trim, and at or
87
94
  * above which it may not. Protects a task that must survive intact from an agent
@@ -83,6 +83,13 @@ class Agent {
83
83
  */
84
84
  enabledPacks;
85
85
  maxHistoryMessages; // If set, keep only last N messages (rolling window)
86
+ /**
87
+ * Tool calls this agent may chain in one turn, in place of the room's default
88
+ * (`ROOM_MAX_TOOL_ITERATIONS`, 30). For an agent whose one job is long — read a
89
+ * template, run its queries, fill, check, fill again — where the default would
90
+ * end its turn mid-task.
91
+ */
92
+ maxToolIterations;
86
93
  /**
87
94
  * Index into {@link history} below which the rolling window may trim, and at or
88
95
  * above which it may not. Protects a task that must survive intact from an agent
@@ -134,7 +134,7 @@ class BalanceService {
134
134
  ...(source?.agentName ? { agentName: source.agentName } : {}),
135
135
  ...(source?.serviceName ? { serviceName: source.serviceName } : {}),
136
136
  ...(source?.modelName ? { modelName: source.modelName } : {}),
137
- ...(tags.user || tags.feature ? { tags } : {}),
137
+ ...(Object.keys(tags).length ? { tags } : {}),
138
138
  });
139
139
  }
140
140
  /**
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Who and what an AI charge is for, recorded with it in the user's usage ledger
3
- * (see BalanceService). Both are the host's own labels: Briyah stores and
3
+ * (see BalanceService). All are the host's own labels: Briyah stores and
4
4
  * groups by them but never interprets them.
5
5
  */
6
6
  export interface UsageTags {
@@ -8,6 +8,15 @@ export interface UsageTags {
8
8
  user?: string;
9
9
  /** What the work was, e.g. "Loss run import" or "AI Assistant". */
10
10
  feature?: string;
11
+ /**
12
+ * One piece of work the charges belong to, e.g. a request id. A single user
13
+ * action — an import, a question — makes many AI calls, each its own charge;
14
+ * charges sharing an activity are that one action, so a host can show "what was
15
+ * done" as one line with its total rather than as every call behind it.
16
+ */
17
+ activity?: string;
18
+ /** What that piece of work was, in the host's words, e.g. "Imported mvrs.pdf". */
19
+ detail?: string;
11
20
  }
12
21
  /**
13
22
  * Runs `fn` with these usage tags in force: every AI charge made while it runs,
@@ -18,6 +27,15 @@ export interface UsageTags {
18
27
  * Tags set on an agent (`agent.usageTags`) win over these.
19
28
  */
20
29
  export declare function runWithUsageTags<T>(tags: UsageTags, fn: () => T): T;
30
+ /**
31
+ * Adds or replaces tags on the context already in force, for every charge made in
32
+ * it from now on — including by work it has already started, which shares that
33
+ * context. For a tag only known partway through: a host that tags each request as it
34
+ * arrives learns what the request was about (the file it uploaded, say) only once
35
+ * the request has been read. Outside any `runWithUsageTags` it does nothing, and a
36
+ * context nested inside this one keeps the tags it copied when it began.
37
+ */
38
+ export declare function updateUsageTags(tags: UsageTags): void;
21
39
  /** The usage tags in force here, or an empty object. */
22
40
  export declare function currentUsageTags(): UsageTags;
23
41
  /** The tags a charge is recorded with: the context's, then the agent's own on top. */
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runWithUsageTags = runWithUsageTags;
4
+ exports.updateUsageTags = updateUsageTags;
4
5
  exports.currentUsageTags = currentUsageTags;
5
6
  exports.resolveUsageTags = resolveUsageTags;
6
7
  const async_hooks_1 = require("async_hooks");
8
+ /** The tag keys a charge records. */
9
+ const TAG_KEYS = ['user', 'feature', 'activity', 'detail'];
7
10
  const storage = new async_hooks_1.AsyncLocalStorage();
8
11
  /**
9
12
  * Runs `fn` with these usage tags in force: every AI charge made while it runs,
@@ -17,6 +20,19 @@ function runWithUsageTags(tags, fn) {
17
20
  const outer = storage.getStore();
18
21
  return storage.run({ ...outer, ...clean(tags) }, fn);
19
22
  }
23
+ /**
24
+ * Adds or replaces tags on the context already in force, for every charge made in
25
+ * it from now on — including by work it has already started, which shares that
26
+ * context. For a tag only known partway through: a host that tags each request as it
27
+ * arrives learns what the request was about (the file it uploaded, say) only once
28
+ * the request has been read. Outside any `runWithUsageTags` it does nothing, and a
29
+ * context nested inside this one keeps the tags it copied when it began.
30
+ */
31
+ function updateUsageTags(tags) {
32
+ const store = storage.getStore();
33
+ if (store)
34
+ Object.assign(store, clean(tags));
35
+ }
20
36
  /** The usage tags in force here, or an empty object. */
21
37
  function currentUsageTags() {
22
38
  return { ...storage.getStore() };
@@ -27,9 +43,10 @@ function resolveUsageTags(agentTags) {
27
43
  }
28
44
  function clean(tags) {
29
45
  const out = {};
30
- if (typeof tags.user === 'string' && tags.user.trim())
31
- out.user = tags.user.trim();
32
- if (typeof tags.feature === 'string' && tags.feature.trim())
33
- out.feature = tags.feature.trim();
46
+ for (const key of TAG_KEYS) {
47
+ const value = tags[key];
48
+ if (typeof value === 'string' && value.trim())
49
+ out[key] = value.trim();
50
+ }
34
51
  return out;
35
52
  }
@@ -58,6 +58,8 @@ export interface AgentCreationOptions {
58
58
  promptCacheTTL?: number;
59
59
  /** Rolling history window: keep only the last N messages. */
60
60
  maxHistoryMessages?: number;
61
+ /** Tool calls the agent may chain in one turn, in place of the room's default. */
62
+ maxToolIterations?: number;
61
63
  /** A cheaper same-service model for mechanical prompts. */
62
64
  smallModelName?: string;
63
65
  /**
@@ -367,6 +367,8 @@ class AppService {
367
367
  agent.promptCacheTTL = options.promptCacheTTL;
368
368
  if (options.maxHistoryMessages !== undefined)
369
369
  agent.maxHistoryMessages = options.maxHistoryMessages;
370
+ if (options.maxToolIterations !== undefined)
371
+ agent.maxToolIterations = options.maxToolIterations;
370
372
  if (options.smallModelName !== undefined)
371
373
  agent.smallModelName = options.smallModelName;
372
374
  if (options.ownerRoomId !== undefined)
@@ -40,6 +40,14 @@ export declare function metricName(fn: DataAggregateFn, field?: string, as?: str
40
40
  *
41
41
  * @param raw The query as the model produced it
42
42
  * @param sets Every dataset the source declares
43
+ * @param options `maxLimit` replaces the row ceiling — the dataset's and the
44
+ * engine's — and makes it the default too, for rows that go somewhere other
45
+ * than an agent's context (a filled template), where those ceilings exist to
46
+ * protect the context
43
47
  * @returns The validated query, or a refusal naming what was allowed instead
44
48
  */
45
- export declare function validateQuery(raw: any, sets: DataSet[]): ValidationResult;
49
+ export declare function validateQuery(raw: any, sets: DataSet[], options?: ValidateQueryOptions): ValidationResult;
50
+ export interface ValidateQueryOptions {
51
+ /** The row ceiling, and the default, in place of the dataset's and the engine's. */
52
+ maxLimit?: number;
53
+ }
@@ -61,9 +61,13 @@ function metricName(fn, field, as) {
61
61
  *
62
62
  * @param raw The query as the model produced it
63
63
  * @param sets Every dataset the source declares
64
+ * @param options `maxLimit` replaces the row ceiling — the dataset's and the
65
+ * engine's — and makes it the default too, for rows that go somewhere other
66
+ * than an agent's context (a filled template), where those ceilings exist to
67
+ * protect the context
64
68
  * @returns The validated query, or a refusal naming what was allowed instead
65
69
  */
66
- function validateQuery(raw, sets) {
70
+ function validateQuery(raw, sets, options = {}) {
67
71
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
68
72
  return fail('The query must be a JSON object.');
69
73
  }
@@ -147,16 +151,16 @@ function validateQuery(raw, sets) {
147
151
  having,
148
152
  select,
149
153
  orderBy,
150
- limit: resolveLimit(raw.limit, set),
154
+ limit: resolveLimit(raw.limit, set, options),
151
155
  },
152
156
  };
153
157
  }
154
158
  /** Clamps a requested row count into the dataset's and the engine's bounds. */
155
- function resolveLimit(requested, set) {
156
- const ceiling = Math.min(set.maxLimit ?? data_types_1.MAX_ROW_LIMIT, data_types_1.MAX_ROW_LIMIT);
159
+ function resolveLimit(requested, set, options = {}) {
160
+ const ceiling = options.maxLimit ?? Math.min(set.maxLimit ?? data_types_1.MAX_ROW_LIMIT, data_types_1.MAX_ROW_LIMIT);
157
161
  const asked = Number(requested);
158
162
  if (!Number.isFinite(asked) || asked <= 0) {
159
- return Math.min(set.defaultLimit ?? data_types_1.DEFAULT_ROW_LIMIT, ceiling);
163
+ return options.maxLimit ?? Math.min(set.defaultLimit ?? data_types_1.DEFAULT_ROW_LIMIT, ceiling);
160
164
  }
161
165
  return Math.min(Math.floor(asked), ceiling);
162
166
  }
@@ -0,0 +1,14 @@
1
+ import { ValidateQueryOptions } from './query-validation';
2
+ import { DataQuery, DataRow } from './data.types';
3
+ export type RunQueryResult = {
4
+ ok: true;
5
+ query: DataQuery;
6
+ rows: DataRow[];
7
+ totalRows?: number;
8
+ } | {
9
+ ok: false;
10
+ error: string;
11
+ available?: string[];
12
+ };
13
+ /** Validates and runs a raw query. Never throws for a bad query: the refusal names what was allowed. */
14
+ export declare function runDataQuery(raw: unknown, context: unknown, options?: ValidateQueryOptions): Promise<RunQueryResult>;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runDataQuery = runDataQuery;
4
+ /**
5
+ * Running one query an agent wrote: validate it against the registered datasets,
6
+ * find the source that offers it, and execute it with the host's context — the
7
+ * same three steps `query_data` takes, for anything else that runs a query on an
8
+ * agent's behalf (a template fill). The context is the host's, so its scoping
9
+ * applies exactly as it does to `query_data`.
10
+ */
11
+ const data_registry_1 = require("./data-registry");
12
+ const query_validation_1 = require("./query-validation");
13
+ /** Validates and runs a raw query. Never throws for a bad query: the refusal names what was allowed. */
14
+ async function runDataQuery(raw, context, options = {}) {
15
+ const checked = (0, query_validation_1.validateQuery)(raw, (0, data_registry_1.listDatasets)(), options);
16
+ if (!checked.ok || !checked.query) {
17
+ return {
18
+ ok: false,
19
+ error: checked.error ?? 'The query was refused.',
20
+ ...(checked.available ? { available: checked.available } : {}),
21
+ };
22
+ }
23
+ const query = checked.query;
24
+ const source = (0, data_registry_1.sourceForDataset)(query.dataset);
25
+ if (!source) {
26
+ return {
27
+ ok: false,
28
+ error: `Unknown dataset "${query.dataset}". Available datasets:`,
29
+ available: (0, data_registry_1.listDatasets)().map((set) => set.name),
30
+ };
31
+ }
32
+ const result = await source.execute(query, context);
33
+ return {
34
+ ok: true,
35
+ query,
36
+ rows: Array.isArray(result?.rows) ? result.rows : [],
37
+ ...(typeof result?.totalRows === 'number' ? { totalRows: result.totalRows } : {}),
38
+ };
39
+ }
@@ -2,9 +2,9 @@
2
2
  * Turning an uploaded file into Markdown pages, whatever kind of file it was.
3
3
  *
4
4
  * PDFs go through the per-page AI conversion in `pdf-conversion.ts`, because a
5
- * PDF is a picture of a page and needs reading. Word and Excel files do not: they
6
- * already carry their text and structure, so they convert locally, instantly and
7
- * for nothing. This module owns that local half, plus the one decision both
5
+ * PDF is a picture of a page and needs reading. Word, Excel and HTML files do not:
6
+ * they already carry their text and structure, so they convert locally, instantly
7
+ * and for nothing. This module owns that local half, plus the one decision both
8
8
  * halves depend on — what kind of file this actually is.
9
9
  *
10
10
  * That decision is the part worth getting right. A host that assumed "not a PDF,
@@ -16,10 +16,13 @@
16
16
  * document does not — its pagination is decided by whatever renders it — so it
17
17
  * comes back as one page, and an agent locates a passage by its heading instead
18
18
  * of by a page number that would not match the user's screen. A workbook comes
19
- * back as one page per visible sheet, labelled with the sheet's name.
19
+ * back as one page per visible sheet, labelled with the sheet's name. An HTML page
20
+ * comes back as one page of what it shows, plus one labelled page per block of
21
+ * data embedded in it (see `convertHtml`).
20
22
  */
23
+ export { describeShape, readableJson } from './html-data';
21
24
  /** What a file turned out to be. */
22
- export type DocumentFileType = 'pdf' | 'docx' | 'xlsx' | 'text' | 'unsupported';
25
+ export type DocumentFileType = 'pdf' | 'docx' | 'xlsx' | 'html' | 'text' | 'unsupported';
23
26
  export interface DocumentTypeDetection {
24
27
  type: DocumentFileType;
25
28
  /** Why the file cannot be read, phrased for the person who uploaded it. Set only when unsupported. */
@@ -30,17 +33,32 @@ export interface DocumentPage {
30
33
  /** 1-based. For a workbook, the sheet's position among the sheets converted. */
31
34
  pageNum: number;
32
35
  markdown: string;
33
- /** A name for the page when it has one — a workbook's sheet name. */
36
+ /** A name for the page when it has one — a workbook's sheet name, an HTML page's data block. */
34
37
  label?: string;
35
38
  }
36
39
  /** A locally converted document. PDFs are not produced here; see `convertPdfToMarkdownPages`. */
37
40
  export interface LocalDocumentConversion {
38
- type: 'docx' | 'xlsx' | 'text';
41
+ type: 'docx' | 'xlsx' | 'html' | 'text';
39
42
  pages: DocumentPage[];
40
43
  /** The pages assembled with `<!-- Page N -->` markers, the same format the PDF path writes. */
41
44
  markdown: string;
42
- /** Things the reader should know were changed or left out: hidden sheets, truncated rows, images. */
45
+ /** Things the reader should know were changed or left out: hidden sheets, truncated rows, images, scripts. */
43
46
  warnings: string[];
47
+ /**
48
+ * For an HTML page, the JSON data blocks it carries — what makes it a template
49
+ * that could be filled with other data (see `html-template.ts`). Absent otherwise.
50
+ */
51
+ dataBlocks?: HtmlDataBlockInfo[];
52
+ }
53
+ /** One JSON data block an HTML page carries, described. */
54
+ export interface HtmlDataBlockInfo {
55
+ /** The block's id, or "data block N". What a fill names it by. */
56
+ label: string;
57
+ /** The script's type, e.g. `application/json`. */
58
+ type: string;
59
+ chars: number;
60
+ /** Its shape in one line, or "not valid JSON". */
61
+ shape: string;
44
62
  }
45
63
  export interface LocalConversionOptions {
46
64
  /**
@@ -63,7 +81,7 @@ export declare class UnsupportedDocumentError extends Error {
63
81
  */
64
82
  export declare function detectDocumentType(bytes: Uint8Array, fileName: string): DocumentTypeDetection;
65
83
  /**
66
- * Converts a Word, Excel or plain-text file to Markdown pages, locally.
84
+ * Converts a Word, Excel, HTML or plain-text file to Markdown pages, locally.
67
85
  *
68
86
  * @throws {UnsupportedDocumentError} For a PDF (which needs the AI path) or anything unreadable
69
87
  */
@@ -3,9 +3,9 @@
3
3
  * Turning an uploaded file into Markdown pages, whatever kind of file it was.
4
4
  *
5
5
  * PDFs go through the per-page AI conversion in `pdf-conversion.ts`, because a
6
- * PDF is a picture of a page and needs reading. Word and Excel files do not: they
7
- * already carry their text and structure, so they convert locally, instantly and
8
- * for nothing. This module owns that local half, plus the one decision both
6
+ * PDF is a picture of a page and needs reading. Word, Excel and HTML files do not:
7
+ * they already carry their text and structure, so they convert locally, instantly
8
+ * and for nothing. This module owns that local half, plus the one decision both
9
9
  * halves depend on — what kind of file this actually is.
10
10
  *
11
11
  * That decision is the part worth getting right. A host that assumed "not a PDF,
@@ -17,7 +17,9 @@
17
17
  * document does not — its pagination is decided by whatever renders it — so it
18
18
  * comes back as one page, and an agent locates a passage by its heading instead
19
19
  * of by a page number that would not match the user's screen. A workbook comes
20
- * back as one page per visible sheet, labelled with the sheet's name.
20
+ * back as one page per visible sheet, labelled with the sheet's name. An HTML page
21
+ * comes back as one page of what it shows, plus one labelled page per block of
22
+ * data embedded in it (see `convertHtml`).
21
23
  */
22
24
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
23
25
  if (k2 === undefined) k2 = k;
@@ -56,7 +58,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
56
58
  return (mod && mod.__esModule) ? mod : { "default": mod };
57
59
  };
58
60
  Object.defineProperty(exports, "__esModule", { value: true });
59
- exports.UnsupportedDocumentError = void 0;
61
+ exports.UnsupportedDocumentError = exports.readableJson = exports.describeShape = void 0;
60
62
  exports.detectDocumentType = detectDocumentType;
61
63
  exports.convertLocalDocument = convertLocalDocument;
62
64
  const mammoth = __importStar(require("mammoth"));
@@ -64,6 +66,11 @@ const turndown_1 = __importDefault(require("turndown"));
64
66
  const exceljs_1 = __importDefault(require("exceljs"));
65
67
  const jszip_1 = __importDefault(require("jszip"));
66
68
  const pdf_conversion_1 = require("./pdf-conversion");
69
+ const html_data_1 = require("./html-data");
70
+ // Kept importable from here, where they were first defined.
71
+ var html_data_2 = require("./html-data");
72
+ Object.defineProperty(exports, "describeShape", { enumerable: true, get: function () { return html_data_2.describeShape; } });
73
+ Object.defineProperty(exports, "readableJson", { enumerable: true, get: function () { return html_data_2.readableJson; } });
67
74
  /** Thrown for a file that cannot be read. `message` is written for the person who uploaded it. */
68
75
  class UnsupportedDocumentError extends Error {
69
76
  constructor(message) {
@@ -78,6 +85,7 @@ const PDF_MAGIC = [0x25, 0x50, 0x44, 0x46];
78
85
  /** Word 97–2003 and Excel 97–2003 share this OLE compound-file signature. */
79
86
  const OLE_MAGIC = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
80
87
  const TEXT_EXTENSIONS = new Set(['md', 'markdown', 'txt', 'csv', 'tsv', 'text']);
88
+ const HTML_EXTENSIONS = new Set(['html', 'htm', 'xhtml']);
81
89
  function startsWith(bytes, magic) {
82
90
  return magic.every((byte, index) => bytes[index] === byte);
83
91
  }
@@ -89,6 +97,17 @@ function startsWith(bytes, magic) {
89
97
  function zipContains(bytes, entryName) {
90
98
  return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).indexOf(entryName, 0, 'latin1') !== -1;
91
99
  }
100
+ /**
101
+ * Whether text opens like an HTML document — a doctype, or an `<html>`, `<head>`
102
+ * or `<body>` tag — once any byte-order mark, whitespace and comments are skipped.
103
+ */
104
+ function looksLikeHtml(bytes) {
105
+ const head = new TextDecoder('utf-8')
106
+ .decode(bytes.subarray(0, Math.min(bytes.length, 4096)))
107
+ .replace(/^\uFEFF/, '')
108
+ .replace(/^(?:\s|<!--[\s\S]*?-->)*/, '');
109
+ return /^<(?:!doctype\s+html|html[\s>]|head[\s>]|body[\s>])/i.test(head);
110
+ }
92
111
  /** Text files essentially never contain a NUL byte; binary files essentially always do. */
93
112
  function looksLikeText(bytes) {
94
113
  const sample = bytes.subarray(0, Math.min(bytes.length, 8192));
@@ -130,19 +149,23 @@ function detectDocumentType(bytes, fileName) {
130
149
  if (looksLikeText(bytes)) {
131
150
  // Text is recognised by its content, so a file with no extension or an
132
151
  // unusual one still reads. The extension list only decides what a binary
133
- // file with a text extension is: nothing readable.
152
+ // file with a text extension is: nothing readable. HTML is text too, and
153
+ // read as a page rather than as its source: named .html, or opening like one.
154
+ if (HTML_EXTENSIONS.has(extension) || looksLikeHtml(bytes)) {
155
+ return { type: 'html' };
156
+ }
134
157
  return { type: 'text' };
135
158
  }
136
- if (TEXT_EXTENSIONS.has(extension)) {
159
+ if (TEXT_EXTENSIONS.has(extension) || HTML_EXTENSIONS.has(extension)) {
137
160
  return { type: 'unsupported', reason: `"${fileName}" is named as a text file but contains binary data.` };
138
161
  }
139
162
  return {
140
163
  type: 'unsupported',
141
- reason: `"${fileName}" is not a file type that can be read. PDF, Word (.docx), Excel (.xlsx) and plain text are supported.`,
164
+ reason: `"${fileName}" is not a file type that can be read. PDF, Word (.docx), Excel (.xlsx), HTML and plain text are supported.`,
142
165
  };
143
166
  }
144
167
  /**
145
- * Converts a Word, Excel or plain-text file to Markdown pages, locally.
168
+ * Converts a Word, Excel, HTML or plain-text file to Markdown pages, locally.
146
169
  *
147
170
  * @throws {UnsupportedDocumentError} For a PDF (which needs the AI path) or anything unreadable
148
171
  */
@@ -156,12 +179,16 @@ async function convertLocalDocument(bytes, fileName, options = {}) {
156
179
  }
157
180
  let pages;
158
181
  let warnings;
182
+ let dataBlocks;
159
183
  if (detection.type === 'docx') {
160
184
  ({ pages, warnings } = await convertDocx(bytes));
161
185
  }
162
186
  else if (detection.type === 'xlsx') {
163
187
  ({ pages, warnings } = await convertXlsx(bytes, options.maxRowsPerSheet ?? DEFAULT_MAX_ROWS_PER_SHEET));
164
188
  }
189
+ else if (detection.type === 'html') {
190
+ ({ pages, warnings, dataBlocks } = convertHtml(bytes));
191
+ }
165
192
  else {
166
193
  const text = new TextDecoder('utf-8').decode(bytes).replace(/^/, '');
167
194
  pages = [{ pageNum: 1, markdown: text }];
@@ -170,7 +197,7 @@ async function convertLocalDocument(bytes, fileName, options = {}) {
170
197
  if (pages.every((page) => !page.markdown.trim())) {
171
198
  throw new UnsupportedDocumentError(`"${fileName}" contains no readable text.`);
172
199
  }
173
- return { type: detection.type, pages, markdown: assemble(pages), warnings };
200
+ return { type: detection.type, pages, markdown: assemble(pages), warnings, ...(dataBlocks?.length ? { dataBlocks } : {}) };
174
201
  }
175
202
  function assemble(pages) {
176
203
  return pages.map((page) => `${(0, pdf_conversion_1.pageMarker)(page.pageNum)}\n${page.markdown}\n`).join('\n');
@@ -205,6 +232,8 @@ function htmlToMarkdown(html) {
205
232
  bulletListMarker: '-',
206
233
  emDelimiter: '*',
207
234
  });
235
+ // Never text a reader sees. Word's HTML has none of these; a web page has all of them.
236
+ turndown.remove(['script', 'style', 'template', 'svg', 'canvas', 'iframe', 'object', 'embed', 'head', 'title']);
208
237
  turndown.addRule('image', {
209
238
  filter: 'img',
210
239
  replacement: (_content, node) => {
@@ -229,6 +258,98 @@ function htmlToMarkdown(html) {
229
258
  return turndown.turndown(html);
230
259
  }
231
260
  // ---------------------------------------------------------------------------
261
+ // HTML
262
+ // ---------------------------------------------------------------------------
263
+ /** Embedded data longer than this is cut, and the cut is stated. */
264
+ const MAX_HTML_DATA_CHARS = 300_000;
265
+ function kilobytes(chars) {
266
+ return `${Math.max(1, Math.round(chars / 1024))} KB`;
267
+ }
268
+ /**
269
+ * An HTML page as Markdown: what it shows, and the data it carries.
270
+ *
271
+ * Page 1 is the page's title and visible text. Its scripts and styles are left
272
+ * out — they are code, not content — and `warnings` says how much was dropped.
273
+ *
274
+ * A modern page often draws everything from data embedded in it, in
275
+ * `<script type="application/json">` blocks, and shows almost no text of its own
276
+ * without its scripts. That data IS the content, so each block comes back as its
277
+ * own labelled page, laid out a record per line so it chunks and searches well.
278
+ * Page 1 ends with an "About this page" note listing the blocks and their shape,
279
+ * so a reader knows the page is built from data and where that data is — the
280
+ * first thing an agent needs to see a page as a template it could refill.
281
+ */
282
+ function convertHtml(bytes) {
283
+ const html = new TextDecoder('utf-8').decode(bytes).replace(/^\uFEFF/, '');
284
+ const warnings = [];
285
+ const blocks = (0, html_data_1.findDataBlocks)(html);
286
+ const code = (0, html_data_1.findCodeScripts)(html);
287
+ const scriptCount = code.length;
288
+ const scriptChars = code.reduce((sum, script) => sum + script.body.length, 0);
289
+ let styleChars = 0;
290
+ const page = (0, html_data_1.withoutScripts)(html).replace(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi, (_match, body) => {
291
+ styleChars += body.length;
292
+ return '';
293
+ });
294
+ const titleMatch = page.match(/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i);
295
+ const title = titleMatch ? htmlToMarkdown(`<p>${titleMatch[1]}</p>`).trim() : '';
296
+ const bodyMatch = page.match(/<body\b[^>]*>([\s\S]*)<\/body\s*>/i);
297
+ const body = htmlToMarkdown(bodyMatch ? bodyMatch[1] : page.replace(/<head\b[\s\S]*?<\/head\s*>/i, '')).trim();
298
+ if (!body && !blocks.length) {
299
+ return { pages: [{ pageNum: 1, markdown: '' }], warnings, dataBlocks: [] };
300
+ }
301
+ if (scriptCount) {
302
+ warnings.push(`${scriptCount} script(s) (${kilobytes(scriptChars)}) were left out; anything the page draws with them is not in the text.`);
303
+ }
304
+ if (styleChars) {
305
+ warnings.push(`Styles (${kilobytes(styleChars)}) were left out.`);
306
+ }
307
+ const dataBlocks = blocks.map((block) => ({
308
+ label: block.label,
309
+ type: block.type,
310
+ chars: block.text.length,
311
+ shape: block.value === undefined ? 'not valid JSON' : (0, html_data_1.describeShape)(block.value),
312
+ }));
313
+ const dataPages = blocks.map((block, index) => {
314
+ let content = block.value === undefined ? block.text : (0, html_data_1.readableJson)(block.value);
315
+ let note = block.value === undefined ? ' It is not valid JSON, so it is shown as it is.' : '';
316
+ if (content.length > MAX_HTML_DATA_CHARS) {
317
+ content = content.slice(0, MAX_HTML_DATA_CHARS);
318
+ note += ` It is cut at ${kilobytes(MAX_HTML_DATA_CHARS)}; the rest is not shown.`;
319
+ warnings.push(`The embedded data "${block.label}" was cut at ${kilobytes(MAX_HTML_DATA_CHARS)}.`);
320
+ }
321
+ const tag = `<script type="${block.type}"${block.id ? ` id="${block.id}"` : ''}>`;
322
+ return {
323
+ pageNum: index + 2,
324
+ label: `Embedded data: ${block.label}`,
325
+ markdown: `## Embedded data: ${block.label}\n\n` +
326
+ `The page's \`${tag}\` block (${kilobytes(block.text.length)}): data its scripts display.${note}\n\n` +
327
+ '```json\n' + content + '\n```',
328
+ };
329
+ });
330
+ const about = [];
331
+ if (scriptCount || styleChars || blocks.length) {
332
+ about.push('---', '', '**About this page.** It is an HTML page.');
333
+ if (scriptCount) {
334
+ about.push(`It has ${scriptCount} script(s) (${kilobytes(scriptChars)}) that are not shown here, so whatever it draws with them ` +
335
+ `(charts, tables, slides) appears only as the data below.`);
336
+ }
337
+ if (blocks.length) {
338
+ about.push('', 'It carries its data in these blocks, each on its own page:', '');
339
+ dataBlocks.forEach((block, index) => {
340
+ about.push(`- \`${block.label}\` (page ${index + 2}, ${kilobytes(block.chars)}): ${block.shape}`);
341
+ });
342
+ if (scriptCount) {
343
+ about.push('', 'Because its scripts draw it from this data, the page can serve as a template: another page ' +
344
+ 'like it is made by replacing the data and keeping the scripts.');
345
+ }
346
+ }
347
+ }
348
+ const shown = body || '*(Without its scripts, the page shows no text of its own.)*';
349
+ const firstPage = [title ? `# ${title}` : '', shown, about.join('\n')].filter(Boolean).join('\n\n');
350
+ return { pages: [{ pageNum: 1, markdown: firstPage }, ...dataPages], warnings, dataBlocks };
351
+ }
352
+ // ---------------------------------------------------------------------------
232
353
  // Excel
233
354
  // ---------------------------------------------------------------------------
234
355
  async function loadWorkbook(bytes) {