@hivemagnus/ardent 2.2.1 → 2.3.1

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/README.md CHANGED
@@ -333,9 +333,31 @@ tools only record a journal event; Ardent never acts on them itself:
333
333
  | `team_ask_user {question, options?}` | `team_ask_user` | Ends the turn; the result is `input_required` with a clarification |
334
334
  | `team_propose_decision {title, statement, rationale?}` | `team_propose_decision` | A proposal; only the user decides |
335
335
  | `artifact_write {name, mime, text \| base64 \| workspace_path, revises_sha256?}` | `artifact_registered` | Markdown, text, JSON, CSV, SVG, PNG, JPEG, WebP, PDF or DOCX, up to `artifacts.max_bytes`. `workspace_path` reads a file inside the profile's `workspace` |
336
- | `document_render {source_markdown, format: pdf \| docx, name}` | `artifact_registered` | Markdown (with ` ```svg ` figures) to PDF. DOCX is not available in this build |
336
+ | `document_render {source_markdown, format: pdf \| docx, name, revises_sha256?}` | `artifact_registered` | Markdown to PDF or DOCX, up to `artifacts.max_bytes`; see below |
337
337
  | `development_note {kind, title, body, sources?}` | `development_note` | Also available in direct tasks; see below |
338
338
 
339
+ `document_render` reads GitHub-flavoured Markdown: headings, paragraphs, bold,
340
+ italic, strikethrough, inline code, links, bulleted, numbered and task lists,
341
+ block quotes, code blocks, tables and horizontal rules. It never fetches a URL
342
+ or reads a file. PDF output draws ` ```svg ` blocks as vector figures; images
343
+ keep only their alternative text. DOCX output is written with
344
+ [`@hivemagnus/canvas-word-codec`](https://www.npmjs.com/package/@hivemagnus/canvas-word-codec):
345
+
346
+ - Headings use Word's Heading 1-6 styles, so they appear in the navigation
347
+ pane; links to `http(s)` URLs become hyperlinks and other link targets are
348
+ kept as text after the label.
349
+ - Bulleted lists and numbered lists that start at 1 use Word numbering. Word
350
+ numbering here has one level, so nested lists are indented, and a numbered
351
+ list that starts elsewhere or has nested content gets its numbers as text.
352
+ - Tables keep their header row, column alignment and inline formatting; a
353
+ table longer than 100 rows continues in another table.
354
+ - PNG and JPEG images given as `data:` URIs are embedded. Other images become
355
+ an `[image: alt]` placeholder and ` ```svg ` figures a short note, since
356
+ DOCX output does not embed vector figures.
357
+ - Raw HTML is kept as literal text. A document beyond the DOCX exchange
358
+ limits (for example more than 100 table columns) fails with
359
+ `DOCX_RENDER_FAILED` and no effect.
360
+
339
361
  Every registered artifact has an immutable manifest (digest, size, media type,
340
362
  revision, provenance and the artifact it supersedes). `revises_sha256` makes
341
363
  a new artifact a revision of an earlier one. `GET /api/v1/tasks/{id}/artifacts`
@@ -464,3 +486,19 @@ See [AGENTS.md](AGENTS.md) for contributor guidance.
464
486
 
465
487
  Apache-2.0. The vendored A2A protocol definition in `protocol/` carries its own
466
488
  license, [`protocol/LICENSE-A2A.txt`](protocol/LICENSE-A2A.txt).
489
+
490
+ ### Interoperability checks
491
+
492
+ Run `npm run interop` from this standalone checkout. The runner installs pinned
493
+ Python A2A SDKs and checks out an exact public Hermes revision in an ignored
494
+ cache; Python is used only for these tests. Both supported Node versions run
495
+ this suite in CI.
496
+
497
+ The suite exercises the real Python SDK and Hermes wire adapter in both
498
+ client/server directions. Team missions, lifecycle and child-budget transactions
499
+ use independent Python reference peers in `test/fixtures/team_reference.py`.
500
+ They implement the published Ardent wire contract; they do not load an external
501
+ Hermes team plugin or require a sibling Magnus checkout. The compatibility probe
502
+ explicitly enables `hermes_compat` and allows its combined functional workload
503
+ through the fixture's rate buckets. Default throttling remains covered by the
504
+ separate rate-limit tests.
@@ -4,6 +4,7 @@ export type DocxWriter = (markdown: string, options: {
4
4
  title: string;
5
5
  }) => Promise<Uint8Array>;
6
6
  export declare const MAX_RENDER_SOURCE_CHARS = 200000;
7
+ /** Render Markdown to DOCX. Rendering is local computation, so a failure has no effect. */
7
8
  export declare function renderDocx(markdown: string, title: string): Promise<Uint8Array>;
8
9
  type Inline = string | {
9
10
  text: string;
@@ -1,18 +1,32 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { dirname, join, sep } from 'node:path';
3
3
  import pdfMake from 'pdfmake';
4
+ import { documentSchema, exportDocx, WordCodecError } from '@hivemagnus/canvas-word-codec';
5
+ import { markdownToWordDocument } from './markdown-docx.js';
4
6
  import { ProvenNoEffectError } from './tools.js';
5
7
  /**
6
- * The DOCX writer. This build has none: `document_render` with `format: 'docx'`
7
- * fails with DOCX_UNAVAILABLE and no effect. Assign the canvas-word codec writer
8
- * here once that package is published; nothing else needs to change.
8
+ * The DOCX writer: Markdown is mapped to a Word exchange document and written by the
9
+ * canvas-word codec. The codec writes no document properties, so the title is not stored.
9
10
  */
10
- const docxWriter = undefined;
11
+ const docxWriter = async (markdown) => {
12
+ const { document, assets } = markdownToWordDocument(markdown);
13
+ const issue = documentSchema.safeParse(document).error?.issues[0];
14
+ if (issue)
15
+ throw new ProvenNoEffectError(`The Markdown is too large or complex for DOCX (${issue.path.join('.')}: ${issue.message})`, 'DOCX_RENDER_FAILED');
16
+ return new Uint8Array(await exportDocx(document, 'final', assets));
17
+ };
11
18
  export const MAX_RENDER_SOURCE_CHARS = 200_000;
19
+ /** Render Markdown to DOCX. Rendering is local computation, so a failure has no effect. */
12
20
  export async function renderDocx(markdown, title) {
13
- if (!docxWriter)
14
- throw new ProvenNoEffectError('DOCX rendering is not available in this build', 'DOCX_UNAVAILABLE');
15
- return docxWriter(markdown, { title });
21
+ try {
22
+ return await docxWriter(markdown, { title });
23
+ }
24
+ catch (error) {
25
+ if (error instanceof ProvenNoEffectError)
26
+ throw error;
27
+ const reason = error instanceof WordCodecError ? `${error.code}: ${error.message}` : error instanceof Error ? error.message : 'unknown error';
28
+ throw new ProvenNoEffectError(`The Markdown could not be rendered as DOCX (${reason.slice(0, 300)})`, 'DOCX_RENDER_FAILED');
29
+ }
16
30
  }
17
31
  const fontRoot = join(dirname(createRequire(import.meta.url).resolve('pdfmake/package.json')), 'build', 'fonts', 'Roboto');
18
32
  let configured = false;
@@ -0,0 +1,12 @@
1
+ import { type DocxAsset, type WordDocument } from '@hivemagnus/canvas-word-codec';
2
+ /** A Word exchange document built from Markdown, with the image bytes its runs reference. */
3
+ export type MarkdownWordDocument = {
4
+ document: WordDocument;
5
+ assets: Map<number, DocxAsset>;
6
+ };
7
+ /**
8
+ * Map Markdown (GFM: headings, paragraphs, emphasis, strikethrough, inline code, links, nested
9
+ * lists and task lists, block quotes, code blocks, tables and rules) to a Word exchange document.
10
+ * Images are embedded only from PNG or JPEG `data:` URIs; nothing is fetched or read.
11
+ */
12
+ export declare function markdownToWordDocument(markdown: string): MarkdownWordDocument;
@@ -0,0 +1,260 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { defaultLayout } from '@hivemagnus/canvas-word-codec';
3
+ import { Lexer } from 'marked';
4
+ const BODY_FONT = 'Calibri';
5
+ const BODY_SIZE = 14.67; // px: 11 pt
6
+ const MONO_FONT = 'Courier New';
7
+ const HEADING_SIZES = [29.33, 24, 20, 17.33, 16, 14.67];
8
+ const HEADING_LEVELS = [1, 2, 3, 4, 5, 6]; // px: 22, 18, 15, 13, 12, 11 pt
9
+ const LIST_INDENT = 48; // px: the codec's numbering indent (0.5 in)
10
+ const NEST_INDENT = 24;
11
+ const QUOTE_INDENT = 24;
12
+ const MAX_TABLE_ROWS = 100;
13
+ const MAX_IMAGE_DATA_CHARS = 16 * 1024 * 1024;
14
+ /** Narrow a lexer token by its type. Without extensions the lexer only emits the known token shapes. */
15
+ function is(token, type) {
16
+ return token.type === type;
17
+ }
18
+ function children(token) {
19
+ return 'tokens' in token ? token.tokens : undefined;
20
+ }
21
+ const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0', copy: '\u00a9',
22
+ reg: '\u00ae', trade: '\u2122', deg: '\u00b0', times: '\u00d7', middot: '\u00b7', ndash: '\u2013', mdash: '\u2014', hellip: '\u2026',
23
+ lsquo: '\u2018', rsquo: '\u2019', ldquo: '\u201c', rdquo: '\u201d', laquo: '\u00ab', raquo: '\u00bb', euro: '\u20ac' };
24
+ /** Resolve the character references the Markdown lexer leaves in text, in one pass. */
25
+ function decodeEntities(text) {
26
+ return text.replace(/&(#x[0-9a-f]{1,6}|#[0-9]{1,7}|[a-z]{2,8});/gi, (match, entity) => {
27
+ if (entity[0] !== '#')
28
+ return Object.hasOwn(NAMED_ENTITIES, entity) ? NAMED_ENTITIES[entity] ?? match : match;
29
+ const code = entity[1] === 'x' || entity[1] === 'X' ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
30
+ return code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff) ? String.fromCodePoint(code) : match;
31
+ });
32
+ }
33
+ /** Drop characters OOXML cannot carry; lone surrogates become U+FFFD. */
34
+ function xmlSafe(text) {
35
+ return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, '')
36
+ .replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, '\ufffd');
37
+ }
38
+ function httpUrl(href) {
39
+ if (href.length > 2048 || !/^https?:\/\//i.test(href) || !URL.canParse(href))
40
+ return undefined;
41
+ return href;
42
+ }
43
+ /** Width and height of base64 PNG or JPEG bytes from a `data:` URI; anything else is not embedded. */
44
+ function dataImage(href) {
45
+ const match = /^data:image\/(png|jpe?g);base64,([A-Za-z0-9+/=\s]+)$/i.exec(href.length <= MAX_IMAGE_DATA_CHARS ? href : '');
46
+ if (!match)
47
+ return undefined;
48
+ const bytes = Buffer.from(match[2] ?? '', 'base64');
49
+ if (bytes.length > 24 && bytes.readUInt32BE(0) === 0x89504e47 && bytes.readUInt32BE(4) === 0x0d0a1a0a && bytes.toString('latin1', 12, 16) === 'IHDR') {
50
+ const width = bytes.readUInt32BE(16);
51
+ const height = bytes.readUInt32BE(20);
52
+ return width && height ? { bytes, mediaType: 'image/png', width, height } : undefined;
53
+ }
54
+ if (bytes.length > 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
55
+ for (let offset = 2; offset + 9 < bytes.length;) {
56
+ if (bytes[offset] !== 0xff)
57
+ return undefined;
58
+ const marker = bytes[offset + 1] ?? 0;
59
+ if (marker === 0xff) {
60
+ offset++;
61
+ continue;
62
+ }
63
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
64
+ offset += 2;
65
+ continue;
66
+ }
67
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
68
+ const height = bytes.readUInt16BE(offset + 5);
69
+ const width = bytes.readUInt16BE(offset + 7);
70
+ return width && height ? { bytes, mediaType: 'image/jpeg', width, height } : undefined;
71
+ }
72
+ offset += 2 + bytes.readUInt16BE(offset + 2);
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+ class WordBuilder {
78
+ layout;
79
+ blocks = [];
80
+ assets = new Map();
81
+ nextId = 0;
82
+ contentWidth;
83
+ constructor(layout = defaultLayout()) {
84
+ this.layout = layout;
85
+ this.contentWidth = layout.width - layout.margins[1] - layout.margins[3];
86
+ }
87
+ id(prefix) { return `${prefix}${++this.nextId}`; }
88
+ run(text, style) { return { id: this.id('r'), text: xmlSafe(text), style }; }
89
+ paragraph(runs, style) {
90
+ return { type: 'paragraph', id: this.id('p'), style, runs: runs.length ? runs : [this.run('', {})] };
91
+ }
92
+ /** Inline tokens to runs; adjacent runs with the same style are merged. */
93
+ inline(tokens, style, ctx, runs = []) {
94
+ const text = (value, runStyle = style) => {
95
+ if (!value)
96
+ return;
97
+ const last = runs.at(-1);
98
+ if (last && !last.inlineImage && JSON.stringify(last.style) === JSON.stringify(runStyle))
99
+ last.text += xmlSafe(value);
100
+ else
101
+ runs.push(this.run(value, runStyle));
102
+ };
103
+ for (const token of tokens ?? []) {
104
+ if (is(token, 'text')) {
105
+ if (token.tokens?.length)
106
+ this.inline(token.tokens, style, ctx, runs);
107
+ else
108
+ text(decodeEntities(token.text));
109
+ }
110
+ else if (is(token, 'escape'))
111
+ text(token.text);
112
+ else if (is(token, 'strong'))
113
+ this.inline(token.tokens, { ...style, bold: true }, ctx, runs);
114
+ else if (is(token, 'em'))
115
+ this.inline(token.tokens, { ...style, italic: true }, ctx, runs);
116
+ else if (is(token, 'del'))
117
+ this.inline(token.tokens, { ...style, strikeout: true }, ctx, runs);
118
+ else if (is(token, 'codespan'))
119
+ text(token.text, { ...style, font: MONO_FONT, highlight: '#eeeeee' });
120
+ else if (is(token, 'br'))
121
+ text('\n');
122
+ else if (is(token, 'checkbox'))
123
+ text(token.checked ? '\u2612 ' : '\u2610 ');
124
+ else if (is(token, 'html'))
125
+ text(/^<br\s*\/?>$/i.test(token.text.trim()) ? '\n' : token.text);
126
+ else if (is(token, 'link')) {
127
+ const url = httpUrl(token.href);
128
+ if (url)
129
+ this.inline(token.tokens, { ...style, hyperlink: url, underline: true, color: '#0563c1' }, ctx, runs);
130
+ else {
131
+ this.inline(token.tokens, style, ctx, runs);
132
+ if (token.href && !token.href.startsWith('#') && token.href !== token.text)
133
+ text(` (${token.href})`);
134
+ }
135
+ }
136
+ else if (is(token, 'image')) {
137
+ const data = dataImage(token.href);
138
+ if (!data) {
139
+ text(token.text ? `[image: ${decodeEntities(token.text)}]` : '[image]', { ...style, italic: true });
140
+ continue;
141
+ }
142
+ const assetId = this.assets.size + 1;
143
+ this.assets.set(assetId, { bytes: data.bytes, mediaType: data.mediaType });
144
+ const scale = Math.min(1, (this.contentWidth - ctx.indent) / data.width, 16384 / data.height);
145
+ runs.push({ id: this.id('r'), text: '', style: {}, inlineImage: { assetId, sha256: createHash('sha256').update(data.bytes).digest('hex'),
146
+ alt: xmlSafe(decodeEntities(token.text)).slice(0, 2000), width: Math.max(1, Math.round(data.width * scale)), height: Math.max(1, Math.round(data.height * scale)) } });
147
+ }
148
+ else if (children(token)?.length)
149
+ this.inline(children(token), style, ctx, runs);
150
+ else if ('text' in token && typeof token.text === 'string')
151
+ text(decodeEntities(token.text));
152
+ }
153
+ return runs;
154
+ }
155
+ /** Paragraph style for body text at this nesting: quotes and list continuations indent. */
156
+ bodyStyle(ctx, extra = {}) {
157
+ return { after: ctx.depth ? 4 : 8, ...(ctx.indent ? { indent: ctx.indent } : {}), ...extra };
158
+ }
159
+ textStyle(ctx) { return ctx.quote ? { italic: true, color: '#555555' } : {}; }
160
+ block(token, ctx) {
161
+ if (is(token, 'space') || is(token, 'def'))
162
+ return;
163
+ if (is(token, 'heading')) {
164
+ const level = HEADING_LEVELS[Math.min(6, Math.max(1, token.depth)) - 1] ?? 1;
165
+ this.blocks.push(this.paragraph(this.inline(token.tokens, { bold: true, size: HEADING_SIZES[level - 1] ?? BODY_SIZE }, ctx), { heading: level, keepWithNext: true, before: level <= 2 ? 13 : 8, after: 6, ...(ctx.indent ? { indent: ctx.indent } : {}) }));
166
+ }
167
+ else if (is(token, 'code')) {
168
+ if (token.lang?.toLowerCase() === 'svg' && /<svg[\s>]/i.test(token.text))
169
+ this.blocks.push(this.paragraph([this.run('[SVG figure omitted: vector figures are rendered in PDF output only]', { italic: true, color: '#777777' })], this.bodyStyle(ctx)));
170
+ else
171
+ this.blocks.push(this.paragraph([this.run(token.text || ' ', { font: MONO_FONT, size: 12, highlight: '#f4f4f4' })], this.bodyStyle(ctx)));
172
+ }
173
+ else if (is(token, 'blockquote')) {
174
+ for (const child of token.tokens)
175
+ this.block(child, { ...ctx, indent: ctx.indent + QUOTE_INDENT, quote: true });
176
+ }
177
+ else if (is(token, 'list'))
178
+ this.list(token, ctx);
179
+ else if (is(token, 'table'))
180
+ this.table(token, ctx);
181
+ else if (is(token, 'hr'))
182
+ this.blocks.push(this.paragraph([this.run('* * *', { color: '#999999' })], { alignment: 'center', before: 4, after: 8 }));
183
+ else if (is(token, 'html')) {
184
+ if (token.text.trim())
185
+ this.blocks.push(this.paragraph([this.run(token.text.trim(), this.textStyle(ctx))], this.bodyStyle(ctx)));
186
+ }
187
+ else {
188
+ // A paragraph, the text of a tight list item, or anything else with inline content.
189
+ const runs = children(token) ? this.inline(children(token), this.textStyle(ctx), ctx)
190
+ : 'text' in token && typeof token.text === 'string' ? [this.run(decodeEntities(token.text), this.textStyle(ctx))] : [];
191
+ if (runs.length)
192
+ this.blocks.push(this.paragraph(runs, this.bodyStyle(ctx)));
193
+ }
194
+ }
195
+ /**
196
+ * Bulleted lists always use Word numbering. The codec writes single-level lists that restart
197
+ * whenever the list kind changes, so an ordered list uses Word numbering only when that numbers
198
+ * it correctly (it starts at 1, no nested blocks interrupt it, and it does not directly follow
199
+ * another numbered list); otherwise its numbers are written as text with a hanging indent.
200
+ */
201
+ list(list, ctx) {
202
+ const content = (item) => item.tokens.filter(token => token.type !== 'space' && token.type !== 'checkbox');
203
+ const previous = this.blocks.at(-1);
204
+ const start = typeof list.start === 'number' ? list.start : 1;
205
+ const native = !list.ordered || (start === 1 && list.items.every(item => content(item).length <= 1)
206
+ && !(previous?.type === 'paragraph' && previous.style.list === 'number'));
207
+ // Item text sits one numbering indent in at the top level and one hanging indent past its parent item's text.
208
+ const indent = ctx.indent + (ctx.depth ? NEST_INDENT : LIST_INDENT);
209
+ const nested = { indent, depth: ctx.depth + 1, quote: ctx.quote };
210
+ list.items.forEach((item, index) => {
211
+ const [first, ...rest] = content(item);
212
+ const checkbox = item.tokens.find(token => is(token, 'checkbox'));
213
+ const runs = [];
214
+ if (!native)
215
+ runs.push(this.run(`${start + index}.\t`, this.textStyle(ctx)));
216
+ if (checkbox)
217
+ runs.push(this.run(checkbox.checked ? '\u2612 ' : '\u2610 ', this.textStyle(ctx)));
218
+ if (first && (is(first, 'text') || is(first, 'paragraph')))
219
+ this.inline(first.tokens ?? [first], this.textStyle(ctx), nested, runs);
220
+ else if (first)
221
+ rest.unshift(first);
222
+ const style = native ? { list: list.ordered ? 'number' : 'bullet', after: 4 } : { indent, firstLineIndent: -NEST_INDENT, after: 4 };
223
+ if (native && indent !== LIST_INDENT)
224
+ style.indent = indent;
225
+ this.blocks.push(this.paragraph(runs, style));
226
+ for (const child of rest)
227
+ this.block(child, nested);
228
+ });
229
+ }
230
+ /** Tables keep their header row, alignment and inline formatting; long tables are split every 100 rows. */
231
+ table(table, ctx) {
232
+ const columns = table.header.length;
233
+ const width = Math.max(1, Math.floor((this.contentWidth - ctx.indent) / columns));
234
+ const row = (cells, header) => ({ id: this.id('tr'), cells: Array.from({ length: columns }, (_, column) => {
235
+ const cell = cells[column];
236
+ const align = table.align[column];
237
+ // An image in a cell is scaled to the cell width.
238
+ const runs = this.inline(cell?.tokens, header ? { bold: true } : {}, { ...ctx, indent: this.contentWidth - width });
239
+ return { id: this.id('tc'), paragraphs: [this.paragraph(runs, align ? { alignment: align } : {})] };
240
+ }) });
241
+ const rows = [row(table.header, true), ...table.rows.map(cells => row(cells, false))];
242
+ for (let offset = 0; offset < rows.length; offset += MAX_TABLE_ROWS)
243
+ this.blocks.push({ type: 'table', id: this.id('t'), widths: Array.from({ length: columns }, () => width), rows: rows.slice(offset, offset + MAX_TABLE_ROWS) });
244
+ this.blocks.push(this.paragraph([], { after: 4 }));
245
+ }
246
+ }
247
+ /**
248
+ * Map Markdown (GFM: headings, paragraphs, emphasis, strikethrough, inline code, links, nested
249
+ * lists and task lists, block quotes, code blocks, tables and rules) to a Word exchange document.
250
+ * Images are embedded only from PNG or JPEG `data:` URIs; nothing is fetched or read.
251
+ */
252
+ export function markdownToWordDocument(markdown) {
253
+ const builder = new WordBuilder({ ...defaultLayout(), font: BODY_FONT, fontSize: BODY_SIZE });
254
+ const tokens = new Lexer({ gfm: true }).lex(markdown.replace(/\r\n?/g, '\n'));
255
+ for (const token of tokens)
256
+ builder.block(token, { indent: 0, depth: 0, quote: false });
257
+ if (!builder.blocks.length)
258
+ builder.blocks.push(builder.paragraph([], {}));
259
+ return { document: { schemaVersion: 1, layout: builder.layout, changes: [], comments: [], blocks: builder.blocks }, assets: builder.assets };
260
+ }
@@ -100,7 +100,7 @@ export function registerMissionTools(registry, deps, granted) {
100
100
  if (has('development_note'))
101
101
  registerDevelopmentNoteTool(registry, deps, ['mission']);
102
102
  if (has('document_render'))
103
- registry.register(defineTool({ name: 'document_render', description: 'Render Markdown (with ```svg blocks for vector figures) to a PDF or DOCX deliverable and save it as an artifact.',
103
+ registry.register(defineTool({ name: 'document_render', description: 'Render Markdown to a PDF or DOCX deliverable and save it as an artifact. ```svg blocks become vector figures in PDF only; images are embedded in DOCX only from PNG or JPEG data: URIs.',
104
104
  input: z.object({ source_markdown: z.string().min(1).max(MAX_RENDER_SOURCE_CHARS), format: z.enum(['pdf', 'docx']), name: safeName, revises_sha256: digest.optional() }).strict(),
105
105
  output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 60_000, handler: async (input) => {
106
106
  const extension = `.${input.format}`;
package/dist/news.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { lookup } from 'node:dns/promises';
3
3
  import { BlockList, isIP } from 'node:net';
4
+ import { parse } from 'parse5';
4
5
  import { z } from 'zod';
5
6
  import { resolveReference } from './config.js';
6
7
  import { ArtifactSchema } from './artifacts.js';
@@ -173,14 +174,29 @@ export function newsStructuredPublicationTime(html, sourceUrl) {
173
174
  dates.add(new Date(published).toISOString());
174
175
  date ??= published;
175
176
  };
176
- const scripts = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
177
- for (let count = 0, match; count < 32 && (match = scripts.exec(html)); count++) {
178
- if (!/\btype\s*=\s*["']application\/ld\+json["']/i.test(match[1]) || Buffer.byteLength(match[2]) > 65_536)
179
- continue;
180
- try {
181
- visit(JSON.parse(match[2]), 0);
177
+ // Parse actual HTML elements: comments, raw text and lookalike attributes
178
+ // must not become publisher evidence. Walk iteratively to bound call depth.
179
+ const pending = [parse(html, { sourceCodeLocationInfo: true })];
180
+ let scripts = 0;
181
+ while (pending.length && scripts < 32) {
182
+ const node = pending.pop();
183
+ if ('tagName' in node && node.tagName === 'script') {
184
+ scripts++;
185
+ if (node.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !node.sourceCodeLocation?.endTag ||
186
+ node.attrs.find(attr => attr.name === 'type')?.value.toLowerCase() !== 'application/ld+json')
187
+ continue;
188
+ const text = node.childNodes.map(child => 'value' in child ? child.value : '').join('');
189
+ if (Buffer.byteLength(text) > 65_536)
190
+ continue;
191
+ try {
192
+ visit(JSON.parse(text), 0);
193
+ }
194
+ catch { /* Malformed publisher data remains unknown. */ }
195
+ }
196
+ else if ('childNodes' in node) {
197
+ for (let index = node.childNodes.length - 1; index >= 0; index--)
198
+ pending.push(node.childNodes[index]);
182
199
  }
183
- catch { /* Malformed publisher data remains unknown. */ }
184
200
  }
185
201
  return nodes <= 64 && dates.size === 1 ? date : null;
186
202
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/ardent",
3
- "version": "2.2.1",
3
+ "version": "2.3.1",
4
4
  "description": "Headless TypeScript agent runtime with A2A, scheduled jobs, skills, chat channels, and a plugin API",
5
5
  "keywords": [
6
6
  "agent",
@@ -73,12 +73,15 @@
73
73
  "@a2a-js/sdk": "1.3.0",
74
74
  "@bufbuild/protobuf": "2.16.0",
75
75
  "@grpc/grpc-js": "1.14.7",
76
+ "@hivemagnus/canvas-word-codec": "1.1.0",
76
77
  "@hivemagnus/emberfold": "0.1.0",
77
78
  "@hono/node-server": "^2.1.5",
78
79
  "better-sqlite3": "^13.0.3",
79
80
  "dotenv": "^18.0.9",
80
81
  "express": "5.3.0",
81
82
  "hono": "^4.13.16",
83
+ "marked": "18.1.1",
84
+ "parse5": "8.1.1",
82
85
  "pdfmake": "0.3.13",
83
86
  "ws": "^8.22.0",
84
87
  "yaml": "2.9.1",