@octopi-agent/engine 0.55.0 → 0.56.0

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 (56) hide show
  1. package/dist/config-schema/context.d.ts +38 -0
  2. package/dist/config-schema/context.js +39 -0
  3. package/dist/config-schema/engine.d.ts +37 -0
  4. package/dist/config-schema/engine.js +3 -1
  5. package/dist/config.d.ts +35 -0
  6. package/dist/harness/context/capabilities/document/backends/docx.d.ts +7 -0
  7. package/dist/harness/context/capabilities/document/backends/docx.js +67 -0
  8. package/dist/harness/context/capabilities/document/backends/office-parser.d.ts +7 -0
  9. package/dist/harness/context/capabilities/document/backends/office-parser.js +76 -0
  10. package/dist/harness/context/capabilities/document/backends/pdf.d.ts +7 -0
  11. package/dist/harness/context/capabilities/document/backends/pdf.js +86 -0
  12. package/dist/harness/context/capabilities/document/backends/plain.d.ts +7 -0
  13. package/dist/harness/context/capabilities/document/backends/plain.js +42 -0
  14. package/dist/harness/context/capabilities/document/backends/sheet.d.ts +7 -0
  15. package/dist/harness/context/capabilities/document/backends/sheet.js +90 -0
  16. package/dist/harness/context/capabilities/document/backends/xmind.d.ts +20 -0
  17. package/dist/harness/context/capabilities/document/backends/xmind.js +198 -0
  18. package/dist/harness/context/capabilities/document/errors.d.ts +27 -0
  19. package/dist/harness/context/capabilities/document/errors.js +33 -0
  20. package/dist/harness/context/capabilities/document/format.d.ts +38 -0
  21. package/dist/harness/context/capabilities/document/format.js +113 -0
  22. package/dist/harness/context/capabilities/document/html-to-md.d.ts +14 -0
  23. package/dist/harness/context/capabilities/document/html-to-md.js +97 -0
  24. package/dist/harness/context/capabilities/document/index.d.ts +21 -0
  25. package/dist/harness/context/capabilities/document/index.js +20 -0
  26. package/dist/harness/context/capabilities/document/legacy/factory.d.ts +13 -0
  27. package/dist/harness/context/capabilities/document/legacy/factory.js +23 -0
  28. package/dist/harness/context/capabilities/document/legacy/soffice.d.ts +32 -0
  29. package/dist/harness/context/capabilities/document/legacy/soffice.js +186 -0
  30. package/dist/harness/context/capabilities/document/port.d.ts +19 -0
  31. package/dist/harness/context/capabilities/document/port.js +400 -0
  32. package/dist/harness/context/capabilities/document/types.d.ts +149 -0
  33. package/dist/harness/context/capabilities/document/types.js +8 -0
  34. package/dist/harness/context/capabilities/index.d.ts +1 -0
  35. package/dist/harness/context/capabilities/index.js +1 -0
  36. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +1 -0
  37. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +10 -0
  38. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.d.ts +64 -0
  39. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +155 -0
  40. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +1 -0
  41. package/dist/harness/extension/plugin-ecosystem/tools/index.js +1 -0
  42. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.d.ts +2 -0
  43. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.js +4 -1
  44. package/dist/harness/index.d.ts +2 -2
  45. package/dist/harness/index.js +1 -1
  46. package/dist/harness/knowledge/index-store.d.ts +7 -1
  47. package/dist/harness/knowledge/index-store.js +6 -0
  48. package/dist/harness/knowledge/ingest.d.ts +23 -0
  49. package/dist/harness/knowledge/ingest.js +81 -3
  50. package/dist/harness/session/attachments/extract.d.ts +3 -2
  51. package/dist/harness/session/attachments/extract.js +19 -6
  52. package/dist/harness/session/attachments/service.d.ts +5 -1
  53. package/dist/harness/session/attachments/service.js +44 -2
  54. package/dist/index.d.ts +2 -2
  55. package/dist/index.js +1 -1
  56. package/package.json +8 -3
@@ -0,0 +1,198 @@
1
+ /**
2
+ * XMind 后端 — ZIP + content.json / content.xml → Markdown 大纲
3
+ *
4
+ * XMind 2020+:content.json 树(children.attached)
5
+ * XMind 8:content.xml topic 树(尽力解析)
6
+ *
7
+ * @module harness/context/capabilities/document/backends/xmind
8
+ */
9
+ import { DocumentExtractError } from '../errors.js';
10
+ let fflateCache;
11
+ async function loadFflate() {
12
+ if (fflateCache !== undefined)
13
+ return fflateCache;
14
+ try {
15
+ const mod = (await import('fflate'));
16
+ if (typeof mod.unzipSync !== 'function' || typeof mod.strFromU8 !== 'function') {
17
+ fflateCache = null;
18
+ return null;
19
+ }
20
+ fflateCache = mod;
21
+ return mod;
22
+ }
23
+ catch {
24
+ // 可选依赖未安装 —— 缓存 null,调用方走 BACKEND_UNAVAILABLE
25
+ fflateCache = null;
26
+ return null;
27
+ }
28
+ }
29
+ function topicTitle(t) {
30
+ return (t.title ?? '').trim() || '(untitled)';
31
+ }
32
+ function topicNote(t) {
33
+ const n = t.note;
34
+ if (!n)
35
+ return '';
36
+ const text = typeof n === 'string' ? n : (n.plain ?? '');
37
+ return text.trim().replace(/\s+/g, ' ');
38
+ }
39
+ function walkTopics(topics, depth, out) {
40
+ for (const topic of topics) {
41
+ const indent = ' '.repeat(depth);
42
+ const note = topicNote(topic);
43
+ const href = topic.href?.trim();
44
+ const labels = (topic.labels ?? []).filter(Boolean).join(' ');
45
+ const extras = [
46
+ labels ? `[${labels}]` : '',
47
+ href ? `<${href}>` : '',
48
+ note ? `(${note})` : '',
49
+ ]
50
+ .filter(Boolean)
51
+ .join(' ');
52
+ out.push(`${indent}- ${topicTitle(topic)}${extras ? ` ${extras}` : ''}`);
53
+ const kids = topic.children?.attached ?? [];
54
+ if (kids.length)
55
+ walkTopics(kids, depth + 1, out);
56
+ }
57
+ }
58
+ /** content.json(XMind 2020+)→ Markdown 大纲 */
59
+ export function xmindJsonToMarkdown(jsonText) {
60
+ let sheets;
61
+ try {
62
+ sheets = JSON.parse(jsonText);
63
+ }
64
+ catch (err) {
65
+ throw new DocumentExtractError('INVALID_SOURCE', `xmind content.json parse failed: ${err instanceof Error ? err.message : String(err)}`);
66
+ }
67
+ const list = Array.isArray(sheets) ? sheets : [sheets];
68
+ const parts = [];
69
+ for (const sheetRaw of list) {
70
+ const sheet = sheetRaw;
71
+ const root = sheet.rootTopic;
72
+ if (!root)
73
+ continue;
74
+ const sheetTitle = (sheet.title ?? '').trim();
75
+ const lines = [];
76
+ // 根主题作 H1;子主题作嵌套列表
77
+ lines.push(`# ${topicTitle(root)}`);
78
+ const note = topicNote(root);
79
+ if (note)
80
+ lines.push(`> ${note}`);
81
+ lines.push('');
82
+ walkTopics(root.children?.attached ?? [], 0, lines);
83
+ if (sheetTitle && sheetTitle !== topicTitle(root)) {
84
+ parts.push(`## ${sheetTitle}\n\n${lines.join('\n')}`);
85
+ }
86
+ else {
87
+ parts.push(lines.join('\n'));
88
+ }
89
+ }
90
+ return parts.join('\n\n').trim();
91
+ }
92
+ /**
93
+ * content.xml(XMind 8)→ Markdown 大纲
94
+ * 仅取 title 树,不解析样式/关系边。
95
+ *
96
+ * @param xmlText - content.xml 文本
97
+ * @returns Markdown 大纲
98
+ */
99
+ export function xmindXmlToMarkdown(xmlText) {
100
+ const cleaned = xmlText
101
+ .replace(/<!--[\s\S]*?-->/g, '')
102
+ .replace(/<\?xml[\s\S]*?\?>/g, '');
103
+ const nodes = [];
104
+ let depth = 0;
105
+ let guard = 0;
106
+ const tokenRe = /<\/?topic\b[^>]*>|<title[^>]*>([\s\S]*?)<\/title>/gi;
107
+ let t;
108
+ while ((t = tokenRe.exec(cleaned)) !== null) {
109
+ guard += 1;
110
+ if (guard > 50_000)
111
+ break;
112
+ const tok = t[0];
113
+ if (/^<topic\b/i.test(tok)) {
114
+ depth += 1;
115
+ }
116
+ else if (/^<\/topic>/i.test(tok)) {
117
+ depth = Math.max(0, depth - 1);
118
+ }
119
+ else {
120
+ const title = (t[1] ?? '')
121
+ .replace(/<[^>]+>/g, '')
122
+ .replace(/&lt;/g, '<')
123
+ .replace(/&gt;/g, '>')
124
+ .replace(/&amp;/g, '&')
125
+ .replace(/&quot;/g, '"')
126
+ .replace(/&#39;/g, "'")
127
+ .trim();
128
+ if (title)
129
+ nodes.push({ title, depth: Math.max(0, depth - 1) });
130
+ }
131
+ }
132
+ if (!nodes.length) {
133
+ throw new DocumentExtractError('INVALID_SOURCE', 'xmind content.xml has no topics');
134
+ }
135
+ const lines = [];
136
+ for (const node of nodes) {
137
+ if (node.depth === 0) {
138
+ lines.push(`# ${node.title}`);
139
+ lines.push('');
140
+ }
141
+ else {
142
+ lines.push(`${' '.repeat(node.depth - 1)}- ${node.title}`);
143
+ }
144
+ }
145
+ return lines.join('\n').trim();
146
+ }
147
+ export const xmindBackend = {
148
+ id: 'xmind',
149
+ tier: 't0',
150
+ formats: ['xmind'],
151
+ async isAvailable() {
152
+ return (await loadFflate()) !== null;
153
+ },
154
+ accepts({ format }) {
155
+ return format === 'xmind';
156
+ },
157
+ async extract(source, _options) {
158
+ const fflate = await loadFflate();
159
+ if (!fflate) {
160
+ throw new DocumentExtractError('BACKEND_UNAVAILABLE', 'fflate is not installed', [
161
+ 'optional:fflate',
162
+ ]);
163
+ }
164
+ let files;
165
+ try {
166
+ files = fflate.unzipSync(source.data);
167
+ }
168
+ catch (err) {
169
+ throw new DocumentExtractError('INVALID_SOURCE', `xmind unzip failed: ${err instanceof Error ? err.message : String(err)}`);
170
+ }
171
+ const jsonEntry = files['content.json'];
172
+ if (jsonEntry) {
173
+ const markdown = xmindJsonToMarkdown(fflate.strFromU8(jsonEntry));
174
+ return {
175
+ markdown,
176
+ meta: { format: 'xmind' },
177
+ warnings: [],
178
+ backend: 'xmind',
179
+ };
180
+ }
181
+ const xmlEntry = files['content.xml'];
182
+ if (xmlEntry) {
183
+ const markdown = xmindXmlToMarkdown(fflate.strFromU8(xmlEntry));
184
+ return {
185
+ markdown,
186
+ meta: { format: 'xmind' },
187
+ warnings: [
188
+ {
189
+ code: 'DEGRADED_BACKEND',
190
+ message: 'xmind content.json missing; parsed content.xml (XMind 8 path)',
191
+ },
192
+ ],
193
+ backend: 'xmind',
194
+ };
195
+ }
196
+ throw new DocumentExtractError('INVALID_SOURCE', 'xmind archive has no content.json/content.xml');
197
+ },
198
+ };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Document 抽取结构化错误
3
+ *
4
+ * @module harness/context/capabilities/document/errors
5
+ */
6
+ import type { ExtractErrorCode } from './types.js';
7
+ /**
8
+ * DocumentExtractError — 调用方可按 code 分支,勿匹配 message 文本
9
+ */
10
+ export declare class DocumentExtractError extends Error {
11
+ readonly code: ExtractErrorCode;
12
+ /** 弥补建议,如 requires: ['legacy-converter'] */
13
+ readonly requires?: string[];
14
+ /**
15
+ * @param code - 结构化错误码
16
+ * @param message - 人读说明(不进程序分支)
17
+ * @param requires - 可选弥补能力名
18
+ */
19
+ constructor(code: ExtractErrorCode, message: string, requires?: string[]);
20
+ }
21
+ /**
22
+ * 类型守卫
23
+ *
24
+ * @param err - 任意异常
25
+ * @returns 是否 DocumentExtractError
26
+ */
27
+ export declare function isDocumentExtractError(err: unknown): err is DocumentExtractError;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Document 抽取结构化错误
3
+ *
4
+ * @module harness/context/capabilities/document/errors
5
+ */
6
+ /**
7
+ * DocumentExtractError — 调用方可按 code 分支,勿匹配 message 文本
8
+ */
9
+ export class DocumentExtractError extends Error {
10
+ code;
11
+ /** 弥补建议,如 requires: ['legacy-converter'] */
12
+ requires;
13
+ /**
14
+ * @param code - 结构化错误码
15
+ * @param message - 人读说明(不进程序分支)
16
+ * @param requires - 可选弥补能力名
17
+ */
18
+ constructor(code, message, requires) {
19
+ super(message);
20
+ this.name = 'DocumentExtractError';
21
+ this.code = code;
22
+ this.requires = requires;
23
+ }
24
+ }
25
+ /**
26
+ * 类型守卫
27
+ *
28
+ * @param err - 任意异常
29
+ * @returns 是否 DocumentExtractError
30
+ */
31
+ export function isDocumentExtractError(err) {
32
+ return err instanceof DocumentExtractError;
33
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 格式嗅探 — 扩展名 + magic bytes
3
+ *
4
+ * @module harness/context/capabilities/document/format
5
+ */
6
+ import type { DocumentFormatHint, ExtractSource } from './types.js';
7
+ /** 二进制老格式(需转换闸门) */
8
+ export declare const LEGACY_FORMATS: Set<DocumentFormatHint>;
9
+ /** DocumentPort 可尝试抽取的扩展名(含老格式;无后端时仍应跳过) */
10
+ export declare const DOCUMENT_EXTENSIONS: Set<string>;
11
+ /**
12
+ * 路径是否属于文档抽取范围
13
+ *
14
+ * @param path - 文件名或路径
15
+ */
16
+ export declare function isDocumentPath(path: string): boolean;
17
+ /**
18
+ * 按扩展名猜测格式
19
+ *
20
+ * @param name - 文件名或路径
21
+ * @returns 格式;未知为 unknown
22
+ */
23
+ export declare function formatFromName(name: string | undefined): DocumentFormatHint;
24
+ /**
25
+ * 从文件头 magic 判断(仅高置信类型;ZIP/OLE2 子类型靠扩展名)
26
+ *
27
+ * @param head - 文件前若干字节
28
+ * @returns 格式;无法判断为 unknown
29
+ */
30
+ export declare function formatFromMagic(head: Uint8Array | undefined): DocumentFormatHint;
31
+ /**
32
+ * 解析输入格式:hint > name > magic
33
+ *
34
+ * @param source - 原始输入
35
+ * @param head - 可选文件头
36
+ * @returns 格式
37
+ */
38
+ export declare function resolveFormat(source: ExtractSource, head?: Uint8Array): DocumentFormatHint;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * 格式嗅探 — 扩展名 + magic bytes
3
+ *
4
+ * @module harness/context/capabilities/document/format
5
+ */
6
+ import { extname } from 'node:path';
7
+ const EXT_MAP = {
8
+ '.pdf': 'pdf',
9
+ '.docx': 'docx',
10
+ '.xlsx': 'xlsx',
11
+ '.pptx': 'pptx',
12
+ '.doc': 'doc',
13
+ '.xls': 'xls',
14
+ '.ppt': 'ppt',
15
+ '.rtf': 'rtf',
16
+ '.odt': 'odt',
17
+ '.ods': 'ods',
18
+ '.odp': 'odp',
19
+ '.odg': 'odg',
20
+ '.htm': 'html',
21
+ '.html': 'html',
22
+ '.md': 'md',
23
+ '.markdown': 'md',
24
+ '.csv': 'csv',
25
+ '.tsv': 'csv',
26
+ '.txt': 'txt',
27
+ '.log': 'txt',
28
+ '.epub': 'epub',
29
+ '.tex': 'tex',
30
+ '.xmind': 'xmind',
31
+ };
32
+ /** 二进制老格式(需转换闸门) */
33
+ export const LEGACY_FORMATS = new Set(['doc', 'xls', 'ppt']);
34
+ /** DocumentPort 可尝试抽取的扩展名(含老格式;无后端时仍应跳过) */
35
+ export const DOCUMENT_EXTENSIONS = new Set([
36
+ '.pdf',
37
+ '.docx',
38
+ '.xlsx',
39
+ '.pptx',
40
+ '.doc',
41
+ '.xls',
42
+ '.ppt',
43
+ '.rtf',
44
+ '.odt',
45
+ '.ods',
46
+ '.odp',
47
+ '.odg',
48
+ '.epub',
49
+ '.tex',
50
+ '.xmind',
51
+ ]);
52
+ /**
53
+ * 路径是否属于文档抽取范围
54
+ *
55
+ * @param path - 文件名或路径
56
+ */
57
+ export function isDocumentPath(path) {
58
+ const ext = extname(path).toLowerCase();
59
+ return DOCUMENT_EXTENSIONS.has(ext);
60
+ }
61
+ /**
62
+ * 按扩展名猜测格式
63
+ *
64
+ * @param name - 文件名或路径
65
+ * @returns 格式;未知为 unknown
66
+ */
67
+ export function formatFromName(name) {
68
+ if (!name)
69
+ return 'unknown';
70
+ const ext = extname(name).toLowerCase();
71
+ return EXT_MAP[ext] ?? 'unknown';
72
+ }
73
+ /**
74
+ * 从文件头 magic 判断(仅高置信类型;ZIP/OLE2 子类型靠扩展名)
75
+ *
76
+ * @param head - 文件前若干字节
77
+ * @returns 格式;无法判断为 unknown
78
+ */
79
+ export function formatFromMagic(head) {
80
+ if (!head || head.length < 4)
81
+ return 'unknown';
82
+ // PDF: %PDF
83
+ if (head[0] === 0x25 && head[1] === 0x50 && head[2] === 0x44 && head[3] === 0x46) {
84
+ return 'pdf';
85
+ }
86
+ // RTF: {\rtf
87
+ if (head.length >= 5 &&
88
+ head[0] === 0x7b &&
89
+ head[1] === 0x5c &&
90
+ head[2] === 0x72 &&
91
+ head[3] === 0x74 &&
92
+ head[4] === 0x66) {
93
+ return 'rtf';
94
+ }
95
+ // ZIP (PK) 与 OLE2 (D0 CF 11 E0) 可对应多种 Office 子类型,
96
+ // 不猜 docx/doc —— 交由扩展名;无名时保持 unknown。
97
+ return 'unknown';
98
+ }
99
+ /**
100
+ * 解析输入格式:hint > name > magic
101
+ *
102
+ * @param source - 原始输入
103
+ * @param head - 可选文件头
104
+ * @returns 格式
105
+ */
106
+ export function resolveFormat(source, head) {
107
+ if (source.formatHint && source.formatHint !== 'unknown')
108
+ return source.formatHint;
109
+ const byName = formatFromName(source.name ?? source.path);
110
+ if (byName !== 'unknown')
111
+ return byName;
112
+ return formatFromMagic(head);
113
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * DOCX HTML → Markdown 轻量转换(配合 mammoth 输出)
3
+ *
4
+ * 只覆盖 mammoth 常见语义标签,不引入 turndown 依赖。
5
+ *
6
+ * @module harness/context/capabilities/document/html-to-md
7
+ */
8
+ /**
9
+ * 将 mammoth 语义 HTML 片段转为 Markdown
10
+ *
11
+ * @param html - HTML fragment
12
+ * @returns Markdown 文本
13
+ */
14
+ export declare function htmlFragmentToMarkdown(html: string): string;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * DOCX HTML → Markdown 轻量转换(配合 mammoth 输出)
3
+ *
4
+ * 只覆盖 mammoth 常见语义标签,不引入 turndown 依赖。
5
+ *
6
+ * @module harness/context/capabilities/document/html-to-md
7
+ */
8
+ /**
9
+ * 将 mammoth 语义 HTML 片段转为 Markdown
10
+ *
11
+ * @param html - HTML fragment
12
+ * @returns Markdown 文本
13
+ */
14
+ export function htmlFragmentToMarkdown(html) {
15
+ let s = html;
16
+ // 表格:先整表处理,避免单元格内标签被过早替换
17
+ s = s.replace(/<table\b[^>]*>[\s\S]*?<\/table>/gi, (table) => tableToMarkdown(table));
18
+ s = s.replace(/<br\s*\/?>/gi, '\n');
19
+ s = s.replace(/<hr\s*\/?>/gi, '\n\n---\n\n');
20
+ s = s.replace(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1>/gi, (_m, level, inner) => {
21
+ const text = inlineToMarkdown(inner).trim();
22
+ return `\n\n${'#'.repeat(Number(level))} ${text}\n\n`;
23
+ });
24
+ s = s.replace(/<p\b[^>]*>([\s\S]*?)<\/p>/gi, (_m, inner) => {
25
+ const text = inlineToMarkdown(inner).trim();
26
+ return text ? `\n\n${text}\n\n` : '\n\n';
27
+ });
28
+ // 列表
29
+ s = s.replace(/<ul\b[^>]*>([\s\S]*?)<\/ul>/gi, (_m, inner) => listToMarkdown(inner, false));
30
+ s = s.replace(/<ol\b[^>]*>([\s\S]*?)<\/ol>/gi, (_m, inner) => listToMarkdown(inner, true));
31
+ s = inlineToMarkdown(s);
32
+ s = s.replace(/\n{3,}/g, '\n\n').trim();
33
+ return s;
34
+ }
35
+ function inlineToMarkdown(input) {
36
+ let s = input;
37
+ s = s.replace(/<strong\b[^>]*>([\s\S]*?)<\/strong>/gi, '**$1**');
38
+ s = s.replace(/<b\b[^>]*>([\s\S]*?)<\/b>/gi, '**$1**');
39
+ s = s.replace(/<em\b[^>]*>([\s\S]*?)<\/em>/gi, '*$1*');
40
+ s = s.replace(/<i\b[^>]*>([\s\S]*?)<\/i>/gi, '*$1*');
41
+ s = s.replace(/<code\b[^>]*>([\s\S]*?)<\/code>/gi, '`$1`');
42
+ s = s.replace(/<a\b[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, '[$2]($1)');
43
+ s = s.replace(/<img\b[^>]*alt=["']([^"']*)["'][^>]*>/gi, '![$1]');
44
+ s = s.replace(/<img\b[^>]*>/gi, '');
45
+ // 去掉剩余标签,保留文本
46
+ s = s.replace(/<[^>]+>/g, '');
47
+ s = s
48
+ .replace(/&nbsp;/g, ' ')
49
+ .replace(/&lt;/g, '<')
50
+ .replace(/&gt;/g, '>')
51
+ .replace(/&amp;/g, '&')
52
+ .replace(/&quot;/g, '"')
53
+ .replace(/&#39;/g, "'");
54
+ return s;
55
+ }
56
+ function listToMarkdown(inner, ordered) {
57
+ const items = [];
58
+ const re = /<li\b[^>]*>([\s\S]*?)<\/li>/gi;
59
+ let m;
60
+ let n = 0;
61
+ while ((m = re.exec(inner)) !== null) {
62
+ n += 1;
63
+ const text = inlineToMarkdown(m[1]).trim().replace(/\n+/g, ' ');
64
+ items.push(ordered ? `${n}. ${text}` : `- ${text}`);
65
+ }
66
+ return `\n\n${items.join('\n')}\n\n`;
67
+ }
68
+ function tableToMarkdown(table) {
69
+ const rows = [];
70
+ const rowRe = /<tr\b[^>]*>([\s\S]*?)<\/tr>/gi;
71
+ let rm;
72
+ while ((rm = rowRe.exec(table)) !== null) {
73
+ const cells = [];
74
+ const cellRe = /<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi;
75
+ let cm;
76
+ while ((cm = cellRe.exec(rm[1])) !== null) {
77
+ cells.push(inlineToMarkdown(cm[1]).trim().replace(/\n+/g, ' ').replace(/\|/g, '\\|'));
78
+ }
79
+ if (cells.length)
80
+ rows.push(cells);
81
+ }
82
+ if (!rows.length)
83
+ return '\n\n';
84
+ const width = Math.max(...rows.map((r) => r.length));
85
+ const norm = rows.map((r) => {
86
+ const copy = [...r];
87
+ while (copy.length < width)
88
+ copy.push('');
89
+ return copy;
90
+ });
91
+ const lines = [
92
+ `| ${norm[0].join(' | ')} |`,
93
+ `| ${norm[0].map(() => '---').join(' | ')} |`,
94
+ ...norm.slice(1).map((r) => `| ${r.join(' | ')} |`),
95
+ ];
96
+ return `\n\n${lines.join('\n')}\n\n`;
97
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Document 公用能力门面
3
+ *
4
+ * 读路径:二进制/文档 → Markdown;写路径不在此层。
5
+ *
6
+ * @module harness/context/capabilities/document
7
+ */
8
+ export * from './types.js';
9
+ export { DocumentExtractError, isDocumentExtractError } from './errors.js';
10
+ export { DOCUMENT_EXTENSIONS, LEGACY_FORMATS, formatFromMagic, formatFromName, isDocumentPath, resolveFormat, } from './format.js';
11
+ export { htmlFragmentToMarkdown } from './html-to-md.js';
12
+ export { createDefaultBackends, createDefaultDocumentPort } from './port.js';
13
+ export { plainTextBackend } from './backends/plain.js';
14
+ export { pdfUnpdfBackend } from './backends/pdf.js';
15
+ export { docxMammothBackend } from './backends/docx.js';
16
+ export { sheetXlsxBackend } from './backends/sheet.js';
17
+ export { officeParserBackend } from './backends/office-parser.js';
18
+ export { xmindBackend, xmindJsonToMarkdown, xmindXmlToMarkdown } from './backends/xmind.js';
19
+ export { createSofficeLegacyConverter, probeSoffice, } from './legacy/soffice.js';
20
+ export { createLegacyConverterFromConfig } from './legacy/factory.js';
21
+ export type { SofficeLegacyOptions } from './legacy/soffice.js';
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Document 公用能力门面
3
+ *
4
+ * 读路径:二进制/文档 → Markdown;写路径不在此层。
5
+ *
6
+ * @module harness/context/capabilities/document
7
+ */
8
+ export * from './types.js';
9
+ export { DocumentExtractError, isDocumentExtractError } from './errors.js';
10
+ export { DOCUMENT_EXTENSIONS, LEGACY_FORMATS, formatFromMagic, formatFromName, isDocumentPath, resolveFormat, } from './format.js';
11
+ export { htmlFragmentToMarkdown } from './html-to-md.js';
12
+ export { createDefaultBackends, createDefaultDocumentPort } from './port.js';
13
+ export { plainTextBackend } from './backends/plain.js';
14
+ export { pdfUnpdfBackend } from './backends/pdf.js';
15
+ export { docxMammothBackend } from './backends/docx.js';
16
+ export { sheetXlsxBackend } from './backends/sheet.js';
17
+ export { officeParserBackend } from './backends/office-parser.js';
18
+ export { xmindBackend, xmindJsonToMarkdown, xmindXmlToMarkdown } from './backends/xmind.js';
19
+ export { createSofficeLegacyConverter, probeSoffice, } from './legacy/soffice.js';
20
+ export { createLegacyConverterFromConfig } from './legacy/factory.js';
@@ -0,0 +1,13 @@
1
+ import type { LegacyConverter } from '../types.js';
2
+ /**
3
+ * 按配置创建 legacy 转换器;converter=none 返回 null
4
+ *
5
+ * @param options - converter / sofficePath / timeoutMs
6
+ * @returns LegacyConverter | null
7
+ */
8
+ export declare function createLegacyConverterFromConfig(options: {
9
+ converter?: 'none' | 'soffice' | 'remote' | null;
10
+ sofficePath?: string | null;
11
+ timeoutMs?: number;
12
+ cacheDir?: string | null;
13
+ }): LegacyConverter | null;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * LegacyConverter 探测失败 / 配置工厂(无 soffice 时不抛)
3
+ */
4
+ import { createSofficeLegacyConverter } from './soffice.js';
5
+ /**
6
+ * 按配置创建 legacy 转换器;converter=none 返回 null
7
+ *
8
+ * @param options - converter / sofficePath / timeoutMs
9
+ * @returns LegacyConverter | null
10
+ */
11
+ export function createLegacyConverterFromConfig(options) {
12
+ if (!options.converter || options.converter === 'none')
13
+ return null;
14
+ if (options.converter === 'soffice') {
15
+ return createSofficeLegacyConverter({
16
+ sofficePath: options.sofficePath,
17
+ timeoutMs: options.timeoutMs,
18
+ cacheDir: options.cacheDir,
19
+ });
20
+ }
21
+ // remote(MinerU/WPS/云转换)后续接入
22
+ return null;
23
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * LibreOffice 老格式转换闸门(LegacyConverter)
3
+ *
4
+ * 将 .doc/.xls/.ppt 转为 OOXML 后走 T0 抽取;不常驻、用完即退。
5
+ *
6
+ * @module harness/context/capabilities/document/legacy/soffice
7
+ */
8
+ import type { LegacyConverter } from '../types.js';
9
+ export interface SofficeLegacyOptions {
10
+ /** soffice 可执行文件;缺省 PATH 上的 soffice */
11
+ sofficePath?: string | null;
12
+ /** 转换超时 ms(默认 60000) */
13
+ timeoutMs?: number;
14
+ /** 最大输入字节(默认 50MB) */
15
+ maxInputBytes?: number;
16
+ /** 转换件缓存目录;缺省不缓存 */
17
+ cacheDir?: string | null;
18
+ }
19
+ /**
20
+ * 创建 soffice LegacyConverter
21
+ *
22
+ * @param options - sofficePath / timeoutMs / maxInputBytes
23
+ * @returns LegacyConverter
24
+ */
25
+ export declare function createSofficeLegacyConverter(options?: SofficeLegacyOptions): LegacyConverter;
26
+ /**
27
+ * 探测 soffice 是否可用(`--version`)
28
+ *
29
+ * @param bin - 可执行名或路径
30
+ * @param timeoutMs - 探测超时
31
+ */
32
+ export declare function probeSoffice(bin: string, timeoutMs?: number): Promise<boolean>;