@project-ava-supernova/core 0.2.182 → 0.2.184
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/agent/agent.d.ts.map +1 -1
- package/dist/agent/agent.js +32 -24
- package/dist/agent/agent.js.map +1 -1
- package/dist/agent/system-prompt.d.ts.map +1 -1
- package/dist/agent/system-prompt.js +12 -5
- package/dist/agent/system-prompt.js.map +1 -1
- package/dist/docs/content/concepts.js +1 -1
- package/dist/docs/content/concepts.js.map +1 -1
- package/dist/docs/content/features.d.ts.map +1 -1
- package/dist/docs/content/features.js +16 -9
- package/dist/docs/content/features.js.map +1 -1
- package/dist/docs/content/start.d.ts.map +1 -1
- package/dist/docs/content/start.js +1 -0
- package/dist/docs/content/start.js.map +1 -1
- package/dist/docs/data/tools.js +4 -4
- package/dist/docs/data/tools.js.map +1 -1
- package/dist/docs/i18n/translations.d.ts.map +1 -1
- package/dist/docs/i18n/translations.js +1 -1
- package/dist/docs/i18n/translations.js.map +1 -1
- package/dist/health/progression.d.ts +68 -0
- package/dist/health/progression.d.ts.map +1 -0
- package/dist/health/progression.js +205 -0
- package/dist/health/progression.js.map +1 -0
- package/dist/health/share-results.d.ts +45 -0
- package/dist/health/share-results.d.ts.map +1 -0
- package/dist/health/share-results.js +123 -0
- package/dist/health/share-results.js.map +1 -0
- package/dist/health/share-workout.d.ts +55 -0
- package/dist/health/share-workout.d.ts.map +1 -0
- package/dist/health/share-workout.js +69 -0
- package/dist/health/share-workout.js.map +1 -0
- package/dist/i18n/locales/ar.d.ts.map +1 -1
- package/dist/i18n/locales/ar.js +104 -0
- package/dist/i18n/locales/ar.js.map +1 -1
- package/dist/i18n/locales/de.d.ts.map +1 -1
- package/dist/i18n/locales/de.js +104 -0
- package/dist/i18n/locales/de.js.map +1 -1
- package/dist/i18n/locales/en.d.ts +104 -0
- package/dist/i18n/locales/en.d.ts.map +1 -1
- package/dist/i18n/locales/en.js +114 -0
- package/dist/i18n/locales/en.js.map +1 -1
- package/dist/i18n/locales/es.d.ts.map +1 -1
- package/dist/i18n/locales/es.js +104 -0
- package/dist/i18n/locales/es.js.map +1 -1
- package/dist/i18n/locales/fr.d.ts.map +1 -1
- package/dist/i18n/locales/fr.js +104 -0
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/hi.d.ts.map +1 -1
- package/dist/i18n/locales/hi.js +104 -0
- package/dist/i18n/locales/hi.js.map +1 -1
- package/dist/i18n/locales/id.d.ts.map +1 -1
- package/dist/i18n/locales/id.js +104 -0
- package/dist/i18n/locales/id.js.map +1 -1
- package/dist/i18n/locales/it.d.ts.map +1 -1
- package/dist/i18n/locales/it.js +104 -0
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/i18n/locales/ja.d.ts.map +1 -1
- package/dist/i18n/locales/ja.js +104 -0
- package/dist/i18n/locales/ja.js.map +1 -1
- package/dist/i18n/locales/ko.d.ts.map +1 -1
- package/dist/i18n/locales/ko.js +104 -0
- package/dist/i18n/locales/ko.js.map +1 -1
- package/dist/i18n/locales/nl.d.ts.map +1 -1
- package/dist/i18n/locales/nl.js +104 -0
- package/dist/i18n/locales/nl.js.map +1 -1
- package/dist/i18n/locales/pl.d.ts.map +1 -1
- package/dist/i18n/locales/pl.js +104 -0
- package/dist/i18n/locales/pl.js.map +1 -1
- package/dist/i18n/locales/pt.d.ts.map +1 -1
- package/dist/i18n/locales/pt.js +104 -0
- package/dist/i18n/locales/pt.js.map +1 -1
- package/dist/i18n/locales/ru.d.ts.map +1 -1
- package/dist/i18n/locales/ru.js +104 -0
- package/dist/i18n/locales/ru.js.map +1 -1
- package/dist/i18n/locales/th.d.ts.map +1 -1
- package/dist/i18n/locales/th.js +104 -0
- package/dist/i18n/locales/th.js.map +1 -1
- package/dist/i18n/locales/tr.d.ts.map +1 -1
- package/dist/i18n/locales/tr.js +104 -0
- package/dist/i18n/locales/tr.js.map +1 -1
- package/dist/i18n/locales/uk.d.ts.map +1 -1
- package/dist/i18n/locales/uk.js +104 -0
- package/dist/i18n/locales/uk.js.map +1 -1
- package/dist/i18n/locales/vi.d.ts.map +1 -1
- package/dist/i18n/locales/vi.js +104 -0
- package/dist/i18n/locales/vi.js.map +1 -1
- package/dist/i18n/locales/zh-CN.d.ts.map +1 -1
- package/dist/i18n/locales/zh-CN.js +104 -0
- package/dist/i18n/locales/zh-CN.js.map +1 -1
- package/dist/i18n/locales/zh-TW.d.ts.map +1 -1
- package/dist/i18n/locales/zh-TW.js +104 -0
- package/dist/i18n/locales/zh-TW.js.map +1 -1
- package/dist/tools/authoring/doc-model.d.ts +2 -11
- package/dist/tools/authoring/doc-model.d.ts.map +1 -1
- package/dist/tools/authoring/doc-model.js +2 -39
- package/dist/tools/authoring/doc-model.js.map +1 -1
- package/dist/tools/authoring/document-places.d.ts +19 -0
- package/dist/tools/authoring/document-places.d.ts.map +1 -0
- package/dist/tools/authoring/document-places.js +24 -0
- package/dist/tools/authoring/document-places.js.map +1 -0
- package/dist/tools/authoring/export-document.d.ts +10 -0
- package/dist/tools/authoring/export-document.d.ts.map +1 -1
- package/dist/tools/authoring/export-document.js +26 -0
- package/dist/tools/authoring/export-document.js.map +1 -1
- package/dist/tools/authoring/font-manifest.d.ts +25 -0
- package/dist/tools/authoring/font-manifest.d.ts.map +1 -0
- package/dist/tools/authoring/font-manifest.js +35 -0
- package/dist/tools/authoring/font-manifest.js.map +1 -0
- package/dist/tools/authoring/formula-eval.d.ts +34 -0
- package/dist/tools/authoring/formula-eval.d.ts.map +1 -0
- package/dist/tools/authoring/formula-eval.js +250 -0
- package/dist/tools/authoring/formula-eval.js.map +1 -0
- package/dist/tools/authoring/index.d.ts +0 -1
- package/dist/tools/authoring/index.d.ts.map +1 -1
- package/dist/tools/authoring/index.js +2 -3
- package/dist/tools/authoring/index.js.map +1 -1
- package/dist/tools/authoring/ods-spreadsheet.d.ts +56 -0
- package/dist/tools/authoring/ods-spreadsheet.d.ts.map +1 -0
- package/dist/tools/authoring/ods-spreadsheet.js +426 -0
- package/dist/tools/authoring/ods-spreadsheet.js.map +1 -0
- package/dist/tools/authoring/pdf-fonts.d.ts +53 -0
- package/dist/tools/authoring/pdf-fonts.d.ts.map +1 -0
- package/dist/tools/authoring/pdf-fonts.js +269 -0
- package/dist/tools/authoring/pdf-fonts.js.map +1 -0
- package/dist/tools/authoring/read-office.d.ts +29 -0
- package/dist/tools/authoring/read-office.d.ts.map +1 -0
- package/dist/tools/authoring/read-office.js +48 -0
- package/dist/tools/authoring/read-office.js.map +1 -0
- package/dist/tools/authoring/render-pdf.d.ts.map +1 -1
- package/dist/tools/authoring/render-pdf.js +136 -7
- package/dist/tools/authoring/render-pdf.js.map +1 -1
- package/dist/tools/authoring/sheet-view.d.ts +32 -0
- package/dist/tools/authoring/sheet-view.d.ts.map +1 -0
- package/dist/tools/authoring/sheet-view.js +122 -0
- package/dist/tools/authoring/sheet-view.js.map +1 -0
- package/dist/tools/authoring/spreadsheet.d.ts +69 -0
- package/dist/tools/authoring/spreadsheet.d.ts.map +1 -0
- package/dist/tools/authoring/spreadsheet.js +216 -0
- package/dist/tools/authoring/spreadsheet.js.map +1 -0
- package/dist/tools/authoring/templates/builtins.d.ts.map +1 -1
- package/dist/tools/authoring/templates/builtins.js +2 -0
- package/dist/tools/authoring/templates/builtins.js.map +1 -1
- package/dist/tools/authoring/xlsx-charts.d.ts +66 -0
- package/dist/tools/authoring/xlsx-charts.d.ts.map +1 -0
- package/dist/tools/authoring/xlsx-charts.js +272 -0
- package/dist/tools/authoring/xlsx-charts.js.map +1 -0
- package/dist/tools/authoring/zip.d.ts +6 -0
- package/dist/tools/authoring/zip.d.ts.map +1 -1
- package/dist/tools/authoring/zip.js +45 -1
- package/dist/tools/authoring/zip.js.map +1 -1
- package/dist/tools/document-author.d.ts +4 -0
- package/dist/tools/document-author.d.ts.map +1 -1
- package/dist/tools/document-author.js +36 -24
- package/dist/tools/document-author.js.map +1 -1
- package/dist/tools/document-manage.d.ts +28 -25
- package/dist/tools/document-manage.d.ts.map +1 -1
- package/dist/tools/document-manage.js +298 -586
- package/dist/tools/document-manage.js.map +1 -1
- package/dist/tools/document-styling.d.ts +0 -26
- package/dist/tools/document-styling.d.ts.map +1 -1
- package/dist/tools/document-styling.js +0 -224
- package/dist/tools/document-styling.js.map +1 -1
- package/dist/tools/document-templates.d.ts +3 -18
- package/dist/tools/document-templates.d.ts.map +1 -1
- package/dist/tools/document-templates.js +4 -94
- package/dist/tools/document-templates.js.map +1 -1
- package/dist/tools/email-draft.d.ts +3 -6
- package/dist/tools/email-draft.d.ts.map +1 -1
- package/dist/tools/email-draft.js +29 -123
- package/dist/tools/email-draft.js.map +1 -1
- package/dist/tools/report-generate.d.ts +1 -2
- package/dist/tools/report-generate.d.ts.map +1 -1
- package/dist/tools/report-generate.js +50 -167
- package/dist/tools/report-generate.js.map +1 -1
- package/package.json +27 -5
|
@@ -1,665 +1,377 @@
|
|
|
1
1
|
import { readFile, writeFile, mkdir } from 'node:fs/promises';
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { dirname, extname } from 'node:path';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { validatePath } from './security.js';
|
|
5
|
+
import { readPdfText, readDocxText, unreadable } from './authoring/read-office.js';
|
|
6
|
+
import { documentPathFor } from './authoring/document-places.js';
|
|
7
|
+
import { exportDocument, parseCsv } from './authoring/export-document.js';
|
|
8
|
+
import { buildWorkbook, updateCells, recalculate, workbookBytes, chartCellsOf } from './authoring/spreadsheet.js';
|
|
9
|
+
import { readCharts } from './authoring/xlsx-charts.js';
|
|
10
|
+
import { workbookToOds, readOds, odsToSheetSpec } from './authoring/ods-spreadsheet.js';
|
|
11
|
+
import { readSheetForView } from './authoring/sheet-view.js';
|
|
12
|
+
/** Chart specs with ranges that ended just above inserted rows stretched over them. */
|
|
13
|
+
function stretchCharts(charts, inserted) {
|
|
14
|
+
return shiftCharts(charts.map((x) => ({ sheet: x.sheet, charts: x.charts.map((c) => ({ ...c, labels: [], data: [], colours: [] })) })), inserted);
|
|
15
|
+
}
|
|
16
|
+
/** Charts read back, with ranges that ended just above inserted rows stretched over them. */
|
|
17
|
+
function shiftCharts(found, inserted) {
|
|
18
|
+
const stretch = (range) => {
|
|
19
|
+
if (!inserted)
|
|
20
|
+
return range;
|
|
21
|
+
return range.replace(/^([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)$/i, (m, c1, r1, c2, r2) => Number(r2) === inserted.at - 1 ? `${c1}${r1}:${c2}${Number(r2) + inserted.count}` : m);
|
|
22
|
+
};
|
|
23
|
+
return found.map(({ sheet, charts }) => ({
|
|
24
|
+
sheet,
|
|
25
|
+
charts: charts.map((c) => ({ type: c.type, title: c.title, at: c.at, categories: stretch(c.categories), series: c.series.map((x) => ({ name: x.name, values: stretch(x.values) })) })),
|
|
26
|
+
}));
|
|
27
|
+
}
|
|
28
|
+
import { loadHouseStyle } from './authoring/templates/index.js';
|
|
29
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
30
|
+
/**
|
|
31
|
+
* Spreadsheets and CSV — ONE job (14 Nov 2026).
|
|
32
|
+
*
|
|
33
|
+
* This tool used to make Word and PDF files too, with a second, simpler
|
|
34
|
+
* engine than document_author's (it dropped bold, tables and callouts), and
|
|
35
|
+
* it offered a ".docx edit" that rebuilt the file from plain text and threw
|
|
36
|
+
* its formatting away. Prose documents now belong to document_author alone;
|
|
37
|
+
* this tool makes and changes spreadsheets, and reads any document so Ava can
|
|
38
|
+
* use what is in it.
|
|
39
|
+
*/
|
|
6
40
|
export class DocumentManageTool {
|
|
7
41
|
name = 'document_manage';
|
|
8
|
-
description = '
|
|
42
|
+
description = 'Make and change spreadsheets (.xlsx) and CSV files; read any document (Word, PDF, spreadsheet, text).';
|
|
9
43
|
riskLevel = 'write';
|
|
10
44
|
requiresConfirmation = true;
|
|
11
45
|
schema = {
|
|
12
46
|
name: 'document_manage',
|
|
13
|
-
description: '
|
|
14
|
-
'
|
|
15
|
-
'
|
|
16
|
-
'
|
|
47
|
+
description: 'Spreadsheets and CSV: create a spreadsheet (.xlsx, or .ods — the open format, with everything in it) or CSV, add rows, change cells, read one, or export between them (xlsx ↔ ods keeps formulas, formats and charts). '
|
|
48
|
+
+ 'Spreadsheets are real: give numbers as numbers, use formulas as text starting with "=" ("=B2*12", "=SUM(B2:B9)"), '
|
|
49
|
+
+ 'set a format per column (currency, percent, date, integer, number, text) and ask for a totals row — Ava works out the results so they read back correctly. '
|
|
50
|
+
+ 'Also reads the text of any document (.docx, .pdf, .md, .txt). '
|
|
51
|
+
+ 'For prose documents — reports, letters, proposals, Word or PDF files — use document_author instead. '
|
|
52
|
+
+ 'A bare file name ("budget.xlsx") is saved in the project\'s documents/ folder, where the Library shows it.',
|
|
17
53
|
parameters: {
|
|
18
54
|
type: 'object',
|
|
19
55
|
properties: {
|
|
20
56
|
action: {
|
|
21
57
|
type: 'string',
|
|
22
|
-
enum: ['create', 'edit', '
|
|
23
|
-
description: '
|
|
24
|
-
},
|
|
25
|
-
file_path: {
|
|
26
|
-
type: 'string',
|
|
27
|
-
description: 'Path for the document (required for create, edit, read, export)',
|
|
28
|
-
},
|
|
29
|
-
format: {
|
|
30
|
-
type: 'string',
|
|
31
|
-
enum: ['docx', 'xlsx', 'pdf', 'csv', 'md'],
|
|
32
|
-
description: 'Document format (auto-detected from file extension if not specified)',
|
|
58
|
+
enum: ['create', 'edit', 'update_cells', 'read', 'export'],
|
|
59
|
+
description: 'create (new spreadsheet / CSV) · edit (add rows; above a totals row, which keeps adding up) · update_cells (change cells by reference) · read (any document, formulas shown) · export (csv ↔ xlsx, or a CSV to ods / pdf / docx)',
|
|
33
60
|
},
|
|
61
|
+
file_path: { type: 'string', description: 'Path of the spreadsheet or document.' },
|
|
34
62
|
content: {
|
|
35
63
|
type: 'object',
|
|
36
|
-
description: '
|
|
37
|
-
},
|
|
38
|
-
template: {
|
|
39
|
-
type: 'string',
|
|
40
|
-
enum: [...TEMPLATES],
|
|
41
|
-
description: 'Template name for from_template action',
|
|
42
|
-
},
|
|
43
|
-
template_data: {
|
|
44
|
-
type: 'object',
|
|
45
|
-
description: 'Data to fill the template with',
|
|
46
|
-
},
|
|
47
|
-
export_format: {
|
|
48
|
-
type: 'string',
|
|
49
|
-
enum: ['docx', 'xlsx', 'pdf', 'csv', 'md'],
|
|
50
|
-
description: 'Target format for export action',
|
|
51
|
-
},
|
|
52
|
-
export_path: {
|
|
53
|
-
type: 'string',
|
|
54
|
-
description: 'Output path for export action',
|
|
64
|
+
description: 'xlsx: { sheets: [{ name, headers, rows, columns?: [{ format?: "text"|"number"|"integer"|"currency"|"percent"|"date", currency?: "GBP"|"USD"|"EUR" }], totals?: { label?, columns: ["Monthly", …] (header names or letters) }, freeze?: true, charts?: [{ type: "column"|"bar"|"line"|"pie", title?, categories: "A2:A6", series: [{ name, values: "B2:B6" }], at?: "E2" }] }] }. Charts are real Excel charts and stay through later edits. Dates as "2026-11-15". csv: { headers, rows }. edit: the rows to add, same shape.',
|
|
55
65
|
},
|
|
66
|
+
sheet: { type: 'string', description: 'update_cells: the sheet name (default: the first sheet).' },
|
|
67
|
+
cells: { type: 'object', description: 'update_cells: cell references to values — { "B4": 950, "C7": "=SUM(C2:C6)", "A9": "Insurance" }.' },
|
|
68
|
+
export_format: { type: 'string', enum: ['xlsx', 'csv', 'ods', 'pdf', 'docx'], description: 'export: the format to make.' },
|
|
69
|
+
export_path: { type: 'string', description: 'export: where to write it (otherwise beside the source).' },
|
|
56
70
|
},
|
|
57
71
|
required: ['action'],
|
|
58
72
|
},
|
|
59
73
|
};
|
|
60
74
|
async execute(args, context) {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
75
|
+
try {
|
|
76
|
+
switch (args.action) {
|
|
77
|
+
case 'create': return await this.handleCreate(args, context);
|
|
78
|
+
case 'edit': return await this.handleEdit(args, context);
|
|
79
|
+
case 'update_cells': return await this.handleUpdateCells(args, context);
|
|
80
|
+
case 'read': return await this.handleRead(args, context);
|
|
81
|
+
case 'export': return await this.handleExport(args, context);
|
|
82
|
+
default:
|
|
83
|
+
return { success: false, output: `Unknown action: ${String(args.action)}. For Word or PDF documents use document_author.` };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
return { success: false, output: e.message };
|
|
71
88
|
}
|
|
72
89
|
}
|
|
90
|
+
// ── Paths ──────────────────────────────────────────────────────────────────
|
|
91
|
+
/** Inside the project only; a bare name for something NEW goes to documents/. */
|
|
92
|
+
target(given, cwd, isNew) {
|
|
93
|
+
if (!given)
|
|
94
|
+
throw new Error('Missing required field: file_path');
|
|
95
|
+
const direct = validatePath(given, cwd);
|
|
96
|
+
if (/[\\/]/.test(given.trim()))
|
|
97
|
+
return direct;
|
|
98
|
+
const inDocs = validatePath(documentPathFor(given), cwd);
|
|
99
|
+
if (isNew)
|
|
100
|
+
return inDocs;
|
|
101
|
+
return existsSync(direct) ? direct : inDocs;
|
|
102
|
+
}
|
|
103
|
+
formatOf(path) {
|
|
104
|
+
return extname(path).toLowerCase().replace('.', '');
|
|
105
|
+
}
|
|
73
106
|
// ── Create ─────────────────────────────────────────────────────────────────
|
|
74
107
|
async handleCreate(args, context) {
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (!format)
|
|
80
|
-
return { success: false, output: 'Cannot determine format. Specify format or use a known extension (.docx, .xlsx, .pdf, .csv, .md)' };
|
|
81
|
-
const content = args.content;
|
|
82
|
-
const fullPath = this.resolvePath(filePath, context.cwd);
|
|
83
|
-
await mkdir(dirname(fullPath), { recursive: true });
|
|
84
|
-
switch (format) {
|
|
85
|
-
case 'csv': return this.createCsv(fullPath, content);
|
|
86
|
-
case 'md': return this.createMarkdown(fullPath, content);
|
|
87
|
-
case 'docx': return this.createDocx(fullPath, content);
|
|
88
|
-
case 'xlsx': return this.createXlsx(fullPath, content);
|
|
89
|
-
case 'pdf': return this.createPdf(fullPath, content);
|
|
90
|
-
default: return { success: false, output: `Unsupported format: ${format}` };
|
|
108
|
+
const fullPath = this.target(args.file_path, context.cwd, true);
|
|
109
|
+
const format = this.formatOf(fullPath);
|
|
110
|
+
if (format !== 'xlsx' && format !== 'ods' && format !== 'csv') {
|
|
111
|
+
return { success: false, output: `document_manage makes spreadsheets (.xlsx, .ods) and CSV files. For a ${format ? `.${format}` : ''} document use document_author.` };
|
|
91
112
|
}
|
|
113
|
+
if (existsSync(fullPath))
|
|
114
|
+
return { success: false, output: `File already exists: ${fullPath}. Use edit to add rows.` };
|
|
115
|
+
await mkdir(dirname(fullPath), { recursive: true });
|
|
116
|
+
const content = args.content;
|
|
117
|
+
return format === 'csv'
|
|
118
|
+
? this.createCsv(fullPath, content)
|
|
119
|
+
: this.createBook(fullPath, content);
|
|
92
120
|
}
|
|
93
|
-
// ── Edit
|
|
121
|
+
// ── Edit (add rows) ──────────────────────────────────────────────────────────
|
|
94
122
|
async handleEdit(args, context) {
|
|
95
|
-
const
|
|
96
|
-
if (!filePath)
|
|
97
|
-
return { success: false, output: 'Missing required field: file_path' };
|
|
98
|
-
const fullPath = this.resolvePath(filePath, context.cwd);
|
|
123
|
+
const fullPath = this.target(args.file_path, context.cwd, false);
|
|
99
124
|
if (!existsSync(fullPath))
|
|
100
|
-
return { success: false, output: `File not found: ${
|
|
101
|
-
const format = this.
|
|
125
|
+
return { success: false, output: `File not found: ${fullPath}` };
|
|
126
|
+
const format = this.formatOf(fullPath);
|
|
102
127
|
const content = args.content;
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
case 'pdf': return { success: false, output: 'PDFs cannot be edited directly. Recreate the document or edit the source format.' };
|
|
109
|
-
default: return { success: false, output: `Unsupported format for editing: ${format}` };
|
|
110
|
-
}
|
|
128
|
+
if (format === 'csv')
|
|
129
|
+
return this.editCsv(fullPath, content);
|
|
130
|
+
if (format === 'xlsx' || format === 'ods')
|
|
131
|
+
return this.editBook(fullPath, content);
|
|
132
|
+
return { success: false, output: `document_manage edits spreadsheets and CSV files. To change a ${format} document use document_author (edit_section).` };
|
|
111
133
|
}
|
|
112
|
-
// ── Read
|
|
134
|
+
// ── Read (any document) ──────────────────────────────────────────────────────
|
|
113
135
|
async handleRead(args, context) {
|
|
114
|
-
const
|
|
115
|
-
if (!filePath)
|
|
116
|
-
return { success: false, output: 'Missing required field: file_path' };
|
|
117
|
-
const fullPath = this.resolvePath(filePath, context.cwd);
|
|
136
|
+
const fullPath = this.target(args.file_path, context.cwd, false);
|
|
118
137
|
if (!existsSync(fullPath))
|
|
119
|
-
return { success: false, output: `File not found: ${
|
|
120
|
-
const format = this.
|
|
138
|
+
return { success: false, output: `File not found: ${fullPath}` };
|
|
139
|
+
const format = this.formatOf(fullPath);
|
|
121
140
|
switch (format) {
|
|
122
141
|
case 'csv': return this.readCsv(fullPath);
|
|
123
|
-
case '
|
|
124
|
-
case '
|
|
125
|
-
case '
|
|
126
|
-
|
|
127
|
-
|
|
142
|
+
case 'xlsx':
|
|
143
|
+
case 'ods': return this.readBook(fullPath);
|
|
144
|
+
case 'docx':
|
|
145
|
+
try {
|
|
146
|
+
const r = await readDocxText(fullPath);
|
|
147
|
+
return { success: true, output: `Word document: ${fullPath}\n\n${r.text.slice(0, 6000)}${r.text.length > 6000 ? '\n… truncated' : ''}` };
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
return { success: false, output: unreadable('Word', fullPath, e) };
|
|
151
|
+
}
|
|
152
|
+
case 'pdf':
|
|
153
|
+
try {
|
|
154
|
+
const r = await readPdfText(await readFile(fullPath));
|
|
155
|
+
return { success: true, output: `PDF: ${fullPath}${r.pages ? ` (${r.pages} pages)` : ''}\n\n${r.text.slice(0, 6000)}${r.text.length > 6000 ? '\n… truncated' : ''}` };
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
return { success: false, output: unreadable('PDF', fullPath, e) };
|
|
159
|
+
}
|
|
160
|
+
default: {
|
|
161
|
+
const raw = await readFile(fullPath, 'utf-8');
|
|
162
|
+
return { success: true, output: `${fullPath}\n\n${raw.slice(0, 6000)}${raw.length > 6000 ? '\n… truncated' : ''}` };
|
|
163
|
+
}
|
|
128
164
|
}
|
|
129
165
|
}
|
|
130
|
-
// ── Export
|
|
166
|
+
// ── Export ───────────────────────────────────────────────────────────────────
|
|
131
167
|
async handleExport(args, context) {
|
|
132
|
-
const
|
|
133
|
-
const exportFormat = args.export_format;
|
|
134
|
-
const exportPath = args.export_path;
|
|
135
|
-
if (!filePath)
|
|
136
|
-
return { success: false, output: 'Missing required field: file_path' };
|
|
137
|
-
if (!exportFormat)
|
|
138
|
-
return { success: false, output: 'Missing required field: export_format' };
|
|
139
|
-
const fullPath = this.resolvePath(filePath, context.cwd);
|
|
168
|
+
const fullPath = this.target(args.file_path, context.cwd, false);
|
|
140
169
|
if (!existsSync(fullPath))
|
|
141
|
-
return { success: false, output: `File not found: ${
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
170
|
+
return { success: false, output: `File not found: ${fullPath}` };
|
|
171
|
+
const to = String(args.export_format ?? '');
|
|
172
|
+
if (!to)
|
|
173
|
+
return { success: false, output: 'Missing required field: export_format' };
|
|
174
|
+
const from = this.formatOf(fullPath);
|
|
175
|
+
const outPath = args.export_path
|
|
176
|
+
? validatePath(args.export_path, context.cwd)
|
|
177
|
+
: fullPath.replace(new RegExp(`\\.${from}$`, 'i'), `.${to}`);
|
|
146
178
|
await mkdir(dirname(outPath), { recursive: true });
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
if (exportFormat === 'md') {
|
|
176
|
-
// Any → Markdown: use the read output as content
|
|
177
|
-
await writeFile(outPath, readResult.output, 'utf-8');
|
|
178
|
-
return { success: true, output: `Exported ${filePath} → ${outPath} (${sourceFormat} → md)` };
|
|
179
|
-
}
|
|
180
|
-
return { success: false, output: `Export from ${sourceFormat} to ${exportFormat} is not supported.` };
|
|
181
|
-
}
|
|
182
|
-
// ── Templates ──────────────────────────────────────────────────────────────
|
|
183
|
-
handleListTemplates() {
|
|
184
|
-
const lines = TEMPLATES.map(t => `- **${t}**`);
|
|
185
|
-
return {
|
|
186
|
-
success: true,
|
|
187
|
-
output: `Available templates:\n${lines.join('\n')}\n\nUse action "from_template" with template name and optional template_data to create a document.`,
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
async handleFromTemplate(args, context) {
|
|
191
|
-
const template = args.template;
|
|
192
|
-
if (!template || !TEMPLATES.includes(template)) {
|
|
193
|
-
return { success: false, output: `Invalid template. Available: ${TEMPLATES.join(', ')}` };
|
|
194
|
-
}
|
|
195
|
-
const filePath = args.file_path;
|
|
196
|
-
if (!filePath)
|
|
197
|
-
return { success: false, output: 'Missing required field: file_path' };
|
|
198
|
-
const format = this.detectFormat(filePath, args.format) ?? 'md';
|
|
199
|
-
const templateData = args.template_data;
|
|
200
|
-
const content = getTemplate(template, templateData);
|
|
201
|
-
// Per-template styling profile (margins, cover page, footer flags) so a
|
|
202
|
-
// letter actually looks like a letter and an invoice like an invoice.
|
|
203
|
-
const profile = getStyleProfile(template);
|
|
204
|
-
const fullPath = this.resolvePath(filePath, context.cwd);
|
|
205
|
-
await mkdir(dirname(fullPath), { recursive: true });
|
|
206
|
-
switch (format) {
|
|
207
|
-
case 'md': return this.createMarkdown(fullPath, content);
|
|
208
|
-
case 'csv': {
|
|
209
|
-
// Convert first table in template to CSV
|
|
210
|
-
const table = content.sections.find(s => s.table)?.table;
|
|
211
|
-
if (table) {
|
|
212
|
-
return this.createCsv(fullPath, { headers: table.headers, rows: table.rows });
|
|
213
|
-
}
|
|
214
|
-
return { success: false, output: 'Template has no table data for CSV format.' };
|
|
215
|
-
}
|
|
216
|
-
case 'docx': return this.createDocx(fullPath, content, profile);
|
|
217
|
-
case 'xlsx': {
|
|
218
|
-
const table = content.sections.find(s => s.table)?.table;
|
|
219
|
-
if (table) {
|
|
220
|
-
return this.createXlsx(fullPath, { sheets: [{ name: 'Sheet1', headers: table.headers, rows: table.rows }] });
|
|
221
|
-
}
|
|
222
|
-
return { success: false, output: 'Template has no table data for XLSX format.' };
|
|
223
|
-
}
|
|
224
|
-
case 'pdf': return this.createPdf(fullPath, content, profile);
|
|
225
|
-
default: return { success: false, output: `Unsupported format for template: ${format}` };
|
|
179
|
+
if (from === 'csv' && (to === 'xlsx' || to === 'ods')) {
|
|
180
|
+
// A real spreadsheet: numbers become numbers, the header is styled.
|
|
181
|
+
const { headers, rows } = parseCsv(await readFile(fullPath, 'utf-8'));
|
|
182
|
+
const r = await this.createBook(outPath, { sheets: [{ name: 'Sheet1', headers, rows }] });
|
|
183
|
+
return r.success ? { success: true, output: `Exported ${fullPath} → ${outPath} (csv → ${to})` } : r;
|
|
184
|
+
}
|
|
185
|
+
if ((from === 'xlsx' || from === 'ods') && (to === 'xlsx' || to === 'ods') && from !== to) {
|
|
186
|
+
// Everything goes across: formulas, formats, totals and charts.
|
|
187
|
+
const { workbook, charts } = await this.loadBook(fullPath);
|
|
188
|
+
await this.saveBook(outPath, workbook, charts);
|
|
189
|
+
return { success: true, output: `Exported ${fullPath} → ${outPath} (${from} → ${to}, with formulas, formats and charts)` };
|
|
190
|
+
}
|
|
191
|
+
if ((from === 'xlsx' || from === 'ods') && to === 'csv') {
|
|
192
|
+
const sheets = await readSheetForView(fullPath);
|
|
193
|
+
const first = sheets[0] ?? { name: 'Sheet1', rows: [] };
|
|
194
|
+
const [head = [], ...body] = first.rows.map((r) => r.map((c) => c.v));
|
|
195
|
+
const r = await this.createCsv(outPath, { headers: head, rows: body });
|
|
196
|
+
const note = sheets.length > 1 ? ` Only the first sheet (${first.name}) — a CSV holds one table.` : '';
|
|
197
|
+
return r.success ? { success: true, output: `Exported ${fullPath} → ${outPath} (${from} → csv; values only).${note}` } : r;
|
|
198
|
+
}
|
|
199
|
+
if (from === 'csv' && (to === 'pdf' || to === 'docx')) {
|
|
200
|
+
const r = await exportDocument({
|
|
201
|
+
sourcePath: fullPath, format: to, outPath,
|
|
202
|
+
loadDocx: () => import('docx'),
|
|
203
|
+
// @ts-expect-error — pdfkit is an optional peer (types may be absent)
|
|
204
|
+
loadPdf: () => import('pdfkit'),
|
|
205
|
+
});
|
|
206
|
+
return r.ok ? { success: true, output: `Exported ${fullPath} → ${r.path} (csv → ${to})` } : { success: false, output: r.error };
|
|
226
207
|
}
|
|
208
|
+
return { success: false, output: `Export from ${from} to ${to} is not supported here. Spreadsheets: xlsx ↔ ods (everything), xlsx / ods → csv, csv → xlsx / ods / pdf / docx. Prose documents export with document_author build.` };
|
|
227
209
|
}
|
|
228
|
-
// ── CSV
|
|
210
|
+
// ── CSV ──────────────────────────────────────────────────────────────────────
|
|
229
211
|
async createCsv(filePath, content) {
|
|
230
212
|
const headers = content?.headers ?? [];
|
|
231
213
|
const rows = content?.rows ?? [];
|
|
232
|
-
const lines = [headers.map(h => this.csvEscape(h)).join(',')];
|
|
233
|
-
for (const row of rows)
|
|
234
|
-
lines.push(row.map(cell => this.csvEscape(String(cell))).join(','));
|
|
235
|
-
|
|
236
|
-
await writeFile(filePath, lines.join('\n'), 'utf-8');
|
|
214
|
+
const lines = [headers.map((h) => this.csvEscape(String(h))).join(',')];
|
|
215
|
+
for (const row of rows)
|
|
216
|
+
lines.push(row.map((cell) => this.csvEscape(String(cell ?? ''))).join(','));
|
|
217
|
+
await writeFile(filePath, lines.join('\n') + '\n', 'utf-8');
|
|
237
218
|
return { success: true, output: `Created CSV: ${filePath} (${rows.length} rows, ${headers.length} columns)` };
|
|
238
219
|
}
|
|
239
220
|
async readCsv(filePath) {
|
|
240
|
-
const
|
|
241
|
-
const
|
|
242
|
-
const
|
|
243
|
-
lines.push(parsed.headers.map(() => '---').join(' | '));
|
|
244
|
-
for (const row of parsed.rows.slice(0, 50)) {
|
|
221
|
+
const parsed = parseCsv(await readFile(filePath, 'utf-8'));
|
|
222
|
+
const lines = [parsed.headers.join(' | '), parsed.headers.map(() => '---').join(' | ')];
|
|
223
|
+
for (const row of parsed.rows.slice(0, 200))
|
|
245
224
|
lines.push(row.join(' | '));
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
return { success: true, output: `CSV: ${filePath} (${parsed.rows.length} rows)\n\n${lines.join('\n')}${truncated}` };
|
|
225
|
+
const more = parsed.rows.length > 200 ? `\n… and ${parsed.rows.length - 200} more rows` : '';
|
|
226
|
+
return { success: true, output: `CSV: ${filePath} (${parsed.rows.length} rows)\n\n${lines.join('\n')}${more}` };
|
|
249
227
|
}
|
|
250
228
|
async editCsv(filePath, content) {
|
|
251
|
-
if (!content)
|
|
252
|
-
return { success: false, output: '
|
|
229
|
+
if (!content?.rows?.length)
|
|
230
|
+
return { success: false, output: 'Nothing to add. Provide { rows: [[…], …] }.' };
|
|
253
231
|
const existing = await readFile(filePath, 'utf-8');
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
return { success: true, output: `Appended ${newRows.length} rows to ${filePath}` };
|
|
232
|
+
const added = content.rows.map((row) => row.map((cell) => this.csvEscape(String(cell ?? ''))).join(','));
|
|
233
|
+
await writeFile(filePath, existing.replace(/\s+$/, '') + '\n' + added.join('\n') + '\n', 'utf-8');
|
|
234
|
+
return { success: true, output: `Added ${added.length} rows to ${filePath}` };
|
|
258
235
|
}
|
|
259
236
|
csvEscape(value) {
|
|
260
|
-
|
|
261
|
-
return `"${value.replace(/"/g, '""')}"`;
|
|
262
|
-
}
|
|
263
|
-
return value;
|
|
264
|
-
}
|
|
265
|
-
parseCsvString(raw) {
|
|
266
|
-
const lines = raw.trim().split('\n');
|
|
267
|
-
if (lines.length === 0)
|
|
268
|
-
return { headers: [], rows: [] };
|
|
269
|
-
const headers = this.parseCsvLine(lines[0]);
|
|
270
|
-
const rows = lines.slice(1).map(l => this.parseCsvLine(l));
|
|
271
|
-
return { headers, rows };
|
|
272
|
-
}
|
|
273
|
-
parseCsvLine(line) {
|
|
274
|
-
const result = [];
|
|
275
|
-
let current = '';
|
|
276
|
-
let inQuotes = false;
|
|
277
|
-
for (let i = 0; i < line.length; i++) {
|
|
278
|
-
const ch = line[i];
|
|
279
|
-
if (inQuotes) {
|
|
280
|
-
if (ch === '"' && line[i + 1] === '"') {
|
|
281
|
-
current += '"';
|
|
282
|
-
i++;
|
|
283
|
-
}
|
|
284
|
-
else if (ch === '"') {
|
|
285
|
-
inQuotes = false;
|
|
286
|
-
}
|
|
287
|
-
else {
|
|
288
|
-
current += ch;
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
else {
|
|
292
|
-
if (ch === '"') {
|
|
293
|
-
inQuotes = true;
|
|
294
|
-
}
|
|
295
|
-
else if (ch === ',') {
|
|
296
|
-
result.push(current);
|
|
297
|
-
current = '';
|
|
298
|
-
}
|
|
299
|
-
else {
|
|
300
|
-
current += ch;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
result.push(current);
|
|
305
|
-
return result;
|
|
306
|
-
}
|
|
307
|
-
// ── Markdown (native) ──────────────────────────────────────────────────────
|
|
308
|
-
async createMarkdown(filePath, content) {
|
|
309
|
-
const lines = [];
|
|
310
|
-
if (content?.title)
|
|
311
|
-
lines.push(`# ${content.title}`, '');
|
|
312
|
-
for (const section of content?.sections ?? []) {
|
|
313
|
-
if (section.heading)
|
|
314
|
-
lines.push(`## ${section.heading}`, '');
|
|
315
|
-
if (section.text)
|
|
316
|
-
lines.push(section.text, '');
|
|
317
|
-
if (section.list) {
|
|
318
|
-
for (const item of section.list)
|
|
319
|
-
lines.push(`- ${item}`);
|
|
320
|
-
lines.push('');
|
|
321
|
-
}
|
|
322
|
-
if (section.table) {
|
|
323
|
-
lines.push(`| ${section.table.headers.join(' | ')} |`);
|
|
324
|
-
lines.push(`| ${section.table.headers.map(() => '---').join(' | ')} |`);
|
|
325
|
-
for (const row of section.table.rows) {
|
|
326
|
-
lines.push(`| ${row.join(' | ')} |`);
|
|
327
|
-
}
|
|
328
|
-
lines.push('');
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
await writeFile(filePath, lines.join('\n'), 'utf-8');
|
|
332
|
-
const sectionCount = content?.sections?.length ?? 0;
|
|
333
|
-
return { success: true, output: `Created Markdown: ${filePath} (${sectionCount} sections)` };
|
|
237
|
+
return /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
|
|
334
238
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
const lineCount = raw.split('\n').length;
|
|
338
|
-
return { success: true, output: `Markdown: ${filePath} (${lineCount} lines)\n\n${raw.slice(0, 3000)}${raw.length > 3000 ? '\n... truncated' : ''}` };
|
|
339
|
-
}
|
|
340
|
-
async editMarkdown(filePath, content) {
|
|
341
|
-
if (!content)
|
|
342
|
-
return { success: false, output: 'Missing content for edit.' };
|
|
343
|
-
const existing = await readFile(filePath, 'utf-8');
|
|
344
|
-
const newContent = [];
|
|
345
|
-
for (const section of content.sections ?? []) {
|
|
346
|
-
if (section.heading)
|
|
347
|
-
newContent.push(`\n## ${section.heading}\n`);
|
|
348
|
-
if (section.text)
|
|
349
|
-
newContent.push(section.text);
|
|
350
|
-
if (section.list)
|
|
351
|
-
newContent.push(...section.list.map(i => `- ${i}`));
|
|
352
|
-
}
|
|
353
|
-
await writeFile(filePath, existing.trimEnd() + '\n' + newContent.join('\n') + '\n', 'utf-8');
|
|
354
|
-
return { success: true, output: `Appended ${content.sections.length} sections to ${filePath}` };
|
|
355
|
-
}
|
|
356
|
-
markdownToContent(raw) {
|
|
357
|
-
const lines = raw.split('\n');
|
|
358
|
-
let title;
|
|
359
|
-
const sections = [];
|
|
360
|
-
let current = {};
|
|
361
|
-
for (const line of lines) {
|
|
362
|
-
if (line.startsWith('# ') && !title) {
|
|
363
|
-
title = line.slice(2).trim();
|
|
364
|
-
}
|
|
365
|
-
else if (line.startsWith('## ')) {
|
|
366
|
-
if (current.heading || current.text)
|
|
367
|
-
sections.push(current);
|
|
368
|
-
current = { heading: line.slice(3).trim() };
|
|
369
|
-
}
|
|
370
|
-
else if (line.startsWith('- ')) {
|
|
371
|
-
if (!current.list)
|
|
372
|
-
current.list = [];
|
|
373
|
-
current.list.push(line.slice(2).trim());
|
|
374
|
-
}
|
|
375
|
-
else if (line.trim()) {
|
|
376
|
-
current.text = (current.text ? current.text + '\n' : '') + line;
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
if (current.heading || current.text || current.list)
|
|
380
|
-
sections.push(current);
|
|
381
|
-
return { title, sections };
|
|
382
|
-
}
|
|
383
|
-
// ── DOCX (optional: docx package) ──────────────────────────────────────────
|
|
384
|
-
async createDocx(filePath, content, profile) {
|
|
385
|
-
let docx;
|
|
239
|
+
// ── XLSX ─────────────────────────────────────────────────────────────────────
|
|
240
|
+
async loadExcel() {
|
|
386
241
|
try {
|
|
387
|
-
|
|
242
|
+
const mod = await import('exceljs');
|
|
243
|
+
return mod.default?.Workbook ? mod.default : mod;
|
|
388
244
|
}
|
|
389
245
|
catch {
|
|
390
|
-
|
|
391
|
-
}
|
|
392
|
-
const { Document, Packer } = docx;
|
|
393
|
-
const styleProfile = profile ?? getStyleProfile();
|
|
394
|
-
const children = [];
|
|
395
|
-
if (content?.title) {
|
|
396
|
-
children.push(titleParagraph(docx, content.title));
|
|
397
|
-
}
|
|
398
|
-
for (const section of content?.sections ?? []) {
|
|
399
|
-
if (section.heading) {
|
|
400
|
-
children.push(headingParagraph(docx, section.heading, 1));
|
|
401
|
-
}
|
|
402
|
-
if (section.text) {
|
|
403
|
-
for (const para of section.text.split('\n')) {
|
|
404
|
-
if (para.trim())
|
|
405
|
-
children.push(bodyParagraph(docx, para));
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
if (section.list) {
|
|
409
|
-
for (const item of section.list) {
|
|
410
|
-
children.push(bulletParagraph(docx, item));
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
if (section.table) {
|
|
414
|
-
children.push(themedTable(docx, {
|
|
415
|
-
headers: section.table.headers,
|
|
416
|
-
rows: section.table.rows,
|
|
417
|
-
}));
|
|
418
|
-
}
|
|
246
|
+
throw new Error('Spreadsheets cannot be made in this build of Ava. Please report it on our Discord.');
|
|
419
247
|
}
|
|
420
|
-
const doc = new Document({
|
|
421
|
-
sections: [{
|
|
422
|
-
properties: sectionProperties(styleProfile),
|
|
423
|
-
children,
|
|
424
|
-
}],
|
|
425
|
-
});
|
|
426
|
-
const buffer = await Packer.toBuffer(doc);
|
|
427
|
-
await writeFile(filePath, buffer);
|
|
428
|
-
return { success: true, output: `Created Word document: ${filePath} (${content?.sections?.length ?? 0} sections, Ava-themed)` };
|
|
429
248
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
mammoth = await import('mammoth');
|
|
434
|
-
}
|
|
435
|
-
catch {
|
|
436
|
-
// Fallback: just report file exists
|
|
437
|
-
const raw = await readFile(filePath);
|
|
438
|
-
return { success: true, output: `Word document: ${filePath} (${raw.length} bytes). Install mammoth for text extraction: npm install mammoth` };
|
|
439
|
-
}
|
|
440
|
-
const result = await mammoth.extractRawText({ path: filePath });
|
|
441
|
-
return { success: true, output: `Word document: ${filePath}\n\n${result.value.slice(0, 3000)}${result.value.length > 3000 ? '\n... truncated' : ''}` };
|
|
249
|
+
/** The house style and the spreadsheet library, for building a workbook. */
|
|
250
|
+
async kit() {
|
|
251
|
+
return { ExcelJS: await this.loadExcel(), brand: await loadHouseStyle() };
|
|
442
252
|
}
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
//
|
|
455
|
-
|
|
456
|
-
if (!readResult.success)
|
|
457
|
-
return readResult;
|
|
458
|
-
// Parse existing text into content structure
|
|
459
|
-
const existingContent = this.markdownToContent(readResult.output);
|
|
460
|
-
// Merge new sections
|
|
461
|
-
const merged = {
|
|
462
|
-
title: existingContent.title,
|
|
463
|
-
sections: [...existingContent.sections, ...(content?.sections ?? [])],
|
|
464
|
-
};
|
|
465
|
-
const result = await this.createDocx(filePath, merged);
|
|
466
|
-
if (result.success) {
|
|
467
|
-
return {
|
|
468
|
-
...result,
|
|
469
|
-
output: result.output + '\n\n⚠ Note: editing a .docx recreates the file. Any custom formatting (fonts, colors, images, complex tables, headers/footers) in the original was lost — only text content was preserved. To preserve formatting, edit the document in Word directly.',
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
return result;
|
|
253
|
+
/** A spreadsheet ready to change: an .xlsx read directly, an .ods rebuilt through the same workbook. Charts alongside. */
|
|
254
|
+
async loadBook(path) {
|
|
255
|
+
const { ExcelJS, brand } = await this.kit();
|
|
256
|
+
const bytes = await readFile(path);
|
|
257
|
+
if (this.formatOf(path) === 'ods') {
|
|
258
|
+
const specs = readOds(bytes).map(odsToSheetSpec);
|
|
259
|
+
const { workbook } = buildWorkbook(ExcelJS, specs, brand);
|
|
260
|
+
return { workbook, charts: specs.map((sp, i) => ({ sheet: workbook.worksheets[i]?.name ?? sp.name, charts: sp.charts ?? [] })) };
|
|
261
|
+
}
|
|
262
|
+
const workbook = new ExcelJS.Workbook();
|
|
263
|
+
await workbook.xlsx.load(bytes);
|
|
264
|
+
// exceljs drops charts on rewrite: read them first, put them back on save.
|
|
265
|
+
return { workbook, charts: shiftCharts(readCharts(bytes), null) };
|
|
473
266
|
}
|
|
474
|
-
|
|
475
|
-
async
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
return { success: false, output: 'exceljs package is not installed. Install it with: npm install exceljs' };
|
|
482
|
-
}
|
|
483
|
-
const workbook = new (ExcelJS.default?.Workbook || ExcelJS.Workbook)();
|
|
484
|
-
let totalRows = 0;
|
|
485
|
-
// If no structured content provided, try to parse plain text content from args
|
|
486
|
-
const sheets = content?.sheets ?? this.parseTextToSheets(content);
|
|
487
|
-
for (const sheet of sheets) {
|
|
488
|
-
const ws = workbook.addWorksheet(sheet.name);
|
|
489
|
-
if (sheet.headers.length > 0) {
|
|
490
|
-
const headerRow = ws.addRow(sheet.headers);
|
|
491
|
-
headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' } };
|
|
492
|
-
headerRow.eachCell((cell) => {
|
|
493
|
-
cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF4472C4' } };
|
|
494
|
-
cell.border = {
|
|
495
|
-
bottom: { style: 'thin', color: { argb: 'FF2F5496' } },
|
|
496
|
-
};
|
|
497
|
-
});
|
|
498
|
-
}
|
|
499
|
-
for (const row of sheet.rows) {
|
|
500
|
-
ws.addRow(row);
|
|
501
|
-
totalRows++;
|
|
502
|
-
}
|
|
503
|
-
// Auto-width columns based on content
|
|
504
|
-
ws.columns?.forEach((col) => {
|
|
505
|
-
if (!col)
|
|
506
|
-
return;
|
|
507
|
-
let maxLen = 10;
|
|
508
|
-
col.eachCell?.({ includeEmpty: false }, (cell) => {
|
|
509
|
-
const len = String(cell.value ?? '').length;
|
|
510
|
-
if (len > maxLen)
|
|
511
|
-
maxLen = len;
|
|
512
|
-
});
|
|
513
|
-
col.width = Math.min(maxLen + 2, 50);
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
await workbook.xlsx.writeFile(filePath);
|
|
517
|
-
return { success: true, output: `Created spreadsheet: ${filePath} (${content?.sheets?.length ?? 1} sheets, ${totalRows} rows)` };
|
|
267
|
+
/** Write a workbook and its charts as .xlsx or .ods, by the file's name. */
|
|
268
|
+
async saveBook(path, workbook, charts) {
|
|
269
|
+
const brand = await loadHouseStyle();
|
|
270
|
+
const bytes = this.formatOf(path) === 'ods'
|
|
271
|
+
? workbookToOds(workbook, charts, chartCellsOf(workbook), brand)
|
|
272
|
+
: await workbookBytes(workbook, charts, brand);
|
|
273
|
+
await writeFile(path, bytes);
|
|
518
274
|
}
|
|
519
|
-
async
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
const
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
}
|
|
541
|
-
else {
|
|
542
|
-
rows.push(cells.join(' | '));
|
|
543
|
-
}
|
|
275
|
+
async createBook(filePath, content) {
|
|
276
|
+
const { ExcelJS, brand } = await this.kit();
|
|
277
|
+
const specs = (content?.sheets ?? []);
|
|
278
|
+
const { workbook, calculated, left } = buildWorkbook(ExcelJS, specs, brand);
|
|
279
|
+
// Charts by the sheet's real name, which buildWorkbook may have trimmed.
|
|
280
|
+
await this.saveBook(filePath, workbook, specs.map((sp, i) => ({ sheet: workbook.worksheets[i]?.name ?? sp.name, charts: sp.charts ?? [] })));
|
|
281
|
+
const rows = specs.reduce((n, sp) => n + (sp.rows?.length ?? 0), 0);
|
|
282
|
+
const sheets = Math.max(1, specs.length);
|
|
283
|
+
const notes = [
|
|
284
|
+
calculated ? `${calculated} formula${calculated === 1 ? '' : 's'} worked out` : '',
|
|
285
|
+
left ? `${left} left for the spreadsheet app to calculate on opening` : '',
|
|
286
|
+
].filter(Boolean).join('; ');
|
|
287
|
+
return { success: true, output: `Created spreadsheet: ${filePath} (${sheets} sheet${sheets === 1 ? '' : 's'}, ${rows} rows${notes ? `; ${notes}` : ''})` };
|
|
288
|
+
}
|
|
289
|
+
/** Any spreadsheet as text for Ava: every sheet, formulas beside their results, charts listed. */
|
|
290
|
+
async readBook(filePath) {
|
|
291
|
+
const sheets = await readSheetForView(filePath);
|
|
292
|
+
const parts = sheets.map((sh) => {
|
|
293
|
+
const lines = sh.rows.slice(0, 201).map((r, i) => {
|
|
294
|
+
const line = r.map((c) => (c.f ? `${c.v} (=${c.f})` : c.v)).join(' | ');
|
|
295
|
+
return i === 0 ? `${line}\n${r.map(() => '---').join(' | ')}` : line;
|
|
544
296
|
});
|
|
545
|
-
|
|
297
|
+
const more = sh.rows.length > 201 ? `\n… and ${sh.rows.length - 201} more rows` : '';
|
|
298
|
+
const charts = sh.charts?.length
|
|
299
|
+
? `\nCharts: ${sh.charts.map((c) => `${c.type}${c.title ? ` "${c.title}"` : ''} (${c.categories}; ${c.series.map((x) => x.values).join(', ')})`).join('; ')}`
|
|
300
|
+
: '';
|
|
301
|
+
return `### ${sh.name}\n${lines.join('\n')}${more}${charts}`;
|
|
546
302
|
});
|
|
547
303
|
return { success: true, output: `Spreadsheet: ${filePath}\n\n${parts.join('\n\n')}` };
|
|
548
304
|
}
|
|
549
|
-
async
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
}
|
|
554
|
-
catch {
|
|
555
|
-
return { success: false, output: 'exceljs package is not installed. Install it with: npm install exceljs' };
|
|
556
|
-
}
|
|
557
|
-
const workbook = new (ExcelJS.default?.Workbook || ExcelJS.Workbook)();
|
|
558
|
-
await workbook.xlsx.readFile(filePath);
|
|
559
|
-
let addedRows = 0;
|
|
305
|
+
async editBook(filePath, content) {
|
|
306
|
+
const { workbook, charts } = await this.loadBook(filePath);
|
|
307
|
+
let inserted = null;
|
|
308
|
+
let added = 0;
|
|
560
309
|
for (const sheet of content?.sheets ?? []) {
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
try {
|
|
576
|
-
// @ts-expect-error — pdfkit is an optional peer dependency
|
|
577
|
-
const pdfkit = await import('pdfkit');
|
|
578
|
-
PDFDocument = pdfkit.default || pdfkit;
|
|
579
|
-
}
|
|
580
|
-
catch {
|
|
581
|
-
return { success: false, output: 'pdfkit package is not installed. Install it with: npm install pdfkit' };
|
|
582
|
-
}
|
|
583
|
-
return new Promise((resolve) => {
|
|
584
|
-
const doc = new PDFDocument({ margin: 56 }); // ~0.78", a touch tighter than docx defaults
|
|
585
|
-
const chunks = [];
|
|
586
|
-
doc.on('data', (chunk) => chunks.push(chunk));
|
|
587
|
-
doc.on('end', async () => {
|
|
588
|
-
const buffer = Buffer.concat(chunks);
|
|
589
|
-
await writeFile(filePath, buffer);
|
|
590
|
-
resolve({ success: true, output: `Created PDF: ${filePath} (${content?.sections?.length ?? 0} sections, Ava-themed)` });
|
|
591
|
-
});
|
|
592
|
-
if (content?.title) {
|
|
593
|
-
pdfTitle(doc, content.title);
|
|
594
|
-
}
|
|
595
|
-
for (const section of content?.sections ?? []) {
|
|
596
|
-
if (section.heading)
|
|
597
|
-
pdfHeading(doc, section.heading, 1);
|
|
598
|
-
if (section.text) {
|
|
599
|
-
for (const para of section.text.split(/\n\n+/)) {
|
|
600
|
-
if (para.trim())
|
|
601
|
-
pdfBody(doc, para.trim());
|
|
310
|
+
const ws = workbook.getWorksheet(sheet.name) ?? workbook.addWorksheet(sheet.name);
|
|
311
|
+
const rows = (sheet.rows ?? []);
|
|
312
|
+
if (!rows.length)
|
|
313
|
+
continue;
|
|
314
|
+
const total = this.totalsRow(ws);
|
|
315
|
+
if (total) {
|
|
316
|
+
// Insert above the totals and stretch each SUM over the new rows.
|
|
317
|
+
inserted = { at: total.row, count: rows.length };
|
|
318
|
+
ws.spliceRows(total.row, 0, ...rows.map((r) => r.map((v) => (typeof v === 'string' && v.startsWith('=') ? { formula: v.slice(1) } : v))));
|
|
319
|
+
const tr = ws.getRow(total.row + rows.length);
|
|
320
|
+
tr.eachCell((cell) => {
|
|
321
|
+
const v = cell.value;
|
|
322
|
+
if (v && typeof v === 'object' && 'formula' in v) {
|
|
323
|
+
cell.value = { formula: String(v.formula).replace(/^(SUM\([A-Z]{1,3}\d+:[A-Z]{1,3})(\d+)\)$/i, (_m, head, end) => `${head}${Number(end) + rows.length})`) };
|
|
602
324
|
}
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
if (section.table) {
|
|
610
|
-
pdfTable(doc, { headers: section.table.headers, rows: section.table.rows });
|
|
325
|
+
});
|
|
326
|
+
// Carry the column formats down onto the new rows.
|
|
327
|
+
const model = ws.getRow(Math.max(2, total.row - 1));
|
|
328
|
+
for (let r = total.row; r < total.row + rows.length; r++) {
|
|
329
|
+
ws.getRow(r).eachCell({ includeEmpty: true }, (cell, c) => { const f = model.getCell(c).numFmt; if (f)
|
|
330
|
+
cell.numFmt = f; });
|
|
611
331
|
}
|
|
612
332
|
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
const mod = await import('pdf-parse');
|
|
620
|
-
pdfParse = mod.default || mod;
|
|
621
|
-
}
|
|
622
|
-
catch {
|
|
623
|
-
const raw = await readFile(filePath);
|
|
624
|
-
return { success: true, output: `PDF: ${filePath} (${raw.length} bytes). Install pdf-parse for text extraction: npm install pdf-parse` };
|
|
333
|
+
else {
|
|
334
|
+
for (const row of rows)
|
|
335
|
+
ws.addRow(row.map((v) => (typeof v === 'string' && v.startsWith('=') ? { formula: v.slice(1) } : v)));
|
|
336
|
+
}
|
|
337
|
+
recalculate(ws);
|
|
338
|
+
added += rows.length;
|
|
625
339
|
}
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
340
|
+
if (!added)
|
|
341
|
+
return { success: false, output: 'Nothing to add. Provide { sheets: [{ name, rows }] }.' };
|
|
342
|
+
await this.saveBook(filePath, workbook, stretchCharts(charts, inserted));
|
|
343
|
+
return { success: true, output: `Updated spreadsheet: ${filePath} (added ${added} rows)` };
|
|
629
344
|
}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
if (filePath.startsWith('/') || /^[A-Za-z]:/.test(filePath))
|
|
643
|
-
return filePath;
|
|
644
|
-
return `${cwd}/${filePath}`;
|
|
345
|
+
/** The last row, when it is a totals row (a SUM down to the row above). */
|
|
346
|
+
totalsRow(ws) {
|
|
347
|
+
const last = ws.rowCount;
|
|
348
|
+
if (last < 2)
|
|
349
|
+
return null;
|
|
350
|
+
let isTotal = false;
|
|
351
|
+
ws.getRow(last).eachCell((cell) => {
|
|
352
|
+
const v = cell.value;
|
|
353
|
+
if (v && typeof v === 'object' && 'formula' in v && new RegExp(`^SUM\\([A-Z]{1,3}\\d+:[A-Z]{1,3}${last - 1}\\)$`, 'i').test(String(v.formula)))
|
|
354
|
+
isTotal = true;
|
|
355
|
+
});
|
|
356
|
+
return isTotal ? { row: last } : null;
|
|
645
357
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
return
|
|
358
|
+
// ── Update cells ─────────────────────────────────────────────────────────────
|
|
359
|
+
async handleUpdateCells(args, context) {
|
|
360
|
+
const fullPath = this.target(args.file_path, context.cwd, false);
|
|
361
|
+
if (!existsSync(fullPath))
|
|
362
|
+
return { success: false, output: `File not found: ${fullPath}` };
|
|
363
|
+
if (!['xlsx', 'ods'].includes(this.formatOf(fullPath)))
|
|
364
|
+
return { success: false, output: 'update_cells changes .xlsx and .ods spreadsheets. For a CSV, use edit to add rows.' };
|
|
365
|
+
const cells = args.cells;
|
|
366
|
+
if (!cells || !Object.keys(cells).length)
|
|
367
|
+
return { success: false, output: 'Nothing to change. Provide cells: { "B4": 950 }.' };
|
|
368
|
+
const { workbook, charts } = await this.loadBook(fullPath);
|
|
369
|
+
const ws = args.sheet ? workbook.getWorksheet(String(args.sheet)) : workbook.worksheets[0];
|
|
370
|
+
if (!ws)
|
|
371
|
+
return { success: false, output: `No sheet called ${String(args.sheet)}.` };
|
|
372
|
+
const changed = updateCells(ws, cells);
|
|
373
|
+
await this.saveBook(fullPath, workbook, charts);
|
|
374
|
+
return { success: true, output: `Updated ${changed.join(', ')} on ${ws.name} in ${fullPath}; formulas recalculated.` };
|
|
663
375
|
}
|
|
664
376
|
}
|
|
665
377
|
//# sourceMappingURL=document-manage.js.map
|