@hivemagnus/ardent 2.1.2 → 2.2.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.
@@ -0,0 +1,159 @@
1
+ import { createRequire } from 'node:module';
2
+ import { dirname, join, sep } from 'node:path';
3
+ import pdfMake from 'pdfmake';
4
+ import { ProvenNoEffectError } from './tools.js';
5
+ /**
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.
9
+ */
10
+ const docxWriter = undefined;
11
+ export const MAX_RENDER_SOURCE_CHARS = 200_000;
12
+ 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 });
16
+ }
17
+ const fontRoot = join(dirname(createRequire(import.meta.url).resolve('pdfmake/package.json')), 'build', 'fonts', 'Roboto');
18
+ let configured = false;
19
+ function configurePdfMake() {
20
+ if (configured)
21
+ return;
22
+ // Documents come from model output: never fetch a URL or read a file other than the bundled fonts.
23
+ pdfMake.setUrlAccessPolicy(() => false);
24
+ pdfMake.setLocalAccessPolicy(path => path.startsWith(fontRoot + sep));
25
+ pdfMake.setFonts({ Roboto: { normal: join(fontRoot, 'Roboto-Regular.ttf'), bold: join(fontRoot, 'Roboto-Medium.ttf'),
26
+ italics: join(fontRoot, 'Roboto-Italic.ttf'), bolditalics: join(fontRoot, 'Roboto-MediumItalic.ttf') } });
27
+ configured = true;
28
+ }
29
+ /** Bold, italics, inline code and links. Images keep only their alternative text. */
30
+ export function inlineMarkdown(source) {
31
+ const parts = [];
32
+ const pattern = /(`[^`]+`)|(\*\*[^*]+\*\*|__[^_]+__)|(\*[^*\s][^*]*\*|_[^_\s][^_]*_)|(!?\[[^\]]*\]\([^)\s]+\))/g;
33
+ let last = 0;
34
+ for (let match = pattern.exec(source); match; match = pattern.exec(source)) {
35
+ if (match.index > last)
36
+ parts.push(source.slice(last, match.index));
37
+ const token = match[0];
38
+ if (match[1])
39
+ parts.push({ text: token.slice(1, -1), background: '#eeeeee' });
40
+ else if (match[2])
41
+ parts.push({ text: token.slice(2, -2), bold: true });
42
+ else if (match[3])
43
+ parts.push({ text: token.slice(1, -1), italics: true });
44
+ else {
45
+ const link = /^(!?)\[([^\]]*)\]\(([^)\s]+)\)$/.exec(token);
46
+ const label = link?.[2] ?? token;
47
+ const url = link?.[3] ?? '';
48
+ if (link?.[1])
49
+ parts.push({ text: label ? `[${label}]` : '[image]', italics: true });
50
+ else if (/^https?:\/\//i.test(url))
51
+ parts.push({ text: label || url, link: url, decoration: 'underline' });
52
+ else
53
+ parts.push(label);
54
+ }
55
+ last = match.index + token.length;
56
+ }
57
+ if (last < source.length)
58
+ parts.push(source.slice(last));
59
+ return parts;
60
+ }
61
+ function cells(line) {
62
+ return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim());
63
+ }
64
+ /** Convert Markdown (headings, paragraphs, lists, quotes, tables, code and ```svg blocks) to pdfmake content. */
65
+ export function markdownToPdfContent(markdown) {
66
+ const lines = markdown.replace(/\r\n?/g, '\n').split('\n');
67
+ const content = [];
68
+ let paragraph = [];
69
+ const flush = () => {
70
+ if (paragraph.length)
71
+ content.push({ text: inlineMarkdown(paragraph.join(' ')), margin: [0, 0, 0, 8] });
72
+ paragraph = [];
73
+ };
74
+ for (let index = 0; index < lines.length; index++) {
75
+ const line = lines[index] ?? '';
76
+ const fence = /^\s*```\s*([A-Za-z0-9_+-]*)\s*$/.exec(line);
77
+ if (fence) {
78
+ flush();
79
+ const body = [];
80
+ for (index++; index < lines.length && !/^\s*```\s*$/.test(lines[index] ?? ''); index++)
81
+ body.push(lines[index] ?? '');
82
+ const code = body.join('\n');
83
+ if (fence[1]?.toLowerCase() === 'svg' && /<svg[\s>]/i.test(code))
84
+ content.push({ svg: code, fit: [480, 640], margin: [0, 0, 0, 8] });
85
+ else
86
+ content.push({ table: { widths: ['*'], body: [[{ text: code || ' ', fontSize: 9, preserveLeadingSpaces: true }]] },
87
+ layout: 'noBorders', fillColor: '#f4f4f4', margin: [0, 0, 0, 8] });
88
+ continue;
89
+ }
90
+ if (!line.trim()) {
91
+ flush();
92
+ continue;
93
+ }
94
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
95
+ if (heading) {
96
+ flush();
97
+ const level = heading[1]?.length ?? 1;
98
+ content.push({ text: inlineMarkdown(heading[2] ?? ''), bold: true, fontSize: [22, 18, 15, 13, 12, 11][level - 1] ?? 11, margin: [0, level <= 2 ? 10 : 6, 0, 6] });
99
+ continue;
100
+ }
101
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
102
+ flush();
103
+ content.push({ canvas: [{ type: 'line', x1: 0, y1: 0, x2: 515, y2: 0, lineWidth: 0.5, lineColor: '#999999' }], margin: [0, 4, 0, 8] });
104
+ continue;
105
+ }
106
+ if (/^\s*\|/.test(line) && /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/.test(lines[index + 1] ?? '')) {
107
+ flush();
108
+ const header = cells(line);
109
+ const rows = [];
110
+ for (index += 2; index < lines.length && /^\s*\|/.test(lines[index] ?? ''); index++)
111
+ rows.push(cells(lines[index] ?? ''));
112
+ index--;
113
+ const width = header.length;
114
+ content.push({ table: { headerRows: 1, widths: Array.from({ length: width }, () => '*'),
115
+ body: [header.map(cell => ({ text: inlineMarkdown(cell), bold: true })),
116
+ ...rows.map(row => Array.from({ length: width }, (_, column) => ({ text: inlineMarkdown(row[column] ?? '') })))] },
117
+ fontSize: 10, margin: [0, 0, 0, 8] });
118
+ continue;
119
+ }
120
+ const list = /^\s*([-*+]|\d+[.)])\s+/.exec(line);
121
+ if (list) {
122
+ flush();
123
+ const ordered = /\d/.test(list[1] ?? '');
124
+ const items = [];
125
+ for (; index < lines.length; index++) {
126
+ const item = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(lines[index] ?? '');
127
+ if (!item || /\d/.test(item[1] ?? '') !== ordered)
128
+ break;
129
+ items.push({ text: inlineMarkdown(item[2] ?? '') });
130
+ }
131
+ index--;
132
+ content.push(ordered ? { ol: items, margin: [0, 0, 0, 8] } : { ul: items, margin: [0, 0, 0, 8] });
133
+ continue;
134
+ }
135
+ if (/^\s*>/.test(line)) {
136
+ flush();
137
+ const quoted = [];
138
+ for (; index < lines.length && /^\s*>/.test(lines[index] ?? ''); index++)
139
+ quoted.push((lines[index] ?? '').replace(/^\s*>\s?/, ''));
140
+ index--;
141
+ content.push({ text: inlineMarkdown(quoted.join(' ')), italics: true, color: '#555555', margin: [12, 0, 0, 8] });
142
+ continue;
143
+ }
144
+ paragraph.push(line.trim());
145
+ }
146
+ flush();
147
+ return content.length ? content : [{ text: ' ' }];
148
+ }
149
+ /** Render Markdown to a PDF. Remote images and local files are never read. */
150
+ export async function renderPdf(markdown, title) {
151
+ configurePdfMake();
152
+ const definition = {
153
+ info: { title, creator: 'Ardent', producer: 'Ardent' },
154
+ pageSize: 'A4', pageMargins: [40, 48, 40, 48],
155
+ defaultStyle: { font: 'Roboto', fontSize: 11, lineHeight: 1.2 },
156
+ content: markdownToPdfContent(markdown)
157
+ };
158
+ return new Uint8Array(await pdfMake.createPdf(definition).getBuffer());
159
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Live reply text for running tasks.
3
+ *
4
+ * Backends report model output as it is generated. That text is not journaled:
5
+ * the task's final answer stays the only authoritative result. This module
6
+ * keeps the visible text of the current model step in memory while a task
7
+ * runs so clients can watch a reply form, and forgets it when the task ends.
8
+ */
9
+ /** Visible text in one model step. Structured output (JSON for tools or research) is never shown. */
10
+ export type StreamMode = 'pending' | 'plain' | 'structured';
11
+ export type PlainTextChunk = {
12
+ /** Model step the text belongs to. A new step starts a new reply segment. */
13
+ step: number;
14
+ /** Text this chunk makes visible; empty while undecided or structured. */
15
+ text: string;
16
+ /** True when this chunk revealed the start of plain text for the step. */
17
+ started: boolean;
18
+ };
19
+ /**
20
+ * Decides per model step whether output is a plain reply or structured data,
21
+ * from its first non-whitespace character, and passes through only plain text.
22
+ */
23
+ export declare class PlainTextFilter {
24
+ #private;
25
+ get step(): number;
26
+ get mode(): StreamMode;
27
+ /** Visible text of the current step so far. */
28
+ get text(): string;
29
+ push(chunk: string, step: number): PlainTextChunk;
30
+ }
31
+ export type LiveTextUpdate = {
32
+ kind: 'text';
33
+ step: number;
34
+ text: string;
35
+ } | {
36
+ kind: 'delta';
37
+ step: number;
38
+ text: string;
39
+ } | {
40
+ kind: 'end';
41
+ };
42
+ export type LiveTextListener = (update: LiveTextUpdate) => void;
43
+ export declare class LiveTextHub {
44
+ #private;
45
+ /** Record model output for a running task and notify subscribers of any visible text. */
46
+ push(taskId: string, chunk: string, step: number): void;
47
+ /** Visible text of the task's current step, if it is running and has shown any. */
48
+ snapshot(taskId: string): {
49
+ step: number;
50
+ text: string;
51
+ } | undefined;
52
+ /** Receive updates until the task ends or the returned function is called. */
53
+ subscribe(taskId: string, listener: LiveTextListener): () => void;
54
+ /** The task finished: tell subscribers and drop its live text. */
55
+ end(taskId: string): void;
56
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Live reply text for running tasks.
3
+ *
4
+ * Backends report model output as it is generated. That text is not journaled:
5
+ * the task's final answer stays the only authoritative result. This module
6
+ * keeps the visible text of the current model step in memory while a task
7
+ * runs so clients can watch a reply form, and forgets it when the task ends.
8
+ */
9
+ /**
10
+ * Decides per model step whether output is a plain reply or structured data,
11
+ * from its first non-whitespace character, and passes through only plain text.
12
+ */
13
+ export class PlainTextFilter {
14
+ #step = -1;
15
+ #mode = 'pending';
16
+ #text = '';
17
+ get step() { return this.#step; }
18
+ get mode() { return this.#mode; }
19
+ /** Visible text of the current step so far. */
20
+ get text() { return this.#mode === 'plain' ? this.#text : ''; }
21
+ push(chunk, step) {
22
+ if (step !== this.#step) {
23
+ this.#step = step;
24
+ this.#text = '';
25
+ this.#mode = 'pending';
26
+ }
27
+ if (this.#mode === 'structured')
28
+ return { step, text: '', started: false };
29
+ if (this.#mode === 'pending') {
30
+ const first = chunk.trimStart()[0];
31
+ if (!first) {
32
+ this.#text += chunk;
33
+ return { step, text: '', started: false };
34
+ }
35
+ this.#mode = first === '{' || first === '[' ? 'structured' : 'plain';
36
+ if (this.#mode === 'structured') {
37
+ this.#text = '';
38
+ return { step, text: '', started: false };
39
+ }
40
+ const text = this.#text + chunk;
41
+ this.#text = text;
42
+ return { step, text, started: true };
43
+ }
44
+ this.#text += chunk;
45
+ return { step, text: chunk, started: false };
46
+ }
47
+ }
48
+ /** Upper bound on retained live text per task; the final answer is stored separately. */
49
+ const MAX_LIVE_CHARS = 256_000;
50
+ export class LiveTextHub {
51
+ #tasks = new Map();
52
+ /** Record model output for a running task and notify subscribers of any visible text. */
53
+ push(taskId, chunk, step) {
54
+ let entry = this.#tasks.get(taskId);
55
+ if (!entry) {
56
+ entry = { filter: new PlainTextFilter(), listeners: new Set(), chars: 0 };
57
+ this.#tasks.set(taskId, entry);
58
+ }
59
+ const previousStep = entry.filter.step;
60
+ const out = entry.filter.push(chunk, step);
61
+ if (!out.text)
62
+ return;
63
+ if (out.started || step !== previousStep) {
64
+ entry.chars = out.text.length;
65
+ if (entry.chars > MAX_LIVE_CHARS)
66
+ return;
67
+ this.#emit(entry, { kind: 'text', step, text: out.text });
68
+ return;
69
+ }
70
+ entry.chars += out.text.length;
71
+ if (entry.chars > MAX_LIVE_CHARS)
72
+ return;
73
+ this.#emit(entry, { kind: 'delta', step, text: out.text });
74
+ }
75
+ /** Visible text of the task's current step, if it is running and has shown any. */
76
+ snapshot(taskId) {
77
+ const entry = this.#tasks.get(taskId);
78
+ if (!entry || !entry.filter.text || entry.chars > MAX_LIVE_CHARS)
79
+ return undefined;
80
+ return { step: entry.filter.step, text: entry.filter.text };
81
+ }
82
+ /** Receive updates until the task ends or the returned function is called. */
83
+ subscribe(taskId, listener) {
84
+ let entry = this.#tasks.get(taskId);
85
+ if (!entry) {
86
+ entry = { filter: new PlainTextFilter(), listeners: new Set(), chars: 0 };
87
+ this.#tasks.set(taskId, entry);
88
+ }
89
+ entry.listeners.add(listener);
90
+ return () => {
91
+ const current = this.#tasks.get(taskId);
92
+ current?.listeners.delete(listener);
93
+ if (current && !current.listeners.size && !current.filter.text && current.filter.step < 0)
94
+ this.#tasks.delete(taskId);
95
+ };
96
+ }
97
+ /** The task finished: tell subscribers and drop its live text. */
98
+ end(taskId) {
99
+ const entry = this.#tasks.get(taskId);
100
+ if (!entry)
101
+ return;
102
+ this.#tasks.delete(taskId);
103
+ this.#emit(entry, { kind: 'end' });
104
+ }
105
+ #emit(entry, update) {
106
+ for (const listener of entry.listeners) {
107
+ try {
108
+ listener(update);
109
+ }
110
+ catch { /* A failing subscriber must not affect the task. */ }
111
+ }
112
+ }
113
+ }
@@ -0,0 +1,22 @@
1
+ import { type ArtifactManifests } from './artifact-manifests.js';
2
+ import { type DevelopmentRecords } from './development.js';
3
+ import type { Task, TaskStore } from './store.js';
4
+ import { type ToolContext, type ToolRegistry } from './tools.js';
5
+ /** Tools a mission may be granted with a `tool:<name>` resource. */
6
+ export declare const MISSION_TOOL_NAMES: readonly ["team_handoff", "team_ask_user", "team_propose_decision", "artifact_write", "development_note", "document_render"];
7
+ export type MissionToolName = typeof MISSION_TOOL_NAMES[number];
8
+ export type MissionToolDeps = {
9
+ task: Task;
10
+ store: TaskStore;
11
+ artifacts: ArtifactManifests;
12
+ development: DevelopmentRecords;
13
+ /** Directory `artifact_write.workspace_path` resolves inside (the profile's `workspace`). */
14
+ workspaceDir: string;
15
+ };
16
+ /** `development_note`: a durable note about how the agent works. Direct tasks always have it; missions need `tool:development_note`. */
17
+ export declare function registerDevelopmentNoteTool(registry: ToolRegistry, deps: MissionToolDeps, contexts: readonly ToolContext[]): void;
18
+ /**
19
+ * Register the mission tools a mission grants. Coordination tools only record a
20
+ * journal event: Ardent never acts on a handoff, question or proposal itself.
21
+ */
22
+ export declare function registerMissionTools(registry: ToolRegistry, deps: MissionToolDeps, granted: ReadonlySet<string>): void;
@@ -0,0 +1,114 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, realpath } from 'node:fs/promises';
3
+ import { isAbsolute, join, relative, sep } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { ArtifactMimeSchema } from './artifact-manifests.js';
6
+ import { formatBytes } from './artifacts.js';
7
+ import { DevelopmentNoteInput } from './development.js';
8
+ import { MAX_RENDER_SOURCE_CHARS, renderDocx, renderPdf } from './document-render.js';
9
+ import { defineTool, ProvenNoEffectError } from './tools.js';
10
+ /** Tools a mission may be granted with a `tool:<name>` resource. */
11
+ export const MISSION_TOOL_NAMES = ['team_handoff', 'team_ask_user', 'team_propose_decision', 'artifact_write', 'development_note', 'document_render'];
12
+ const safeName = z.string().regex(/^[A-Za-z0-9._-]{1,128}$/, 'Use 1-128 letters, digits, dots, dashes or underscores');
13
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
14
+ const line = (max) => z.string().trim().min(1).max(max);
15
+ const Recorded = z.object({ recorded: z.literal(true), event: z.string(), note: z.string() }).strict();
16
+ const Registered = z.object({ artifact_id: z.string(), sha256: digest, reference: z.string(), name: z.string(), mime: z.string(),
17
+ size: z.number().int(), revision: z.number().int(), supersedes_sha256: digest.nullable() }).strict();
18
+ function registered(record) {
19
+ const manifest = record.manifest;
20
+ return { artifact_id: manifest.artifact_id, sha256: manifest.sha256, reference: `ardent-artifact:${manifest.sha256}`, name: manifest.name,
21
+ mime: manifest.mime, size: manifest.size, revision: manifest.revision, supersedes_sha256: manifest.supersedes_sha256 };
22
+ }
23
+ /** Read a regular file inside the workspace without following a final symlink. */
24
+ async function readWorkspaceFile(workspaceDir, path, maxBytes) {
25
+ if (isAbsolute(path) || path.split(/[\\/]/).includes('..'))
26
+ throw new ProvenNoEffectError('workspace_path must be relative to the workspace', 'INVALID_PATH');
27
+ let root;
28
+ let target;
29
+ try {
30
+ root = await realpath(workspaceDir);
31
+ target = await realpath(join(workspaceDir, path));
32
+ }
33
+ catch {
34
+ throw new ProvenNoEffectError('workspace_path does not exist', 'NOT_FOUND');
35
+ }
36
+ const inside = relative(root, target);
37
+ if (!inside || inside.startsWith(`..${sep}`) || inside === '..' || isAbsolute(inside))
38
+ throw new ProvenNoEffectError('workspace_path escapes the workspace', 'INVALID_PATH');
39
+ const file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
40
+ try {
41
+ const stat = await file.stat();
42
+ if (!stat.isFile())
43
+ throw new ProvenNoEffectError('workspace_path is not a regular file', 'INVALID_PATH');
44
+ if (stat.size > maxBytes)
45
+ throw new ProvenNoEffectError(`Artifact exceeds ${formatBytes(maxBytes)}`, 'ARTIFACT_TOO_LARGE');
46
+ return await file.readFile();
47
+ }
48
+ finally {
49
+ await file.close();
50
+ }
51
+ }
52
+ /** `development_note`: a durable note about how the agent works. Direct tasks always have it; missions need `tool:development_note`. */
53
+ export function registerDevelopmentNoteTool(registry, deps, contexts) {
54
+ registry.register(defineTool({ name: 'development_note', description: 'Record a durable note about your own development: what you learned, how you work best, or a method you changed. Kinds such as self_understanding, method, lesson. Do not store secrets.',
55
+ input: DevelopmentNoteInput, output: z.object({ id: z.string(), kind: z.string(), title: z.string() }).strict(),
56
+ effect: 'artifact-write', contexts, timeoutMs: 5_000, handler: async (input) => {
57
+ const record = deps.development.add({ ...input, author: 'agent', epistemic: 'agent_reported', taskId: deps.task.id });
58
+ return { id: record.id, kind: record.kind, title: record.title };
59
+ } }));
60
+ }
61
+ /**
62
+ * Register the mission tools a mission grants. Coordination tools only record a
63
+ * journal event: Ardent never acts on a handoff, question or proposal itself.
64
+ */
65
+ export function registerMissionTools(registry, deps, granted) {
66
+ const has = (name) => granted.has(`tool:${name}`);
67
+ const record = (event, detail, note) => {
68
+ deps.store.append(deps.task.id, event, detail);
69
+ return { recorded: true, event, note };
70
+ };
71
+ const maxBytes = deps.artifacts.artifacts.maxBytes;
72
+ if (has('team_handoff'))
73
+ registry.register(defineTool({ name: 'team_handoff', description: 'Ask the team coordinator to hand work to another team role. This records the request; the coordinator decides whether to start it.',
74
+ input: z.object({ to_role: line(128), objective: line(4000), deliverables: z.array(line(500)).max(16).optional(), note: line(2000).optional() }).strict(),
75
+ output: Recorded, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 5_000,
76
+ handler: async (input) => record('team_handoff', input, 'Handoff request recorded for the coordinator. Ardent does not start other agents; continue or finish your turn.') }));
77
+ if (has('team_ask_user'))
78
+ registry.register(defineTool({ name: 'team_ask_user', description: 'Ask the user a question you cannot answer from the mission or tools. Your turn ends after this call and the task finishes as input_required.',
79
+ input: z.object({ question: line(1200), options: z.array(line(300)).max(8).optional() }).strict(),
80
+ output: Recorded, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 5_000,
81
+ handler: async (input) => record('team_ask_user', input, 'Question recorded. Finish now with one short sentence for the user; the task ends as input_required.') }));
82
+ if (has('team_propose_decision'))
83
+ registry.register(defineTool({ name: 'team_propose_decision', description: 'Propose a team decision for the user to accept. This records the proposal; only the user decides.',
84
+ input: z.object({ title: line(200), statement: line(4000), rationale: line(4000).optional() }).strict(),
85
+ output: Recorded, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 5_000,
86
+ handler: async (input) => record('team_propose_decision', input, 'Decision proposal recorded for the user.') }));
87
+ if (has('artifact_write'))
88
+ registry.register(defineTool({ name: 'artifact_write', description: `Save a deliverable file (Markdown, text, JSON, CSV, SVG, PNG, JPEG, WebP, PDF or DOCX; at most ${formatBytes(maxBytes)}). Give exactly one of text, base64 or workspace_path. Set revises_sha256 to replace an earlier version.`,
89
+ input: z.object({ name: safeName, mime: ArtifactMimeSchema, text: z.string().min(1).max(maxBytes).optional(),
90
+ base64: z.string().min(1).max(Math.ceil(maxBytes / 3) * 4).regex(/^[A-Za-z0-9+/]+={0,2}$/).optional(),
91
+ workspace_path: line(512).optional(), revises_sha256: digest.optional() }).strict()
92
+ .refine(value => [value.text, value.base64, value.workspace_path].filter(item => item !== undefined).length === 1, 'Give exactly one of text, base64 or workspace_path'),
93
+ output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 30_000, handler: async (input) => {
94
+ const bytes = input.text !== undefined ? Buffer.from(input.text, 'utf8')
95
+ : input.base64 !== undefined ? Buffer.from(input.base64, 'base64')
96
+ : await readWorkspaceFile(deps.workspaceDir, input.workspace_path ?? '', maxBytes);
97
+ return registered(await deps.artifacts.register({ taskId: deps.task.id, name: input.name, mime: input.mime, bytes,
98
+ source: 'artifact_write', revisesSha256: input.revises_sha256 }));
99
+ } }));
100
+ if (has('development_note'))
101
+ registerDevelopmentNoteTool(registry, deps, ['mission']);
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.',
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
+ output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 60_000, handler: async (input) => {
106
+ const extension = `.${input.format}`;
107
+ const name = input.name.toLowerCase().endsWith(extension) ? input.name : `${input.name.slice(0, 128 - extension.length)}${extension}`;
108
+ const title = name.slice(0, -extension.length);
109
+ const bytes = input.format === 'pdf' ? await renderPdf(input.source_markdown, title) : await renderDocx(input.source_markdown, title);
110
+ return registered(await deps.artifacts.register({ taskId: deps.task.id, name,
111
+ mime: input.format === 'pdf' ? 'application/pdf' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
112
+ bytes, source: 'document_render', revisesSha256: input.revises_sha256 }));
113
+ } }));
114
+ }
@@ -0,0 +1,101 @@
1
+ import { z } from 'zod';
2
+ import type { ChatMessage } from './llamacpp.js';
3
+ import type { Task, TaskStore } from './store.js';
4
+ import { TeamMission, TeamResult, type TeamEnvelope } from './team-contract.js';
5
+ /** Bound on the combined text of a mission's context items. */
6
+ export declare const MAX_CONTEXT_ITEM_BYTES: number;
7
+ export declare const ContextItem: z.ZodObject<{
8
+ title: z.ZodString;
9
+ mime: z.ZodOptional<z.ZodString>;
10
+ text: z.ZodString;
11
+ }, z.core.$strict>;
12
+ export type ContextItem = z.infer<typeof ContextItem>;
13
+ export declare const MissionLabels: z.ZodRecord<z.ZodString, z.ZodString>;
14
+ export declare const MissionSubmit: z.ZodObject<{
15
+ session_id: z.ZodOptional<z.ZodString>;
16
+ objective: z.ZodString;
17
+ mission: z.ZodObject<{
18
+ id: z.ZodString;
19
+ revision: z.ZodNumber;
20
+ parent_task: z.ZodNullable<z.ZodString>;
21
+ constraints: z.ZodArray<z.ZodString>;
22
+ allowed_actions: z.ZodArray<z.ZodEnum<{
23
+ observe: "observe";
24
+ analyze: "analyze";
25
+ create_artifact: "create_artifact";
26
+ create_draft: "create_draft";
27
+ reversible_change: "reversible_change";
28
+ deploy: "deploy";
29
+ external_publish: "external_publish";
30
+ destructive_response: "destructive_response";
31
+ }>>;
32
+ resources: z.ZodArray<z.ZodString>;
33
+ deadline: z.ZodNumber;
34
+ acceptance_criteria: z.ZodArray<z.ZodString>;
35
+ expected_artifacts: z.ZodArray<z.ZodString>;
36
+ }, z.core.$strict>;
37
+ context_items: z.ZodOptional<z.ZodArray<z.ZodObject<{
38
+ title: z.ZodString;
39
+ mime: z.ZodOptional<z.ZodString>;
40
+ text: z.ZodString;
41
+ }, z.core.$strict>>>;
42
+ labels: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
43
+ idempotency_key: z.ZodString;
44
+ }, z.core.$strict>;
45
+ export type MissionSubmit = z.infer<typeof MissionSubmit>;
46
+ /** What a mission task journals at acceptance. */
47
+ export declare const MissionRecord: z.ZodObject<{
48
+ mission: z.ZodObject<{
49
+ id: z.ZodString;
50
+ revision: z.ZodNumber;
51
+ parent_task: z.ZodNullable<z.ZodString>;
52
+ constraints: z.ZodArray<z.ZodString>;
53
+ allowed_actions: z.ZodArray<z.ZodEnum<{
54
+ observe: "observe";
55
+ analyze: "analyze";
56
+ create_artifact: "create_artifact";
57
+ create_draft: "create_draft";
58
+ reversible_change: "reversible_change";
59
+ deploy: "deploy";
60
+ external_publish: "external_publish";
61
+ destructive_response: "destructive_response";
62
+ }>>;
63
+ resources: z.ZodArray<z.ZodString>;
64
+ deadline: z.ZodNumber;
65
+ acceptance_criteria: z.ZodArray<z.ZodString>;
66
+ expected_artifacts: z.ZodArray<z.ZodString>;
67
+ }, z.core.$strict>;
68
+ context_items: z.ZodArray<z.ZodObject<{
69
+ title: z.ZodString;
70
+ mime: z.ZodOptional<z.ZodString>;
71
+ text: z.ZodString;
72
+ }, z.core.$strict>>;
73
+ labels: z.ZodRecord<z.ZodString, z.ZodString>;
74
+ }, z.core.$strict>;
75
+ export type MissionRecord = z.infer<typeof MissionRecord>;
76
+ /** Accept a mission as a durable `mission` task. The mission and its context are journaled atomically with the task. */
77
+ export declare function acceptMission(accept: (input: {
78
+ prompt: string;
79
+ sessionId?: string;
80
+ idempotencyKey: string;
81
+ deadlineMs: number;
82
+ content: unknown;
83
+ onAccepted: (task: Task) => void;
84
+ }) => Task, store: TaskStore, input: MissionSubmit, nowMs?: number): Task;
85
+ /** The mission a task was accepted with, re-read from the journal. */
86
+ export declare function missionRecord(store: TaskStore, taskId: string): MissionRecord | undefined;
87
+ /** A team envelope view of a local mission, so mission tasks reuse the peer mission rules and result contract. */
88
+ export declare function missionEnvelope(task: Task, mission: TeamMission): TeamEnvelope;
89
+ /**
90
+ * Context items as completed tool transactions after the objective. The context
91
+ * fitter can then shorten or drop older items, never the policy or objective;
92
+ * the full items stay in the task journal.
93
+ */
94
+ export declare function contextItemMessages(items: readonly ContextItem[]): ChatMessage[];
95
+ /**
96
+ * The validated TeamResult of a finished mission task. A reply that carries a
97
+ * team_result is checked against the mission; anything else becomes a partial
98
+ * result whose summary is the reply. A recorded team_ask_user makes the result
99
+ * input_required. Artifacts always come from the task's own registrations.
100
+ */
101
+ export declare function missionTeamResult(store: TaskStore, task: Task, mission: TeamMission, answer: string, submitted?: unknown): TeamResult;