From e49fc9d835395b7cec03bc2231b73f79b4c368b8 Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Sat, 7 Nov 2026 08:57:19 +0100 Subject: [PATCH 01/13] feat(document-studio): module de studio de documents V0 (AGENT-1578) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Module document-studio : 11 Workflows (plan, draft, render, finalize, publish, cancel, export, profile-save, list, review-read, template-read) et la MiniApp document-studio-review. Gabarits quote et meeting-minutes copiés du contrat template/v1 (PIN), rendu par artifact_render_v1, étapes JavaScript testées sous Node avec Storage et rendu simulés. Inventaire, catalogue et suites de test enregistrés. Co-Authored-By: Claude Opus 5.5 --- catalog.json | 75 ++ catalog/document-studio.yaml | 19 + document-studio/README.md | 95 ++ .../main/miniapps/document-studio-review.json | 200 ++++ .../workflows/document-studio-cancel.json | 102 +++ .../main/workflows/document-studio-draft.json | 145 +++ .../workflows/document-studio-export.json | 75 ++ .../workflows/document-studio-finalize.json | 91 ++ .../main/workflows/document-studio-list.json | 53 ++ .../main/workflows/document-studio-plan.json | 105 +++ .../document-studio-profile-save.json | 51 ++ .../workflows/document-studio-publish.json | 92 ++ .../workflows/document-studio-render.json | 71 ++ .../document-studio-review-read.json | 69 ++ .../document-studio-template-read.json | 36 + document-studio/examples/profile.example.json | 40 + .../meeting-minutes/examples/default.json | 26 + .../meeting-minutes/examples/minimal.json | 44 + .../meeting-minutes/fragments/footer.typ | 14 + .../meeting-minutes/fragments/header.typ | 26 + .../fragments/legal-mentions.typ | 12 + .../meeting-minutes/fragments/lines-table.typ | 18 + .../meeting-minutes/input.schema.json | 45 + .../templates/meeting-minutes/main.typ | 53 ++ .../templates/meeting-minutes/manifest.json | 41 + .../templates/quote/examples/default.json | 43 + .../templates/quote/fragments/footer.typ | 14 + .../templates/quote/fragments/header.typ | 26 + .../quote/fragments/legal-mentions.typ | 12 + .../templates/quote/fragments/lines-table.typ | 18 + .../templates/quote/input.schema.json | 62 ++ .../examples/templates/quote/main.typ | 82 ++ .../examples/templates/quote/manifest.json | 22 + document-studio/module.yaml | 88 ++ inventory/modules.json | 304 +++++++ modules.json | 7 + scripts/inventory.py | 2 + scripts/test.py | 6 +- tooling/document-studio/build.py | 857 ++++++++++++++++++ tooling/document-studio/contract/PIN.json | 122 +++ tooling/document-studio/contract/i18n.fr.json | 35 + tooling/document-studio/tests/test_module.py | 520 +++++++++++ 42 files changed, 3815 insertions(+), 3 deletions(-) create mode 100644 catalog/document-studio.yaml create mode 100644 document-studio/README.md create mode 100644 document-studio/agents/main/miniapps/document-studio-review.json create mode 100644 document-studio/agents/main/workflows/document-studio-cancel.json create mode 100644 document-studio/agents/main/workflows/document-studio-draft.json create mode 100644 document-studio/agents/main/workflows/document-studio-export.json create mode 100644 document-studio/agents/main/workflows/document-studio-finalize.json create mode 100644 document-studio/agents/main/workflows/document-studio-list.json create mode 100644 document-studio/agents/main/workflows/document-studio-plan.json create mode 100644 document-studio/agents/main/workflows/document-studio-profile-save.json create mode 100644 document-studio/agents/main/workflows/document-studio-publish.json create mode 100644 document-studio/agents/main/workflows/document-studio-render.json create mode 100644 document-studio/agents/main/workflows/document-studio-review-read.json create mode 100644 document-studio/agents/main/workflows/document-studio-template-read.json create mode 100644 document-studio/examples/profile.example.json create mode 100644 document-studio/examples/templates/meeting-minutes/examples/default.json create mode 100644 document-studio/examples/templates/meeting-minutes/examples/minimal.json create mode 100644 document-studio/examples/templates/meeting-minutes/fragments/footer.typ create mode 100644 document-studio/examples/templates/meeting-minutes/fragments/header.typ create mode 100644 document-studio/examples/templates/meeting-minutes/fragments/legal-mentions.typ create mode 100644 document-studio/examples/templates/meeting-minutes/fragments/lines-table.typ create mode 100644 document-studio/examples/templates/meeting-minutes/input.schema.json create mode 100644 document-studio/examples/templates/meeting-minutes/main.typ create mode 100644 document-studio/examples/templates/meeting-minutes/manifest.json create mode 100644 document-studio/examples/templates/quote/examples/default.json create mode 100644 document-studio/examples/templates/quote/fragments/footer.typ create mode 100644 document-studio/examples/templates/quote/fragments/header.typ create mode 100644 document-studio/examples/templates/quote/fragments/legal-mentions.typ create mode 100644 document-studio/examples/templates/quote/fragments/lines-table.typ create mode 100644 document-studio/examples/templates/quote/input.schema.json create mode 100644 document-studio/examples/templates/quote/main.typ create mode 100644 document-studio/examples/templates/quote/manifest.json create mode 100644 document-studio/module.yaml create mode 100644 tooling/document-studio/build.py create mode 100644 tooling/document-studio/contract/PIN.json create mode 100644 tooling/document-studio/contract/i18n.fr.json create mode 100644 tooling/document-studio/tests/test_module.py diff --git a/catalog.json b/catalog.json index df3cc78..f4f52cf 100644 --- a/catalog.json +++ b/catalog.json @@ -640,6 +640,81 @@ "workflows": 10, "miniapps": 6 }, + { + "key": "document-studio", + "name": "Document studio", + "version": "0.1.0", + "subpath": "document-studio", + "manifest": "document-studio/module.yaml", + "manifest_sha256": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", + "tree_sha256": "482bcfbdc1e544c43c8f61962fae37359f2464af1168969945e8178131658863", + "description": { + "en": "Document studio: draft business documents from a brief, render them to PDF from templates and the company profile, review, approve and issue them with a number, and keep every revision in Storage.", + "fr": "Studio de documents : rédiger des documents professionnels depuis un brief, les rendre en PDF avec des gabarits et la fiche entreprise, les relire, les approuver et les émettre avec un numéro, en gardant chaque révision dans Storage." + }, + "capabilities": [ + "documents", + "templates", + "pdf", + "review", + "numbering", + "storage" + ], + "actions": [ + { + "key": "document-studio-plan", + "name": "Plan a document" + }, + { + "key": "document-studio-draft", + "name": "Draft a document" + }, + { + "key": "document-studio-render", + "name": "Render a document preview" + }, + { + "key": "document-studio-finalize", + "name": "Approve a document" + }, + { + "key": "document-studio-publish", + "name": "Issue a document" + }, + { + "key": "document-studio-cancel", + "name": "Cancel a document" + }, + { + "key": "document-studio-export", + "name": "Export a document" + }, + { + "key": "document-studio-profile-save", + "name": "Save the company profile" + } + ], + "queries": [ + "document-studio-list", + "document-studio-review-read", + "document-studio-template-read" + ], + "requires": { + "runtimes": [ + "deno" + ], + "language_model": true, + "connectors": [], + "credentials": [], + "modules": [] + }, + "price": { + "model": "free" + }, + "maturity": "preview", + "workflows": 11, + "miniapps": 1 + }, { "key": "image-studio", "name": "Image studio", diff --git a/catalog/document-studio.yaml b/catalog/document-studio.yaml new file mode 100644 index 0000000..c9ef89a --- /dev/null +++ b/catalog/document-studio.yaml @@ -0,0 +1,19 @@ +{ + "capabilities": [ + "documents", + "templates", + "pdf", + "review", + "numbering", + "storage" + ], + "credentials": [], + "description": { + "en": "Document studio: draft business documents from a brief, render them to PDF from templates and the company profile, review, approve and issue them with a number, and keep every revision in Storage.", + "fr": "Studio de documents : rédiger des documents professionnels depuis un brief, les rendre en PDF avec des gabarits et la fiche entreprise, les relire, les approuver et les émettre avec un numéro, en gardant chaque révision dans Storage." + }, + "price": { + "model": "free" + }, + "schema": "agentmaurice.module_catalog_entry/v1" +} diff --git a/document-studio/README.md b/document-studio/README.md new file mode 100644 index 0000000..a6ff4e1 --- /dev/null +++ b/document-studio/README.md @@ -0,0 +1,95 @@ +# Document studio + +Module réutilisable qui transforme un brief en document professionnel (devis, +compte rendu de réunion) : brouillon, rendu PDF à partir d'un gabarit et de la +fiche entreprise, relecture, approbation, émission avec un numéro. Tout vit +dans Storage ; rien n'est envoyé à l'extérieur. + +Le Module ne contient aucun moteur de rendu. Le rendu passe par le tool MCP +`artifact--artifact_render_v1` (mode `preview` pour les brouillons, `final` pour +l'émission). Les étapes de code sont du JavaScript (`code_execution`) : pas de +WASM en V0. Aucun binaire n'est versionné ici (ni PDF ni PNG). + +## Workflows + +| Workflow | Rôle | +|---|---| +| `document-studio-plan` | choisit le gabarit d'après un brief, propose un titre, liste les données manquantes et les questions à poser. N'écrit rien | +| `document-studio-draft` | remplit les données du gabarit (appel modèle, puis validation stricte) et crée le dossier du document au statut `draft`. Pour un devis, les montants et les totaux sont calculés ici, en centimes entiers, à partir des lignes : le modèle ne fournit que des quantités et des prix | +| `document-studio-render` | rend l'état courant (PDF et aperçus PNG) et ajoute une révision. `data_patch` fusionne (superficiellement) des corrections dans les données, qui sont revalidées. Un document émis ou annulé ne se rend plus (`document_locked`) | +| `document-studio-finalize` | `draft` vers `approved`. Exige un rendu de la révision courante et `confirmation_manuelle` | +| `document-studio-publish` | exige `approved` et `confirmation_manuelle`. Réserve le prochain numéro, rend en mode `final`, enregistre le PDF émis, passe à `issued` | +| `document-studio-cancel` | passe à `cancelled` avec un motif. Un numéro émis n'est jamais réutilisé | +| `document-studio-export` | copie le PDF émis (ou le dernier rendu, signalé comme brouillon) vers un chemin Storage hors de `/document-studio/`, avec son empreinte SHA-256. Mail et SFTP sont hors V0 | +| `document-studio-profile-save` | valide et enregistre la fiche entreprise et la charte (`/document-studio/profile.json`), avec confirmation manuelle | +| `document-studio-list` | liste des documents (identifiant, titre, statut, numéro, révision, dernière empreinte) | +| `document-studio-review-read` | dossier complet d'un document et aperçus du dernier rendu, pour la MiniApp | +| `document-studio-template-read` | liste des gabarits, ou manifeste et schémas de données d'un gabarit | + +La MiniApp `document-studio-review` charge un document par son identifiant, +affiche statut, révision, numéro, pages et le tableau des rendus (révision, +mode, empreinte, chemin), et relance un rendu. L'approbation et l'émission +passent par les formulaires des Workflows, avec la confirmation manuelle. + +## Cycle de vie + +`draft` (rendus successifs) → `approved` → `issued`. `cancelled` est possible +depuis tous les autres statuts. Un nouveau rendu d'un document `approved` le +ramène à `draft` : l'approbation est à refaire. La confirmation manuelle est +le champ de formulaire `confirmation_manuelle` (`oui` ou `non`) ; sans `oui`, +le Workflow refuse (`manual_confirmation_required`) avant toute lecture ou +écriture. Le Module n'approuve jamais à la place d'une personne. + +## Stockage + +- `/document-studio/profile.json` : la charte, au schéma `{schema_version: 1, company, brand}` du contrat de gabarit. Un exemple fictif est dans `examples/profile.example.json`. +- `/document-studio/docs//record.json` : le dossier (`document-studio.record/v1`) : statut, numéro, révision (+1 à chaque écriture), données, historique, rendus (chemin, SHA-256, aperçus, provenance), émission. +- `/document-studio/docs//r/` : PDF et aperçus d'un rendu. +- `/document-studio/docs//issued/.pdf` : le PDF émis. +- `/document-studio/numbers///.json` : jeton de numéro. + +`doc_id` : `^[a-z0-9][a-z0-9-]{0,47}$`, choisi par l'appelant ou dérivé du +titre avec un suffixe court. Numéro : `--` (`DEV` pour le +devis, `CR` pour le compte rendu). + +Sans fiche entreprise, `render` et `publish` échouent avec `profile_missing` : +enregistrez la charte par `document-studio-profile-save`. + +## Gabarits + +`examples/templates/quote` et `examples/templates/meeting-minutes` sont des +copies des gabarits de référence du contrat `agentmaurice.template/v1`, avec +les fragments partagés qu'ils importent. `tooling/document-studio/contract/PIN.json` +note le commit du contrat d'origine et l'empreinte de chaque fichier. Un seul +fichier diffère de l'original : `quote/main.typ`, qui ajoute la mention +« Ce document est un devis, ce n'est pas une facture ». Le contrôle du contrat se lance +avec le script `template_check.py` de ce contrat (`check `) ; la CI de ce dépôt est +hors ligne et ne dépend pas de lui. + +Les gabarits sont embarqués en texte dans les Workflows qui rendent. Leurs +accolades y sont écrites en séquences d'échappement, car le moteur de Workflows +lirait une double accolade dans le code comme une action de gabarit. + +Données d'un devis : le brouillon porte des nombres (`quantity`, `unit_price_ht`, +`vat_rate`), jamais des montants formatés ni des totaux. Au rendu, le Workflow +produit les chaînes attendues par le gabarit (`1 250,00 €`) et les totaux HT, TVA par taux et TTC. + +## Régénération et tests + +``` +python3 tooling/document-studio/build.py +python3 -m unittest discover -s tooling/document-studio/tests -p 'test_*.py' +``` + +Les tests exécutent chaque étape JavaScript sous Node, avec un Storage et un +moteur de rendu simulés, sur des données synthétiques. Ils ne prouvent pas le +comportement sur un One. + +## Limites connues (V0) + +- La charte est lue dans Storage seulement. Le Module `profile` garde la fiche dans un enregistrement d'application, dont le broker n'est pas encore câblé dans le One : l'appel du Workflow `cib-profile-read` fait échouer le rendu tant qu'il en est ainsi. +- Le logo est une référence (`storage://…`) ; ce Module ne la résout pas en fichier avant le rendu. +- La réservation d'un numéro n'est pas atomique : elle liste, écrit sans écrasement, relit et vérifie le propriétaire, 5 essais au plus (`number_conflict`). Un numéro réservé puis perdu (rendu en échec) reste réservé : il est repris au nouvel essai, jamais réutilisé par un autre document. +- Pas d'envoi (mail, SFTP), pas de DOCX, une seule langue (`fr`). +- `document-studio-export` lit le PDF en base64 par `read_file` ; si le runtime ne le permet pas, l'export échoue sur l'empreinte (`export_integrity_failed`). +- Pas de carte `document` du Viewer pour l'aperçu dans le chat : à vérifier ensuite. diff --git a/document-studio/agents/main/miniapps/document-studio-review.json b/document-studio/agents/main/miniapps/document-studio-review.json new file mode 100644 index 0000000..e4b3e62 --- /dev/null +++ b/document-studio/agents/main/miniapps/document-studio-review.json @@ -0,0 +1,200 @@ +{ + "$schema": "agentmaurice.miniapp/v2", + "schema_version": 2, + "miniapp_id": "document-studio-review", + "kind": "miniapp", + "title": "Document studio", + "version": "1", + "description": "Relire un document, relancer un rendu, l'approuver puis l'émettre.", + "ui": { + "renderer": "component", + "component": "document-studio-review", + "configuration": { + "layout": [ + { + "type": "callout", + "title": "Relecture humaine", + "tone": "info", + "value": "Chargez un document par son identifiant, relisez les rendus, puis approuvez et émettez avec une confirmation manuelle. Un document émis est verrouillé et son numéro n'est jamais réutilisé." + }, + { + "type": "button", + "label": "Charger le document", + "on_click": "load" + }, + { + "type": "section", + "title": "Document", + "children": [ + { + "type": "kpi_grid", + "items": [ + { + "label": "Statut", + "value": { + "state": "review.status" + } + }, + { + "label": "Révision", + "value": { + "state": "review.revision" + } + }, + { + "label": "Numéro", + "value": { + "state": "review.number" + } + }, + { + "label": "Pages", + "value": { + "state": "review.pages" + } + } + ] + }, + { + "type": "stat", + "label": "Titre", + "value": { + "state": "review.title" + } + }, + { + "type": "table", + "columns": [ + "revision", + "mode", + "sha256", + "path" + ], + "column_labels": { + "revision": "Révision", + "mode": "Mode", + "sha256": "Empreinte SHA-256", + "path": "Chemin" + }, + "rows": { + "state": "review.renders" + } + } + ] + }, + { + "type": "section", + "title": "Actions", + "children": [ + { + "type": "button", + "label": "Nouveau rendu", + "on_click": "render" + }, + { + "type": "text", + "value": "Approuver et Émettre ouvrent un formulaire de confirmation manuelle dans les interactions disponibles." + }, + { + "type": "text", + "value": { + "state": "result.message" + } + } + ] + } + ] + } + }, + "state_schema": { + "type": "object", + "properties": { + "doc_id": { + "type": "string" + }, + "confirmation_manuelle": { + "type": "string" + }, + "review": { + "type": "object" + }, + "result": { + "type": "object" + } + } + }, + "initial_state": { + "doc_id": "", + "confirmation_manuelle": "non", + "review": { + "status": "", + "revision": 0, + "number": "", + "pages": 0, + "title": "", + "renders": [] + }, + "result": { + "message": "Aucune action." + } + }, + "events": [ + { + "event_id": "load", + "trigger": "action.click", + "workflow": { + "workflow_id": "document-studio-review-read", + "input": { + "doc_id": "{{ state.doc_id }}" + } + }, + "result_to_state": "review" + }, + { + "event_id": "review", + "trigger": "form.submit", + "workflow": { + "workflow_id": "document-studio-review-read", + "input": { + "doc_id": "{{ state.doc_id }}" + } + }, + "result_to_state": "review" + }, + { + "event_id": "render", + "trigger": "action.click", + "workflow": { + "workflow_id": "document-studio-render", + "input": { + "doc_id": "{{ state.doc_id }}" + } + }, + "result_to_state": "result" + }, + { + "event_id": "approve", + "trigger": "form.submit", + "workflow": { + "workflow_id": "document-studio-finalize", + "input": { + "doc_id": "{{ state.doc_id }}", + "confirmation_manuelle": "{{ state.confirmation_manuelle }}" + } + }, + "result_to_state": "result" + }, + { + "event_id": "issue", + "trigger": "form.submit", + "workflow": { + "workflow_id": "document-studio-publish", + "input": { + "doc_id": "{{ state.doc_id }}", + "confirmation_manuelle": "{{ state.confirmation_manuelle }}" + } + }, + "result_to_state": "result" + } + ] +} diff --git a/document-studio/agents/main/workflows/document-studio-cancel.json b/document-studio/agents/main/workflows/document-studio-cancel.json new file mode 100644 index 0000000..29533b4 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-cancel.json @@ -0,0 +1,102 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-cancel", + "kind": "workflow", + "title": "Cancel a document", + "version": "1", + "description": "Marks a document cancelled with a reason. An issued number is never reused.", + "input_schema": { + "type": "object", + "required": [ + "doc_id", + "confirmation_manuelle", + "reason" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "confirmation_manuelle": { + "type": [ + "boolean", + "string" + ], + "description": "Manual confirmation: oui (or true) to proceed" + }, + "reason": { + "type": "string", + "description": "Reason of the cancellation" + } + } + }, + "forms": [ + { + "id": "cancel", + "title": "Annuler un document", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + }, + { + "name": "reason", + "title": "Motif", + "type": "text", + "required": true + }, + { + "name": "confirmation_manuelle", + "title": "Confirmation manuelle", + "type": "select", + "required": true, + "options": [ + { + "value": "non", + "label": "Non" + }, + { + "value": "oui", + "label": "Oui" + } + ], + "default": "non" + } + ], + "actions_on_submit": [ + "cancel" + ] + } + ], + "actions": [ + { + "id": "cancel", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst reason = text(input.reason, \"reason\", 500, true);\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"status_invalid\", \"document déjà annulé\");\nrec.status = \"cancelled\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"cancelled\", note: reason});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "template_key": "{{ result.template_key }}", + "title": "{{ result.title }}", + "status": "{{ result.status }}", + "number": "{{ result.number }}", + "revision": "{{ result.revision }}", + "renders": "{{ result.renders }}", + "last_render": "{{ result.last_render }}", + "issued": "{{ result.issued }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-draft.json b/document-studio/agents/main/workflows/document-studio-draft.json new file mode 100644 index 0000000..1a8a03e --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-draft.json @@ -0,0 +1,145 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-draft", + "kind": "workflow", + "title": "Draft a document", + "version": "1", + "description": "Fills the data of a template from a brief (model call, then strict validation; quote totals are computed here from the lines) and creates the record in Storage with status draft. Nothing is rendered yet.", + "input_schema": { + "type": "object", + "required": [ + "brief", + "template_key" + ], + "additionalProperties": false, + "properties": { + "brief": { + "type": "string", + "description": "Brief of the document" + }, + "template_key": { + "type": "string", + "description": "Template key", + "enum": [ + "quote", + "meeting-minutes" + ] + }, + "title": { + "type": "string", + "description": "Document title; derived from the data when absent" + }, + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "answers": { + "type": "object", + "description": "Answers to the questions of the plan" + }, + "locale": { + "type": "string", + "description": "Document language; fr only in V0", + "enum": [ + "fr" + ] + } + } + }, + "forms": [ + { + "id": "draft", + "title": "Rédiger un brouillon", + "fields": [ + { + "name": "brief", + "title": "Brief", + "type": "text", + "required": true + }, + { + "name": "template_key", + "title": "Gabarit", + "type": "select", + "required": true, + "options": [ + { + "value": "quote", + "label": "Devis" + }, + { + "value": "meeting-minutes", + "label": "Compte rendu de réunion" + } + ] + }, + { + "name": "title", + "title": "Titre (facultatif)", + "type": "string", + "required": false + }, + { + "name": "doc_id", + "title": "Identifiant (facultatif)", + "type": "string", + "required": false + } + ], + "actions_on_submit": [ + "prepare", + "draft-llm", + "create" + ] + } + ], + "actions": [ + { + "id": "prepare", + "type": "code_execution", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst brief = text(input.brief, \"brief\", 8000, true);\nconst key = input.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst locale = input.locale || \"fr\";\nif (locale !== \"fr\") fail(\"locale_unsupported\", \"seul fr est disponible en V0\");\nif (input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\") docIdOf(input.doc_id);\nif (input.answers !== undefined && input.answers !== null && !isObject(input.answers)) fail(\"answers_invalid\", \"objet attendu\");\nconst prompt = \"Brief du demandeur :\\n\" + brief + \"\\n\\n\" + (input.answers && Object.keys(input.answers).length ? \"Réponses complémentaires du demandeur :\\n\" + JSON.stringify(input.answers) + \"\\n\\n\" : \"\") + \"Date du jour : \" + today() + \".\\n\\nRemplis les données du document \\\"\" + key + \"\\\" selon ce schéma JSON :\\n\" + JSON.stringify(TEMPLATES[key].draft_schema) + \"\\n\\nRègles : réponds par l'objet de données seul, conforme au schéma. N'invente ni client, ni prix, ni date, ni participant : si une donnée requise manque, réponds uniquement {\\\"missing\\\": [\\\"description de ce qui manque\\\"]}. Ne calcule aucun total ni montant TTC. Dates au format AAAA-MM-JJ. Texte en français.\";\nreturn {prompt, template_key: key, locale};\n", + "output_key": "prep" + }, + { + "id": "draft-llm", + "type": "llm_call", + "llm_prompt": "{{ prep.prompt }}", + "llm_system_prompt": "Tu es un assistant de rédaction de documents professionnels. Tu réponds uniquement par un objet JSON, sans texte autour.", + "llm_temperature": 0.2, + "llm_max_tokens": 6000, + "llm_response_format": "json", + "llm_response_schema": { + "type": "object" + }, + "output_key": "draft" + }, + { + "id": "create", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst key = prep.template_key;\nlet data = parseJsonValue(input.draft);\nif (!isObject(data)) fail(\"llm_output_invalid\", \"objet attendu\");\nif (Array.isArray(data.missing) && data.missing.length) fail(\"data_missing\", data.missing.filter((x) => typeof x === \"string\").join(\" ; \"));\nlet title = typeof input.title === \"string\" && input.title.trim() ? input.title.trim().slice(0, 120) : \"\";\nconst given = input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\";\nconst id = given ? docIdOf(input.doc_id) : slugify(title || (key === \"quote\" ? \"devis \" + (isObject(data.customer) ? data.customer.name : \"\") : (isObject(data.meeting) ? data.meeting.title : key))) + \"-\" + shortSuffix();\ndata = normalizeData(key, data, id);\nif (!title) title = key === \"quote\" ? \"Devis \" + data.customer.name : data.meeting.title;\ntitle = title.slice(0, 120);\nconst at = nowIso();\nconst rec = {schema: \"document-studio.record/v1\", doc_id: id, template_key: key, template_version: TEMPLATES[key].manifest.version, title, locale: prep.locale, status: \"draft\", number: null, revision: 1, data, history: [{at, action: \"created\", note: \"brouillon créé depuis un brief\"}], renders: [], issued: null};\ntry { await writeJson(recordPath(id), rec, false); } catch (e) { fail(\"document_create_failed\", id + \" : \" + String(e && e.message)); }\nreturn {...summarize(rec), data, computed: templateData(key, data)};\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "template_key": "{{ result.template_key }}", + "title": "{{ result.title }}", + "status": "{{ result.status }}", + "number": "{{ result.number }}", + "revision": "{{ result.revision }}", + "renders": "{{ result.renders }}", + "last_render": "{{ result.last_render }}", + "issued": "{{ result.issued }}", + "data": "{{ result.data }}", + "computed": "{{ result.computed }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-export.json b/document-studio/agents/main/workflows/document-studio-export.json new file mode 100644 index 0000000..00d38d5 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-export.json @@ -0,0 +1,75 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-export", + "kind": "workflow", + "title": "Export a document", + "version": "1", + "description": "Copies the issued PDF (or the last render, flagged as a draft) to a Storage path outside /document-studio/. Sending by mail or SFTP is out of scope.", + "input_schema": { + "type": "object", + "required": [ + "doc_id", + "destination_path" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "destination_path": { + "type": "string", + "description": "Absolute Storage path of the copy, outside /document-studio/" + } + } + }, + "forms": [ + { + "id": "export", + "title": "Exporter un document", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + }, + { + "name": "destination_path", + "title": "Chemin de destination", + "type": "string", + "required": true + } + ], + "actions_on_submit": [ + "export" + ] + } + ], + "actions": [ + { + "id": "export", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst dest = input.destination_path;\nif (typeof dest !== \"string\" || !dest.startsWith(\"/\") || dest.length > 300 || dest.includes(\"..\") || dest.includes(\"//\") || /\\s$/.test(dest) || dest.endsWith(\"/\")) fail(\"destination_invalid\", \"chemin Storage absolu attendu\");\nif (dest === ROOT || dest.startsWith(ROOT + \"/\")) fail(\"destination_invalid\", \"la destination doit être hors de \" + ROOT);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst source = rec.issued ? rec.issued.file : (last ? last.file : null);\nif (!source) fail(\"no_render\", \"aucun rendu à exporter\");\nconst encoded = await readText(source.path, {encoding: \"base64\"});\nconst bytes = b64ToBytes(encoded.replace(/\\s+/g, \"\"));\nconst sha = await sha256Hex(bytes);\nif (sha !== source.sha256) fail(\"export_integrity_failed\", \"l'empreinte du fichier lu ne correspond pas au rendu\");\nawait callTool(\"write_file\", {path: dest, content: encoded.replace(/\\s+/g, \"\"), encoding: \"base64\", overwrite: false});\nreturn {doc_id: id, destination_path: dest, source_path: source.path, sha256: sha, bytes: bytes.length, draft: !rec.issued, warning: rec.issued ? \"\" : \"document non émis : copie du dernier rendu, marquée brouillon\"};\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "destination_path": "{{ result.destination_path }}", + "source_path": "{{ result.source_path }}", + "sha256": "{{ result.sha256 }}", + "bytes": "{{ result.bytes }}", + "draft": "{{ result.draft }}", + "warning": "{{ result.warning }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-finalize.json b/document-studio/agents/main/workflows/document-studio-finalize.json new file mode 100644 index 0000000..68247e8 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-finalize.json @@ -0,0 +1,91 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-finalize", + "kind": "workflow", + "title": "Approve a document", + "version": "1", + "description": "Moves a rendered draft to approved. Requires a render of the current revision and a manual confirmation.", + "input_schema": { + "type": "object", + "required": [ + "doc_id", + "confirmation_manuelle" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "confirmation_manuelle": { + "type": [ + "boolean", + "string" + ], + "description": "Manual confirmation: oui (or true) to proceed" + } + } + }, + "forms": [ + { + "id": "approve", + "title": "Approuver un document", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + }, + { + "name": "confirmation_manuelle", + "title": "Confirmation manuelle", + "type": "select", + "required": true, + "options": [ + { + "value": "non", + "label": "Non" + }, + { + "value": "oui", + "label": "Oui" + } + ], + "default": "non" + } + ], + "actions_on_submit": [ + "finalize" + ] + } + ], + "actions": [ + { + "id": "finalize", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"draft\") fail(\"status_invalid\", \"seul un brouillon s'approuve (statut actuel : \" + rec.status + \")\");\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nif (!last || last.revision !== rec.revision) fail(\"render_required\", \"rendez la révision courante avant de l'approuver\");\nrec.status = \"approved\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"approved\", note: \"rendu r\" + last.revision + \" approuvé\"});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "template_key": "{{ result.template_key }}", + "title": "{{ result.title }}", + "status": "{{ result.status }}", + "number": "{{ result.number }}", + "revision": "{{ result.revision }}", + "renders": "{{ result.renders }}", + "last_render": "{{ result.last_render }}", + "issued": "{{ result.issued }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-list.json b/document-studio/agents/main/workflows/document-studio-list.json new file mode 100644 index 0000000..1b4c129 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-list.json @@ -0,0 +1,53 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-list", + "kind": "workflow", + "title": "List documents", + "version": "1", + "description": "Lists the documents of the studio: identifier, title, status, number, revision and last fingerprint.", + "input_schema": { + "type": "object", + "required": [], + "additionalProperties": false, + "properties": { + "status": { + "type": "string", + "description": "Filter on a status", + "enum": [ + "draft", + "approved", + "issued", + "cancelled" + ] + }, + "template_key": { + "type": "string", + "description": "Template key", + "enum": [ + "quote", + "meeting-minutes" + ] + } + } + }, + "actions": [ + { + "id": "list", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nif (input.status !== undefined && input.status !== null && input.status !== \"\" && !STATUSES.includes(input.status)) fail(\"status_invalid\", String(input.status));\nconst paths = await listPaths(ROOT + \"/docs\");\nconst ids = [];\nfor (const p of paths) { const m = /document-studio\\/docs\\/([a-z0-9][a-z0-9-]{0,47})(?:\\/|$)/.exec(p); if (m && !ids.includes(m[1])) ids.push(m[1]); }\nif (ids.length > 200) fail(\"too_many_documents\", \"plus de 200 documents : filtrez ou archivez\");\nconst items = [];\nfor (const id of ids.sort()) {\n let rec;\n try { rec = await loadRecord(id); } catch (e) { continue; }\n if (input.status && rec.status !== input.status) continue;\n if (input.template_key && rec.template_key !== input.template_key) continue;\n const s = summarize(rec);\n items.push({doc_id: s.doc_id, title: s.title, template_key: s.template_key, status: s.status, number: s.number, revision: s.revision, sha256: s.issued ? s.issued.file.sha256 : (s.last_render ? s.last_render.sha256 : null)});\n}\nreturn {count: items.length, items};\n", + "output_key": "result" + } + ], + "output": { + "count": "{{ result.count }}", + "items": "{{ result.items }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-plan.json b/document-studio/agents/main/workflows/document-studio-plan.json new file mode 100644 index 0000000..2f63194 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-plan.json @@ -0,0 +1,105 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-plan", + "kind": "workflow", + "title": "Plan a document", + "version": "1", + "description": "Chooses the template for a brief, proposes a title and lists the missing data with questions. Writes nothing.", + "input_schema": { + "type": "object", + "required": [ + "brief" + ], + "additionalProperties": false, + "properties": { + "brief": { + "type": "string", + "description": "Brief of the document" + }, + "template_key": { + "type": "string", + "description": "Template key", + "enum": [ + "quote", + "meeting-minutes" + ] + }, + "locale": { + "type": "string", + "description": "Document language; fr only in V0", + "enum": [ + "fr" + ] + } + } + }, + "forms": [ + { + "id": "plan", + "title": "Planifier un document", + "fields": [ + { + "name": "brief", + "title": "Brief", + "type": "text", + "required": true + }, + { + "name": "template_key", + "title": "Gabarit (facultatif)", + "type": "select", + "required": false, + "options": [ + { + "value": "quote", + "label": "Devis" + }, + { + "value": "meeting-minutes", + "label": "Compte rendu de réunion" + } + ] + } + ], + "actions_on_submit": [ + "prepare", + "plan-llm", + "normalize" + ] + } + ], + "actions": [ + { + "id": "prepare", + "type": "code_execution", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst brief = text(input.brief, \"brief\", 8000, true);\nlet key = null;\nif (input.template_key !== undefined && input.template_key !== null && input.template_key !== \"\") { key = input.template_key; if (!TEMPLATES[key]) fail(\"template_unknown\", String(key)); }\nconst locale = input.locale || \"fr\";\nif (locale !== \"fr\") fail(\"locale_unsupported\", \"seul fr est disponible en V0\");\nconst catalogue = Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, summary: TEMPLATES[k].summary, data_schema: TEMPLATES[k].draft_schema}));\nconst prompt = \"Brief du demandeur :\\n\" + brief + \"\\n\\n\" + (key ? \"Gabarit imposé : \" + key + \"\\n\\n\" : \"\") + \"Gabarits disponibles (avec le schéma JSON des données attendues) :\\n\" + JSON.stringify(catalogue) + \"\\n\\nChoisis le gabarit adapté, propose un titre court et liste ce qui manque dans le brief pour remplir toutes les données requises du schéma. Ne remplis aucune donnée. Réponds par un objet JSON : {\\\"template_key\\\": string, \\\"title\\\": string, \\\"missing\\\": [string], \\\"questions\\\": [string]}. \\\"missing\\\" nomme les données absentes, \\\"questions\\\" les formule en questions au demandeur, en français.\";\nreturn {prompt, template_key: key, locale};\n", + "output_key": "prep" + }, + { + "id": "plan-llm", + "type": "llm_call", + "llm_prompt": "{{ prep.prompt }}", + "llm_system_prompt": "Tu es un assistant de rédaction de documents professionnels. Tu réponds uniquement par un objet JSON, sans texte autour.", + "llm_temperature": 0.2, + "llm_max_tokens": 2000, + "llm_response_format": "json", + "llm_response_schema": { + "type": "object" + }, + "output_key": "plan_draft" + }, + { + "id": "normalize", + "type": "code_execution", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst out = parseJsonValue(input.plan_draft);\nif (!isObject(out)) fail(\"llm_output_invalid\", \"objet attendu\");\nconst key = prep.template_key || out.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === \"string\" && x.trim()).map((x) => x.trim().slice(0, 300)).slice(0, 20) : []);\nconst title = typeof out.title === \"string\" && out.title.trim() ? out.title.trim().slice(0, 120) : TEMPLATES[key].title;\nreturn {template_key: key, title, locale: prep.locale, missing: list(out.missing), questions: list(out.questions)};\n", + "output_key": "result" + } + ], + "output": { + "template_key": "{{ result.template_key }}", + "title": "{{ result.title }}", + "missing": "{{ result.missing }}", + "questions": "{{ result.questions }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-profile-save.json b/document-studio/agents/main/workflows/document-studio-profile-save.json new file mode 100644 index 0000000..cd80194 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-profile-save.json @@ -0,0 +1,51 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-profile-save", + "kind": "workflow", + "title": "Save the company profile", + "version": "1", + "description": "Validates the profile (company identity and brand tokens of the template contract) and stores it as /document-studio/profile.json. Requires a manual confirmation.", + "input_schema": { + "type": "object", + "required": [ + "profile", + "confirmation_manuelle" + ], + "additionalProperties": false, + "properties": { + "profile": { + "type": "object", + "description": "Body {schema_version: 1, company, brand}" + }, + "confirmation_manuelle": { + "type": [ + "boolean", + "string" + ], + "description": "Manual confirmation: oui (or true) to proceed" + } + } + }, + "actions": [ + { + "id": "save", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst body = normalizeProfile(input.profile);\nawait callTool(\"write_file\", {path: ROOT + \"/profile.json\", content: JSON.stringify(body, null, 2) + \"\\n\", overwrite: true});\nreturn {path: ROOT + \"/profile.json\", legal_name: body.company.legal_name, colors: body.brand.colors, message: \"Charte enregistrée dans Storage.\"};\n", + "output_key": "result" + } + ], + "output": { + "path": "{{ result.path }}", + "legal_name": "{{ result.legal_name }}", + "colors": "{{ result.colors }}", + "message": "{{ result.message }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-publish.json b/document-studio/agents/main/workflows/document-studio-publish.json new file mode 100644 index 0000000..0783a90 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-publish.json @@ -0,0 +1,92 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-publish", + "kind": "workflow", + "title": "Issue a document", + "version": "1", + "description": "Reserves the next number of the template for the year, renders the final PDF (mode final) and stores it as the issued file. Requires an approved document and a manual confirmation. The reservation is not atomic.", + "input_schema": { + "type": "object", + "required": [ + "doc_id", + "confirmation_manuelle" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "confirmation_manuelle": { + "type": [ + "boolean", + "string" + ], + "description": "Manual confirmation: oui (or true) to proceed" + } + } + }, + "forms": [ + { + "id": "issue", + "title": "Émettre un document", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + }, + { + "name": "confirmation_manuelle", + "title": "Confirmation manuelle", + "type": "select", + "required": true, + "options": [ + { + "value": "non", + "label": "Non" + }, + { + "value": "oui", + "label": "Oui" + } + ], + "default": "non" + } + ], + "actions_on_submit": [ + "publish" + ] + } + ], + "actions": [ + { + "id": "publish", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files", + "artifact--artifact_render_v1" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"reference\\\\\\\": \\\\\\\"AFF-2026-017\\\\\\\",\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cabinet Fictif & Associés\\\\\\\",\\\\n \\\\\\\"address_lines\\\\\\\": [\\\\\\\"12 avenue de l'Échantillon\\\\\\\", \\\\\\\"00000 Exemple-sur-Seine\\\\\\\"],\\\\n \\\\\\\"contact\\\\\\\": \\\\\\\"Mme Dupont (exemple), contact@fictif.invalid\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Atelier de cadrage (2 demi-journées) #1\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"2 forfaits\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"600,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"1 200,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Développement du prototype_v1 [lot A]\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"5 jours\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"700,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"3 500,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Documentation et formation\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"1 jour\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"5 350,00 €\\\\\\\",\\\\n \\\\\\\"vat\\\\\\\": [\\u007b \\\\\\\"rate\\\\\\\": \\\\\\\"20 %\\\\\\\", \\\\\\\"amount\\\\\\\": \\\\\\\"1 070,00 €\\\\\\\" \\u007d],\\\\n \\\\\\\"total_ttc\\\\\\\": \\\\\\\"6 420,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\\\\\\"2026-12-06\\\\\\\",\\\\n \\\\\\\"terms\\\\\\\": [\\\\n \\\\\\\"Acompte de 30 % à la commande.\\\\\\\",\\\\n \\\\\\\"Livraison sous 6 semaines après acompte.\\\\\\\",\\\\n \\\\\\\"Toute prestation supplémentaire fait l'objet d'un avenant.\\\\\\\"\\\\n ],\\\\n \\\\\\\"payment_terms\\\\\\\": \\\\\\\"30 jours à réception de facture, par virement.\\\\\\\"\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"reference\\\\\\\", \\\\\\\"customer\\\\\\\", \\\\\\\"lines\\\\\\\", \\\\\\\"totals\\\\\\\", \\\\\\\"valid_until\\\\\\\", \\\\\\\"terms\\\\\\\", \\\\\\\"payment_terms\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"reference\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"address_lines\\\\\\\", \\\\\\\"contact\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"address_lines\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"contact\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"quantity\\\\\\\", \\\\\\\"unit_price_ht\\\\\\\", \\\\\\\"vat_rate\\\\\\\", \\\\\\\"total_ht\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"quantity\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"description\\\\\\\": \\\\\\\"Quantite et unite, par exemple `3 jours`.\\\\\\\" \\u007d,\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat_rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"pattern\\\\\\\": \\\\\\\"^[0-9]+([,.][0-9]+)? ?%$\\\\\\\" \\u007d,\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"total_ht\\\\\\\", \\\\\\\"vat\\\\\\\", \\\\\\\"total_ttc\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"rate\\\\\\\", \\\\\\\"amount\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"amount\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"total_ttc\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"payment_terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"money\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montant formate en amont, par exemple `1 250,00 €`.\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/.\\\\n// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .company.siret \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#set par(justify: false)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_title \\u007d\\u007d \\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_reference \\u007d\\u007d \\u007b\\u007b .data.reference \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n#grid(\\\\n columns: (1fr, 1fr),\\\\n gutter: 10mm,\\\\n [\\\\n *\\u007b\\u007b .company.legal_name \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .company.address.line1 \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.address.postal_code \\u007d\\u007d \\u007b\\u007b .company.address.city \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.email \\u007d\\u007d\\\\n ],\\\\n [\\\\n *\\u007b\\u007b .i18n.strings.quote_customer \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .data.customer.name \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- range .data.customer.address_lines \\u007d\\u007d\\\\n \\u007b\\u007b . \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n \\u007b\\u007b .data.customer.contact \\u007d\\u007d\\\\n ],\\\\n)\\\\n\\\\n#v(6mm)\\\\n\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.quote_col_description \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_quantity \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_unit_price \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_vat \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_total \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.lines \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .quantity \\u007d\\u007d], [\\u007b\\u007b .unit_price_ht \\u007d\\u007d], [\\u007b\\u007b .vat_rate \\u007d\\u007d], [\\u007b\\u007b .total_ht \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n)\\\\n\\\\n#v(4mm)\\\\n#align(right, block(width: 60%, table(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n stroke: none,\\\\n inset: (x: 2mm, y: 1.5mm),\\\\n [\\u007b\\u007b .i18n.strings.quote_total_ht \\u007d\\u007d], [\\u007b\\u007b .data.totals.total_ht \\u007d\\u007d],\\\\n\\u007b\\u007b- range .data.totals.vat \\u007d\\u007d\\\\n [\\u007b\\u007b $.i18n.strings.quote_total_vat \\u007d\\u007d \\u007b\\u007b .rate \\u007d\\u007d], [\\u007b\\u007b .amount \\u007d\\u007d],\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n [*\\u007b\\u007b .i18n.strings.quote_total_ttc \\u007d\\u007d*], [*\\u007b\\u007b .data.totals.total_ttc \\u007d\\u007d*],\\\\n)))\\\\n\\\\n#v(4mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_valid_until \\u007d\\u007d* \\u007b\\u007b .data.valid_until \\u007d\\u007d\\\\n\\\\n#v(2mm)\\\\n*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement.\\\\n\\\\n#v(2mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_terms \\u007d\\u007d*\\\\n\\u007b\\u007b range .data.terms \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n*\\u007b\\u007b .i18n.strings.quote_payment \\u007d\\u007d* \\u007b\\u007b .data.payment_terms \\u007d\\u007d\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"quote\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\", \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\" \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\\\\"pdf\\\\\\\"],\\\\n \\\\\\\"locales\\\\\\\": [\\\\\\\"fr\\\\\\\"],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\u007b \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\", \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\" \\u007d],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b \\\\\\\"max_source_bytes\\\\\\\": 20000, \\\\\\\"max_pages\\\\\\\": 4 \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\nconst I18N = JSON.parse(\"\\u007b\\\"locale\\\": \\\"fr\\\", \\\"strings\\\": \\u007b\\\"common_legal_notice\\\": \\\"Mentions légales\\\", \\\"common_page\\\": \\\"Page\\\", \\\"common_unsubscribe\\\": \\\"Se désinscrire\\\", \\\"minutes_absent\\\": \\\"excusé\\\", \\\"minutes_actions\\\": \\\"Actions\\\", \\\"minutes_agenda\\\": \\\"Ordre du jour\\\", \\\"minutes_col_action\\\": \\\"Action\\\", \\\"minutes_col_due\\\": \\\"Échéance\\\", \\\"minutes_col_owner\\\": \\\"Responsable\\\", \\\"minutes_date\\\": \\\"Date\\\", \\\"minutes_decisions\\\": \\\"Décisions\\\", \\\"minutes_meeting\\\": \\\"Réunion\\\", \\\"minutes_participants\\\": \\\"Participants\\\", \\\"minutes_place\\\": \\\"Lieu\\\", \\\"minutes_present\\\": \\\"présent\\\", \\\"minutes_title\\\": \\\"Compte rendu de réunion\\\", \\\"quote_col_description\\\": \\\"Désignation\\\", \\\"quote_col_quantity\\\": \\\"Quantité\\\", \\\"quote_col_total\\\": \\\"Total HT\\\", \\\"quote_col_unit_price\\\": \\\"PU HT\\\", \\\"quote_col_vat\\\": \\\"TVA\\\", \\\"quote_customer\\\": \\\"Client\\\", \\\"quote_payment\\\": \\\"Règlement\\\", \\\"quote_reference\\\": \\\"Référence\\\", \\\"quote_terms\\\": \\\"Conditions\\\", \\\"quote_title\\\": \\\"Devis\\\", \\\"quote_total_ht\\\": \\\"Total HT\\\", \\\"quote_total_ttc\\\": \\\"Total TTC\\\", \\\"quote_total_vat\\\": \\\"Total TVA\\\", \\\"quote_valid_until\\\": \\\"Valable jusqu'au\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nfunction safeName(name, fallback) {\n const base = typeof name === \"string\" ? name.split(\"/\").pop() : \"\";\n return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(\".\") ? base : fallback;\n}\n\nasync function renderDocument(rec, data, profile, mode, number, status, revision) {\n const tpl = TEMPLATES[rec.template_key];\n if (!tpl) fail(\"template_unknown\", rec.template_key);\n const tdata = templateData(rec.template_key, data);\n validateSchema(tpl.input_schema, tdata, \"gabarit \" + rec.template_key);\n const doc = {number: number || \"BROUILLON\", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale};\n const raw = await callTool(\"artifact--artifact_render_v1\", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: \"pdf\", mode});\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"render_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file)) fail(\"render_failed\", \"réponse inattendue du moteur de rendu\");\n return res;\n}\n\n// Stores one rendered file: by buffer reference when the engine gives one, else from base64.\nasync function storeFile(path, f) {\n const args = {path, overwrite: true};\n let sha = typeof f.sha256 === \"string\" ? f.sha256 : \"\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") args.buffer_ref = f.ref;\n else if (typeof f.content_base64 === \"string\") {\n const computed = await sha256Hex(b64ToBytes(f.content_base64));\n if (sha && sha !== computed) fail(\"render_integrity_failed\", path);\n sha = computed;\n args.content = f.content_base64;\n args.encoding = \"base64\";\n } else fail(\"render_output_missing\", path);\n await callTool(\"write_file\", args);\n return {path, sha256: sha, bytes: typeof f.bytes === \"number\" ? f.bytes : null, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n for (const p of Array.isArray(res.previews) ? res.previews : []) {\n const page = Number.isInteger(p.page) ? p.page : previews.length + 1;\n const stored = await storeFile(dir + \"/\" + safeName(p.filename, \"page-\" + page + \".png\"), p);\n previews.push({page, path: stored.path, sha256: stored.sha256});\n }\n return previews;\n}\n\n// Number reservation: lists the year folder, takes max + 1, writes the token without overwrite, reads it back and\n// checks the owner. Not atomic: the check narrows the window, it does not close it.\nasync function reserveNumber(rec) {\n const year = new Date().getUTCFullYear();\n const dir = ROOT + \"/numbers/\" + rec.template_key + \"/\" + year;\n let last = \"\";\n for (let attempt = 0; attempt < 5; attempt++) {\n const paths = await listPaths(dir);\n let max = 0;\n for (const p of paths) { const m = /(?:^|\\/)(\\d{4,})\\.json$/.exec(p); if (m) max = Math.max(max, Number(m[1])); }\n const seq = String(max + 1).padStart(4, \"0\");\n const path = dir + \"/\" + seq + \".json\";\n try { await writeJson(path, {doc_id: rec.doc_id, at: nowIso()}, false); } catch (e) { last = String(e && e.message); continue; }\n let token = null;\n try { token = await readJson(path); } catch (e) { last = String(e && e.message); continue; }\n if (isObject(token) && token.doc_id === rec.doc_id) return TEMPLATES[rec.template_key].prefix + \"-\" + year + \"-\" + seq;\n last = \"numéro \" + seq + \" pris par un autre document\";\n }\n fail(\"number_conflict\", \"5 essais sans numéro libre (\" + last + \")\");\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"approved\") fail(\"status_invalid\", \"seul un document approuvé s'émet (statut actuel : \" + rec.status + \")\");\nconst profile = await loadProfile();\nif (!rec.number) {\n rec.number = await reserveNumber(rec);\n rec.revision += 1;\n rec.history.push({at: nowIso(), action: \"number_reserved\", note: rec.number});\n await saveRecord(rec);\n}\nconst data = normalizeData(rec.template_key, rec.data, id);\nconst revision = rec.revision + 1;\nconst res = await renderDocument(rec, data, profile, \"final\", rec.number, \"issued\", revision);\nconst dir = ROOT + \"/docs/\" + id;\nconst file = await storeFile(dir + \"/issued/\" + rec.number + \".pdf\", res.file);\nconst previews = await storePreviews(dir + \"/r\" + revision, res);\nconst at = nowIso();\nrec.status = \"issued\";\nrec.revision = revision;\nrec.renders.push({revision, mode: \"final\", file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nrec.issued = {number: rec.number, file: {path: file.path, sha256: file.sha256}, at};\nrec.history.push({at, action: \"issued\", note: rec.number});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "template_key": "{{ result.template_key }}", + "title": "{{ result.title }}", + "status": "{{ result.status }}", + "number": "{{ result.number }}", + "revision": "{{ result.revision }}", + "renders": "{{ result.renders }}", + "last_render": "{{ result.last_render }}", + "issued": "{{ result.issued }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-render.json b/document-studio/agents/main/workflows/document-studio-render.json new file mode 100644 index 0000000..9699a4b --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-render.json @@ -0,0 +1,71 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-render", + "kind": "workflow", + "title": "Render a document preview", + "version": "1", + "description": "Renders the current data with the company profile through the artifact tool (mode preview), stores the PDF and its page previews in Storage and appends a revision. An issued or cancelled document is locked.", + "input_schema": { + "type": "object", + "required": [ + "doc_id" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "data_patch": { + "type": "object", + "description": "Shallow merge into the draft data, then revalidated" + } + } + }, + "forms": [ + { + "id": "render", + "title": "Nouveau rendu", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + } + ], + "actions_on_submit": [ + "render" + ] + } + ], + "actions": [ + { + "id": "render", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files", + "artifact--artifact_render_v1" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"reference\\\\\\\": \\\\\\\"AFF-2026-017\\\\\\\",\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cabinet Fictif & Associés\\\\\\\",\\\\n \\\\\\\"address_lines\\\\\\\": [\\\\\\\"12 avenue de l'Échantillon\\\\\\\", \\\\\\\"00000 Exemple-sur-Seine\\\\\\\"],\\\\n \\\\\\\"contact\\\\\\\": \\\\\\\"Mme Dupont (exemple), contact@fictif.invalid\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Atelier de cadrage (2 demi-journées) #1\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"2 forfaits\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"600,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"1 200,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Développement du prototype_v1 [lot A]\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"5 jours\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"700,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"3 500,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Documentation et formation\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"1 jour\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"5 350,00 €\\\\\\\",\\\\n \\\\\\\"vat\\\\\\\": [\\u007b \\\\\\\"rate\\\\\\\": \\\\\\\"20 %\\\\\\\", \\\\\\\"amount\\\\\\\": \\\\\\\"1 070,00 €\\\\\\\" \\u007d],\\\\n \\\\\\\"total_ttc\\\\\\\": \\\\\\\"6 420,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\\\\\\"2026-12-06\\\\\\\",\\\\n \\\\\\\"terms\\\\\\\": [\\\\n \\\\\\\"Acompte de 30 % à la commande.\\\\\\\",\\\\n \\\\\\\"Livraison sous 6 semaines après acompte.\\\\\\\",\\\\n \\\\\\\"Toute prestation supplémentaire fait l'objet d'un avenant.\\\\\\\"\\\\n ],\\\\n \\\\\\\"payment_terms\\\\\\\": \\\\\\\"30 jours à réception de facture, par virement.\\\\\\\"\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"reference\\\\\\\", \\\\\\\"customer\\\\\\\", \\\\\\\"lines\\\\\\\", \\\\\\\"totals\\\\\\\", \\\\\\\"valid_until\\\\\\\", \\\\\\\"terms\\\\\\\", \\\\\\\"payment_terms\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"reference\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"address_lines\\\\\\\", \\\\\\\"contact\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"address_lines\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"contact\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"quantity\\\\\\\", \\\\\\\"unit_price_ht\\\\\\\", \\\\\\\"vat_rate\\\\\\\", \\\\\\\"total_ht\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"quantity\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"description\\\\\\\": \\\\\\\"Quantite et unite, par exemple `3 jours`.\\\\\\\" \\u007d,\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat_rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"pattern\\\\\\\": \\\\\\\"^[0-9]+([,.][0-9]+)? ?%$\\\\\\\" \\u007d,\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"total_ht\\\\\\\", \\\\\\\"vat\\\\\\\", \\\\\\\"total_ttc\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"rate\\\\\\\", \\\\\\\"amount\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"amount\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"total_ttc\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"payment_terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"money\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montant formate en amont, par exemple `1 250,00 €`.\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/.\\\\n// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .company.siret \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#set par(justify: false)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_title \\u007d\\u007d \\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_reference \\u007d\\u007d \\u007b\\u007b .data.reference \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n#grid(\\\\n columns: (1fr, 1fr),\\\\n gutter: 10mm,\\\\n [\\\\n *\\u007b\\u007b .company.legal_name \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .company.address.line1 \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.address.postal_code \\u007d\\u007d \\u007b\\u007b .company.address.city \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.email \\u007d\\u007d\\\\n ],\\\\n [\\\\n *\\u007b\\u007b .i18n.strings.quote_customer \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .data.customer.name \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- range .data.customer.address_lines \\u007d\\u007d\\\\n \\u007b\\u007b . \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n \\u007b\\u007b .data.customer.contact \\u007d\\u007d\\\\n ],\\\\n)\\\\n\\\\n#v(6mm)\\\\n\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.quote_col_description \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_quantity \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_unit_price \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_vat \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_total \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.lines \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .quantity \\u007d\\u007d], [\\u007b\\u007b .unit_price_ht \\u007d\\u007d], [\\u007b\\u007b .vat_rate \\u007d\\u007d], [\\u007b\\u007b .total_ht \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n)\\\\n\\\\n#v(4mm)\\\\n#align(right, block(width: 60%, table(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n stroke: none,\\\\n inset: (x: 2mm, y: 1.5mm),\\\\n [\\u007b\\u007b .i18n.strings.quote_total_ht \\u007d\\u007d], [\\u007b\\u007b .data.totals.total_ht \\u007d\\u007d],\\\\n\\u007b\\u007b- range .data.totals.vat \\u007d\\u007d\\\\n [\\u007b\\u007b $.i18n.strings.quote_total_vat \\u007d\\u007d \\u007b\\u007b .rate \\u007d\\u007d], [\\u007b\\u007b .amount \\u007d\\u007d],\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n [*\\u007b\\u007b .i18n.strings.quote_total_ttc \\u007d\\u007d*], [*\\u007b\\u007b .data.totals.total_ttc \\u007d\\u007d*],\\\\n)))\\\\n\\\\n#v(4mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_valid_until \\u007d\\u007d* \\u007b\\u007b .data.valid_until \\u007d\\u007d\\\\n\\\\n#v(2mm)\\\\n*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement.\\\\n\\\\n#v(2mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_terms \\u007d\\u007d*\\\\n\\u007b\\u007b range .data.terms \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n*\\u007b\\u007b .i18n.strings.quote_payment \\u007d\\u007d* \\u007b\\u007b .data.payment_terms \\u007d\\u007d\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"quote\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\", \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\" \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\\\\"pdf\\\\\\\"],\\\\n \\\\\\\"locales\\\\\\\": [\\\\\\\"fr\\\\\\\"],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\u007b \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\", \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\" \\u007d],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b \\\\\\\"max_source_bytes\\\\\\\": 20000, \\\\\\\"max_pages\\\\\\\": 4 \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\nconst I18N = JSON.parse(\"\\u007b\\\"locale\\\": \\\"fr\\\", \\\"strings\\\": \\u007b\\\"common_legal_notice\\\": \\\"Mentions légales\\\", \\\"common_page\\\": \\\"Page\\\", \\\"common_unsubscribe\\\": \\\"Se désinscrire\\\", \\\"minutes_absent\\\": \\\"excusé\\\", \\\"minutes_actions\\\": \\\"Actions\\\", \\\"minutes_agenda\\\": \\\"Ordre du jour\\\", \\\"minutes_col_action\\\": \\\"Action\\\", \\\"minutes_col_due\\\": \\\"Échéance\\\", \\\"minutes_col_owner\\\": \\\"Responsable\\\", \\\"minutes_date\\\": \\\"Date\\\", \\\"minutes_decisions\\\": \\\"Décisions\\\", \\\"minutes_meeting\\\": \\\"Réunion\\\", \\\"minutes_participants\\\": \\\"Participants\\\", \\\"minutes_place\\\": \\\"Lieu\\\", \\\"minutes_present\\\": \\\"présent\\\", \\\"minutes_title\\\": \\\"Compte rendu de réunion\\\", \\\"quote_col_description\\\": \\\"Désignation\\\", \\\"quote_col_quantity\\\": \\\"Quantité\\\", \\\"quote_col_total\\\": \\\"Total HT\\\", \\\"quote_col_unit_price\\\": \\\"PU HT\\\", \\\"quote_col_vat\\\": \\\"TVA\\\", \\\"quote_customer\\\": \\\"Client\\\", \\\"quote_payment\\\": \\\"Règlement\\\", \\\"quote_reference\\\": \\\"Référence\\\", \\\"quote_terms\\\": \\\"Conditions\\\", \\\"quote_title\\\": \\\"Devis\\\", \\\"quote_total_ht\\\": \\\"Total HT\\\", \\\"quote_total_ttc\\\": \\\"Total TTC\\\", \\\"quote_total_vat\\\": \\\"Total TVA\\\", \\\"quote_valid_until\\\": \\\"Valable jusqu'au\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nfunction safeName(name, fallback) {\n const base = typeof name === \"string\" ? name.split(\"/\").pop() : \"\";\n return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(\".\") ? base : fallback;\n}\n\nasync function renderDocument(rec, data, profile, mode, number, status, revision) {\n const tpl = TEMPLATES[rec.template_key];\n if (!tpl) fail(\"template_unknown\", rec.template_key);\n const tdata = templateData(rec.template_key, data);\n validateSchema(tpl.input_schema, tdata, \"gabarit \" + rec.template_key);\n const doc = {number: number || \"BROUILLON\", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale};\n const raw = await callTool(\"artifact--artifact_render_v1\", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: \"pdf\", mode});\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"render_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file)) fail(\"render_failed\", \"réponse inattendue du moteur de rendu\");\n return res;\n}\n\n// Stores one rendered file: by buffer reference when the engine gives one, else from base64.\nasync function storeFile(path, f) {\n const args = {path, overwrite: true};\n let sha = typeof f.sha256 === \"string\" ? f.sha256 : \"\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") args.buffer_ref = f.ref;\n else if (typeof f.content_base64 === \"string\") {\n const computed = await sha256Hex(b64ToBytes(f.content_base64));\n if (sha && sha !== computed) fail(\"render_integrity_failed\", path);\n sha = computed;\n args.content = f.content_base64;\n args.encoding = \"base64\";\n } else fail(\"render_output_missing\", path);\n await callTool(\"write_file\", args);\n return {path, sha256: sha, bytes: typeof f.bytes === \"number\" ? f.bytes : null, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n for (const p of Array.isArray(res.previews) ? res.previews : []) {\n const page = Number.isInteger(p.page) ? p.page : previews.length + 1;\n const stored = await storeFile(dir + \"/\" + safeName(p.filename, \"page-\" + page + \".png\"), p);\n previews.push({page, path: stored.path, sha256: stored.sha256});\n }\n return previews;\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status === \"issued\" || rec.status === \"cancelled\") fail(\"document_locked\", \"un document \" + (rec.status === \"issued\" ? \"émis\" : \"annulé\") + \" ne se rend plus\");\nlet data = rec.data;\nif (input.data_patch !== undefined && input.data_patch !== null) {\n if (!isObject(input.data_patch)) fail(\"data_patch_invalid\", \"objet attendu\");\n data = {...rec.data, ...input.data_patch};\n}\ndata = normalizeData(rec.template_key, data, id);\nconst profile = await loadProfile();\nconst revision = rec.revision + 1;\nconst res = await renderDocument(rec, data, profile, \"preview\", null, \"draft\", revision);\nconst dir = ROOT + \"/docs/\" + id + \"/r\" + revision;\nconst file = await storeFile(dir + \"/\" + safeName(res.file.filename, \"document.pdf\"), res.file);\nconst previews = await storePreviews(dir, res);\nconst at = nowIso();\nif (rec.status === \"approved\") rec.history.push({at, action: \"reopened\", note: \"nouveau rendu : l'approbation est à renouveler\"});\nrec.history.push({at, action: \"rendered\", note: \"r\" + revision + \", \" + (Number.isInteger(res.pages) ? res.pages : previews.length) + \" page(s)\"});\nrec.status = \"draft\";\nrec.data = data;\nrec.revision = revision;\nrec.renders.push({revision, mode: \"preview\", file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "template_key": "{{ result.template_key }}", + "title": "{{ result.title }}", + "status": "{{ result.status }}", + "number": "{{ result.number }}", + "revision": "{{ result.revision }}", + "renders": "{{ result.renders }}", + "last_render": "{{ result.last_render }}", + "issued": "{{ result.issued }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-review-read.json b/document-studio/agents/main/workflows/document-studio-review-read.json new file mode 100644 index 0000000..9b81cb8 --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-review-read.json @@ -0,0 +1,69 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-review-read", + "kind": "workflow", + "title": "Read a document for review", + "version": "1", + "description": "Returns the record of a document with the previews of its last render, for the review MiniApp.", + "input_schema": { + "type": "object", + "required": [ + "doc_id" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + } + } + }, + "forms": [ + { + "id": "review", + "title": "Relire un document", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + } + ], + "actions_on_submit": [ + "read" + ] + } + ], + "actions": [ + { + "id": "read", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "write_file", + "list_files" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst s = summarize(rec);\nreturn {doc_id: id, title: rec.title, template_key: rec.template_key, status: rec.status, number: rec.number === null ? \"\" : rec.number, revision: rec.revision, pages: last ? last.previews.length : 0, previews: last ? last.previews : [], renders: rec.renders.map((r) => ({revision: r.revision, mode: r.mode, sha256: r.file.sha256, path: r.file.path})), history: rec.history, issued: rec.issued, record: rec};\n", + "output_key": "result" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "title": "{{ result.title }}", + "template_key": "{{ result.template_key }}", + "status": "{{ result.status }}", + "number": "{{ result.number }}", + "revision": "{{ result.revision }}", + "pages": "{{ result.pages }}", + "previews": "{{ result.previews }}", + "renders": "{{ result.renders }}", + "history": "{{ result.history }}", + "issued": "{{ result.issued }}", + "record": "{{ result.record }}" + } +} diff --git a/document-studio/agents/main/workflows/document-studio-template-read.json b/document-studio/agents/main/workflows/document-studio-template-read.json new file mode 100644 index 0000000..44fe8cd --- /dev/null +++ b/document-studio/agents/main/workflows/document-studio-template-read.json @@ -0,0 +1,36 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-studio-template-read", + "kind": "workflow", + "title": "Read the templates", + "version": "1", + "description": "Lists the available templates, or returns the manifest and the data schemas of one of them.", + "input_schema": { + "type": "object", + "required": [], + "additionalProperties": false, + "properties": { + "template_key": { + "type": "string", + "description": "Template key", + "enum": [ + "quote", + "meeting-minutes" + ] + } + } + }, + "actions": [ + { + "id": "read", + "type": "code_execution", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nif (input.template_key === undefined || input.template_key === null || input.template_key === \"\") {\n return {templates: Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, version: TEMPLATES[k].manifest.version, prefix: TEMPLATES[k].prefix, summary: TEMPLATES[k].summary})), template: null};\n}\nconst tpl = TEMPLATES[input.template_key];\nif (!tpl) fail(\"template_unknown\", String(input.template_key));\nreturn {templates: [], template: {template_key: input.template_key, title: tpl.title, version: tpl.manifest.version, prefix: tpl.prefix, summary: tpl.summary, manifest: tpl.manifest, input_schema: tpl.input_schema, draft_schema: tpl.draft_schema}};\n", + "output_key": "result" + } + ], + "output": { + "templates": "{{ result.templates }}", + "template": "{{ result.template }}" + } +} diff --git a/document-studio/examples/profile.example.json b/document-studio/examples/profile.example.json new file mode 100644 index 0000000..f3289c7 --- /dev/null +++ b/document-studio/examples/profile.example.json @@ -0,0 +1,40 @@ +{ + "schema_version": 1, + "company": { + "legal_name": "Atelier Exemple SAS", + "trade_name": "Atelier Exemple", + "legal_form": "SAS", + "share_capital": "10 000 EUR", + "siren": "000 000 000", + "siret": "000 000 000 00000", + "vat_number": "FR00000000000", + "rcs": "RCS Exemple-sur-Seine 000 000 000", + "address": { + "line1": "1 rue de l'Exemple", + "postal_code": "00000", + "city": "Exemple-sur-Seine", + "country": "France" + }, + "email": "contact@atelier-exemple.invalid", + "phone": "+33 0 00 00 00 00", + "website": "https://atelier-exemple.invalid", + "legal_mentions": "Atelier Exemple SAS, capital de 10 000 EUR, RCS Exemple-sur-Seine 000 000 000. Société fictive : aucune donnée réelle." + }, + "brand": { + "colors": { + "primary": "#1F3A5F", + "secondary": "#4F6D8F", + "accent": "#E07A1F", + "text": "#1B1B1F", + "muted": "#6B7280", + "background": "#F5F7FA" + }, + "fonts": { + "heading": { "family": "Libertinus Serif" }, + "body": { "family": "Libertinus Serif" }, + "mono": { "family": "DejaVu Sans Mono" } + }, + "logo": { "ref": "storage:///logos/atelier-exemple.svg", "alt": "Logo Atelier Exemple" }, + "page": { "size": "A4", "margins_mm": { "top": 22, "right": 20, "bottom": 22, "left": 20 } } + } +} diff --git a/document-studio/examples/templates/meeting-minutes/examples/default.json b/document-studio/examples/templates/meeting-minutes/examples/default.json new file mode 100644 index 0000000..6dc64cc --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/examples/default.json @@ -0,0 +1,26 @@ +{ + "meeting": { + "title": "Point d'avancement du projet Exemple", + "date": "2026-11-05", + "time": "14:00", + "place": "Salle Horizon / visio" + }, + "participants": [ + { "name": "Camille Martin", "role": "Cheffe de projet", "present": true }, + { "name": "Alex Durand", "role": "Développeur", "present": true }, + { "name": "Sam Leroy", "role": "Client référent", "present": false } + ], + "agenda": [ + "Revue de l'avancement", + "Budget restant et risques", + "Planning de la prochaine itération" + ], + "decisions": [ + "Le lot A est validé en l'état.", + "La recette est repoussée au 2026-11-20 (marge de sécurité)." + ], + "actions": [ + { "description": "Envoyer le planning révisé", "owner": "Camille Martin", "due_date": "2026-11-08" }, + { "description": "Corriger les 3 anomalies de recette", "owner": "Alex Durand", "due_date": "2026-11-15" } + ] +} diff --git a/document-studio/examples/templates/meeting-minutes/examples/minimal.json b/document-studio/examples/templates/meeting-minutes/examples/minimal.json new file mode 100644 index 0000000..0abeecd --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/examples/minimal.json @@ -0,0 +1,44 @@ +{ + "meeting": { + "title": "Point d'avancement du projet Exemple", + "date": "2026-11-05" + }, + "participants": [ + { + "name": "Camille Martin", + "role": "Cheffe de projet", + "present": true + }, + { + "name": "Alex Durand", + "role": "Développeur", + "present": true + }, + { + "name": "Sam Leroy", + "role": "Client référent", + "present": false + } + ], + "agenda": [ + "Revue de l'avancement", + "Budget restant et risques", + "Planning de la prochaine itération" + ], + "decisions": [ + "Le lot A est validé en l'état.", + "La recette est repoussée au 2026-11-20 (marge de sécurité)." + ], + "actions": [ + { + "description": "Envoyer le planning révisé", + "owner": "Camille Martin", + "due_date": "2026-11-08" + }, + { + "description": "Corriger les 3 anomalies de recette", + "owner": "Alex Durand", + "due_date": "2026-11-15" + } + ] +} diff --git a/document-studio/examples/templates/meeting-minutes/fragments/footer.typ b/document-studio/examples/templates/meeting-minutes/fragments/footer.typ new file mode 100644 index 0000000..6b9ba82 --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/fragments/footer.typ @@ -0,0 +1,14 @@ +// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`. +#import "/brand.typ": brand + +#let doc-footer(company-line) = { + set text(size: 8pt, fill: brand.colors.muted) + line(length: 100%, stroke: 0.4pt + brand.colors.muted) + v(1mm) + grid( + columns: (1fr, auto), + align: (left, right), + company-line, + context [#counter(page).display() / #counter(page).final().first()], + ) +} diff --git a/document-studio/examples/templates/meeting-minutes/fragments/header.typ b/document-studio/examples/templates/meeting-minutes/fragments/header.typ new file mode 100644 index 0000000..0bfd11a --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/fragments/header.typ @@ -0,0 +1,26 @@ +// Fragment partage : en-tete de document. Fonction pure, aucune balise Go. +// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees. +#import "/brand.typ": brand + +#let doc-header(company-name, doc-title, doc-number, doc-date) = { + grid( + columns: (1fr, auto), + gutter: 8mm, + align: (left + horizon, right + horizon), + { + if brand.logo != none { + image(brand.logo, height: 12mm, alt: brand.logo-alt) + } else { + text(font: brand.fonts.heading, size: 14pt, weight: "bold", fill: brand.colors.primary, company-name) + } + }, + { + text(size: 9pt, fill: brand.colors.muted)[#doc-number \ #doc-date] + }, + ) + v(2mm) + line(length: 100%, stroke: 0.8pt + brand.colors.primary) + v(4mm) + text(font: brand.fonts.heading, size: 20pt, weight: "bold", fill: brand.colors.primary, doc-title) + v(4mm) +} diff --git a/document-studio/examples/templates/meeting-minutes/fragments/legal-mentions.typ b/document-studio/examples/templates/meeting-minutes/fragments/legal-mentions.typ new file mode 100644 index 0000000..f84313d --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/fragments/legal-mentions.typ @@ -0,0 +1,12 @@ +// Fragment partage : mentions legales. Le texte vient de la fiche entreprise +// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit. +#import "/brand.typ": brand + +#let legal-mentions(title, body) = { + v(6mm) + block(breakable: false, width: 100%)[ + #set text(size: 8pt, fill: brand.colors.muted) + #text(weight: "bold")[#title] \ + #body + ] +} diff --git a/document-studio/examples/templates/meeting-minutes/fragments/lines-table.typ b/document-studio/examples/templates/meeting-minutes/fragments/lines-table.typ new file mode 100644 index 0000000..a1c5456 --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/fragments/lines-table.typ @@ -0,0 +1,18 @@ +// Fragment partage : tableau de lignes (devis, facture lisible, commande). +// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus. +// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont). +#import "/brand.typ": brand + +#let lines-table(headers, rows, widths: auto, right-from: 1) = { + let ncols = headers.len() + let aligns = range(ncols).map(i => if i >= right-from { right } else { left }) + table( + columns: if widths == auto { (1fr,) + (auto,) * (ncols - 1) } else { widths }, + align: aligns, + inset: (x: 3mm, y: 2.2mm), + stroke: (x: none, y: 0.4pt + brand.colors.muted), + fill: (_, y) => if y == 0 { brand.colors.primary } else { none }, + ..headers.map(h => text(fill: white, weight: "bold", h)), + ..rows.flatten(), + ) +} diff --git a/document-studio/examples/templates/meeting-minutes/input.schema.json b/document-studio/examples/templates/meeting-minutes/input.schema.json new file mode 100644 index 0000000..49ddb10 --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/input.schema.json @@ -0,0 +1,45 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Donnees metier du compte rendu de reunion", + "type": "object", + "required": ["meeting", "participants", "agenda", "decisions", "actions"], + "properties": { + "meeting": { + "type": "object", + "required": ["title", "date"], + "properties": { + "title": { "type": "string", "minLength": 1 }, + "date": { "type": "string", "format": "date" }, + "time": { "type": "string" }, + "place": { "type": "string" } + } + }, + "participants": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["name", "role", "present"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "role": { "type": "string" }, + "present": { "type": "boolean" } + } + } + }, + "agenda": { "type": "array", "items": { "type": "string" } }, + "decisions": { "type": "array", "items": { "type": "string" } }, + "actions": { + "type": "array", + "items": { + "type": "object", + "required": ["description", "owner", "due_date"], + "properties": { + "description": { "type": "string", "minLength": 1 }, + "owner": { "type": "string", "minLength": 1 }, + "due_date": { "type": "string", "format": "date" } + } + } + } + } +} diff --git a/document-studio/examples/templates/meeting-minutes/main.typ b/document-studio/examples/templates/meeting-minutes/main.typ new file mode 100644 index 0000000..e8ad098 --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/main.typ @@ -0,0 +1,53 @@ +// Gabarit de reference `meeting-minutes` (compte rendu de reunion). +// Contrat : contracts/template/v1/. +#import "/brand.typ": brand, locale +#import "/fragments/header.typ": doc-header +#import "/fragments/footer.typ": doc-footer +#import "/fragments/legal-mentions.typ": legal-mentions +#import "/fragments/lines-table.typ": lines-table + +#set page( + paper: brand.page.paper, + margin: brand.page.margins, + footer: doc-footer([{{ .company.legal_name }} - {{ .i18n.strings.minutes_title }}]), +) +#set text(font: (brand.fonts.body, "Libertinus Serif"), size: 10pt, fill: brand.colors.text, lang: locale) + +#doc-header([{{ .company.trade_name }}], [{{ .i18n.strings.minutes_title }}], [{{ .doc.number }}], [{{ .doc.date }}]) + +*{{ .i18n.strings.minutes_meeting }}* : {{ .data.meeting.title }} \ +*{{ .i18n.strings.minutes_date }}* : {{ .data.meeting.date }} {{ .data.meeting.time | default "" }} \ +*{{ .i18n.strings.minutes_place }}* : {{ .data.meeting.place | default "-" }} + +#v(4mm) +== {{ .i18n.strings.minutes_participants }} +{{ range .data.participants }} +- *{{ .name }}*, {{ .role }}{{ if not .present }} ({{ $.i18n.strings.minutes_absent }}){{ end }} +{{- end }} + +== {{ .i18n.strings.minutes_agenda }} +{{ range .data.agenda }} ++ {{ . }} +{{- end }} + +== {{ .i18n.strings.minutes_decisions }} +{{ range .data.decisions }} +- {{ . }} +{{- end }} + +== {{ .i18n.strings.minutes_actions }} +#lines-table( + ( + [{{ .i18n.strings.minutes_col_action }}], + [{{ .i18n.strings.minutes_col_owner }}], + [{{ .i18n.strings.minutes_col_due }}], + ), + ( +{{- range .data.actions }} + ([{{ .description }}], [{{ .owner }}], [{{ .due_date }}]), +{{- end }} + ), + right-from: 3, +) + +#legal-mentions([{{ .i18n.strings.common_legal_notice }}], [{{ .company.legal_mentions }}]) diff --git a/document-studio/examples/templates/meeting-minutes/manifest.json b/document-studio/examples/templates/meeting-minutes/manifest.json new file mode 100644 index 0000000..dbdbb34 --- /dev/null +++ b/document-studio/examples/templates/meeting-minutes/manifest.json @@ -0,0 +1,41 @@ +{ + "schema": "agentmaurice.template/v1", + "key": "meeting-minutes", + "version": "1.0.0", + "title": "Compte rendu de réunion", + "description": "Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).", + "kind": "document", + "profile": "document", + "source": { + "engine": "typst", + "entry": "main.typ" + }, + "outputs": [ + "pdf" + ], + "locales": [ + "fr" + ], + "default_locale": "fr", + "input_schema": "input.schema.json", + "examples": [ + { + "name": "default", + "data": "examples/default.json" + }, + { + "name": "minimal", + "data": "examples/minimal.json" + } + ], + "fragments": [ + "fragments/header.typ", + "fragments/footer.typ", + "fragments/legal-mentions.typ", + "fragments/lines-table.typ" + ], + "limits": { + "max_source_bytes": 20000, + "max_pages": 3 + } +} diff --git a/document-studio/examples/templates/quote/examples/default.json b/document-studio/examples/templates/quote/examples/default.json new file mode 100644 index 0000000..1beb367 --- /dev/null +++ b/document-studio/examples/templates/quote/examples/default.json @@ -0,0 +1,43 @@ +{ + "reference": "AFF-2026-017", + "customer": { + "name": "Cabinet Fictif & Associés", + "address_lines": ["12 avenue de l'Échantillon", "00000 Exemple-sur-Seine"], + "contact": "Mme Dupont (exemple), contact@fictif.invalid" + }, + "lines": [ + { + "description": "Atelier de cadrage (2 demi-journées) #1", + "quantity": "2 forfaits", + "unit_price_ht": "600,00 €", + "vat_rate": "20 %", + "total_ht": "1 200,00 €" + }, + { + "description": "Développement du prototype_v1 [lot A]", + "quantity": "5 jours", + "unit_price_ht": "700,00 €", + "vat_rate": "20 %", + "total_ht": "3 500,00 €" + }, + { + "description": "Documentation et formation", + "quantity": "1 jour", + "unit_price_ht": "650,00 €", + "vat_rate": "20 %", + "total_ht": "650,00 €" + } + ], + "totals": { + "total_ht": "5 350,00 €", + "vat": [{ "rate": "20 %", "amount": "1 070,00 €" }], + "total_ttc": "6 420,00 €" + }, + "valid_until": "2026-12-06", + "terms": [ + "Acompte de 30 % à la commande.", + "Livraison sous 6 semaines après acompte.", + "Toute prestation supplémentaire fait l'objet d'un avenant." + ], + "payment_terms": "30 jours à réception de facture, par virement." +} diff --git a/document-studio/examples/templates/quote/fragments/footer.typ b/document-studio/examples/templates/quote/fragments/footer.typ new file mode 100644 index 0000000..6b9ba82 --- /dev/null +++ b/document-studio/examples/templates/quote/fragments/footer.typ @@ -0,0 +1,14 @@ +// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`. +#import "/brand.typ": brand + +#let doc-footer(company-line) = { + set text(size: 8pt, fill: brand.colors.muted) + line(length: 100%, stroke: 0.4pt + brand.colors.muted) + v(1mm) + grid( + columns: (1fr, auto), + align: (left, right), + company-line, + context [#counter(page).display() / #counter(page).final().first()], + ) +} diff --git a/document-studio/examples/templates/quote/fragments/header.typ b/document-studio/examples/templates/quote/fragments/header.typ new file mode 100644 index 0000000..0bfd11a --- /dev/null +++ b/document-studio/examples/templates/quote/fragments/header.typ @@ -0,0 +1,26 @@ +// Fragment partage : en-tete de document. Fonction pure, aucune balise Go. +// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees. +#import "/brand.typ": brand + +#let doc-header(company-name, doc-title, doc-number, doc-date) = { + grid( + columns: (1fr, auto), + gutter: 8mm, + align: (left + horizon, right + horizon), + { + if brand.logo != none { + image(brand.logo, height: 12mm, alt: brand.logo-alt) + } else { + text(font: brand.fonts.heading, size: 14pt, weight: "bold", fill: brand.colors.primary, company-name) + } + }, + { + text(size: 9pt, fill: brand.colors.muted)[#doc-number \ #doc-date] + }, + ) + v(2mm) + line(length: 100%, stroke: 0.8pt + brand.colors.primary) + v(4mm) + text(font: brand.fonts.heading, size: 20pt, weight: "bold", fill: brand.colors.primary, doc-title) + v(4mm) +} diff --git a/document-studio/examples/templates/quote/fragments/legal-mentions.typ b/document-studio/examples/templates/quote/fragments/legal-mentions.typ new file mode 100644 index 0000000..f84313d --- /dev/null +++ b/document-studio/examples/templates/quote/fragments/legal-mentions.typ @@ -0,0 +1,12 @@ +// Fragment partage : mentions legales. Le texte vient de la fiche entreprise +// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit. +#import "/brand.typ": brand + +#let legal-mentions(title, body) = { + v(6mm) + block(breakable: false, width: 100%)[ + #set text(size: 8pt, fill: brand.colors.muted) + #text(weight: "bold")[#title] \ + #body + ] +} diff --git a/document-studio/examples/templates/quote/fragments/lines-table.typ b/document-studio/examples/templates/quote/fragments/lines-table.typ new file mode 100644 index 0000000..a1c5456 --- /dev/null +++ b/document-studio/examples/templates/quote/fragments/lines-table.typ @@ -0,0 +1,18 @@ +// Fragment partage : tableau de lignes (devis, facture lisible, commande). +// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus. +// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont). +#import "/brand.typ": brand + +#let lines-table(headers, rows, widths: auto, right-from: 1) = { + let ncols = headers.len() + let aligns = range(ncols).map(i => if i >= right-from { right } else { left }) + table( + columns: if widths == auto { (1fr,) + (auto,) * (ncols - 1) } else { widths }, + align: aligns, + inset: (x: 3mm, y: 2.2mm), + stroke: (x: none, y: 0.4pt + brand.colors.muted), + fill: (_, y) => if y == 0 { brand.colors.primary } else { none }, + ..headers.map(h => text(fill: white, weight: "bold", h)), + ..rows.flatten(), + ) +} diff --git a/document-studio/examples/templates/quote/input.schema.json b/document-studio/examples/templates/quote/input.schema.json new file mode 100644 index 0000000..d865ee2 --- /dev/null +++ b/document-studio/examples/templates/quote/input.schema.json @@ -0,0 +1,62 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Donnees metier du devis", + "description": "Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.", + "type": "object", + "required": ["reference", "customer", "lines", "totals", "valid_until", "terms", "payment_terms"], + "properties": { + "reference": { "type": "string", "minLength": 1 }, + "customer": { + "type": "object", + "required": ["name", "address_lines", "contact"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "address_lines": { "type": "array", "items": { "type": "string" } }, + "contact": { "type": "string" } + } + }, + "lines": { + "type": "array", + "items": { + "type": "object", + "required": ["description", "quantity", "unit_price_ht", "vat_rate", "total_ht"], + "properties": { + "description": { "type": "string", "minLength": 1 }, + "quantity": { "type": "string", "description": "Quantite et unite, par exemple `3 jours`." }, + "unit_price_ht": { "$ref": "#/$defs/money" }, + "vat_rate": { "type": "string", "pattern": "^[0-9]+([,.][0-9]+)? ?%$" }, + "total_ht": { "$ref": "#/$defs/money" } + } + } + }, + "totals": { + "type": "object", + "required": ["total_ht", "vat", "total_ttc"], + "properties": { + "total_ht": { "$ref": "#/$defs/money" }, + "vat": { + "type": "array", + "items": { + "type": "object", + "required": ["rate", "amount"], + "properties": { + "rate": { "type": "string" }, + "amount": { "$ref": "#/$defs/money" } + } + } + }, + "total_ttc": { "$ref": "#/$defs/money" } + } + }, + "valid_until": { "type": "string", "format": "date" }, + "terms": { "type": "array", "items": { "type": "string" } }, + "payment_terms": { "type": "string" } + }, + "$defs": { + "money": { + "type": "string", + "pattern": "^-?[0-9][0-9 ]*,[0-9]{2} (EUR|€)$", + "description": "Montant formate en amont, par exemple `1 250,00 €`." + } + } +} diff --git a/document-studio/examples/templates/quote/main.typ b/document-studio/examples/templates/quote/main.typ new file mode 100644 index 0000000..e77d20c --- /dev/null +++ b/document-studio/examples/templates/quote/main.typ @@ -0,0 +1,82 @@ +// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/. +// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data). +#import "/brand.typ": brand, locale +#import "/fragments/header.typ": doc-header +#import "/fragments/footer.typ": doc-footer +#import "/fragments/legal-mentions.typ": legal-mentions +#import "/fragments/lines-table.typ": lines-table + +#set page( + paper: brand.page.paper, + margin: brand.page.margins, + footer: doc-footer([{{ .company.legal_name }} - {{ .company.siret }}]), +) +#set text(font: (brand.fonts.body, "Libertinus Serif"), size: 10pt, fill: brand.colors.text, lang: locale) +#set par(justify: false) + +#doc-header([{{ .company.trade_name }}], [{{ .i18n.strings.quote_title }} {{ .doc.number }}], [{{ .i18n.strings.quote_reference }} {{ .data.reference }}], [{{ .doc.date }}]) + +#grid( + columns: (1fr, 1fr), + gutter: 10mm, + [ + *{{ .company.legal_name }}* \ + {{ .company.address.line1 }} \ + {{ .company.address.postal_code }} {{ .company.address.city }} \ + {{ .company.email }} + ], + [ + *{{ .i18n.strings.quote_customer }}* \ + {{ .data.customer.name }} \ +{{- range .data.customer.address_lines }} + {{ . }} \ +{{- end }} + {{ .data.customer.contact }} + ], +) + +#v(6mm) + +#lines-table( + ( + [{{ .i18n.strings.quote_col_description }}], + [{{ .i18n.strings.quote_col_quantity }}], + [{{ .i18n.strings.quote_col_unit_price }}], + [{{ .i18n.strings.quote_col_vat }}], + [{{ .i18n.strings.quote_col_total }}], + ), + ( +{{- range .data.lines }} + ([{{ .description }}], [{{ .quantity }}], [{{ .unit_price_ht }}], [{{ .vat_rate }}], [{{ .total_ht }}]), +{{- end }} + ), +) + +#v(4mm) +#align(right, block(width: 60%, table( + columns: (1fr, auto), + align: (left, right), + stroke: none, + inset: (x: 2mm, y: 1.5mm), + [{{ .i18n.strings.quote_total_ht }}], [{{ .data.totals.total_ht }}], +{{- range .data.totals.vat }} + [{{ $.i18n.strings.quote_total_vat }} {{ .rate }}], [{{ .amount }}], +{{- end }} + [*{{ .i18n.strings.quote_total_ttc }}*], [*{{ .data.totals.total_ttc }}*], +))) + +#v(4mm) +*{{ .i18n.strings.quote_valid_until }}* {{ .data.valid_until }} + +#v(2mm) +*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement. + +#v(2mm) +*{{ .i18n.strings.quote_terms }}* +{{ range .data.terms }} +- {{ . }} +{{- end }} + +*{{ .i18n.strings.quote_payment }}* {{ .data.payment_terms }} + +#legal-mentions([{{ .i18n.strings.common_legal_notice }}], [{{ .company.legal_mentions }}]) diff --git a/document-studio/examples/templates/quote/manifest.json b/document-studio/examples/templates/quote/manifest.json new file mode 100644 index 0000000..1e11175 --- /dev/null +++ b/document-studio/examples/templates/quote/manifest.json @@ -0,0 +1,22 @@ +{ + "schema": "agentmaurice.template/v1", + "key": "quote", + "version": "1.0.0", + "title": "Devis", + "description": "Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.", + "kind": "document", + "profile": "document", + "source": { "engine": "typst", "entry": "main.typ" }, + "outputs": ["pdf"], + "locales": ["fr"], + "default_locale": "fr", + "input_schema": "input.schema.json", + "examples": [{ "name": "default", "data": "examples/default.json" }], + "fragments": [ + "fragments/header.typ", + "fragments/footer.typ", + "fragments/legal-mentions.typ", + "fragments/lines-table.typ" + ], + "limits": { "max_source_bytes": 20000, "max_pages": 4 } +} diff --git a/document-studio/module.yaml b/document-studio/module.yaml new file mode 100644 index 0000000..37cdb42 --- /dev/null +++ b/document-studio/module.yaml @@ -0,0 +1,88 @@ +{ + "$schema": "agentmaurice.module/v2", + "schema_version": 2, + "key": "document-studio", + "name": "Document studio", + "version": "0.1.0", + "provides": { + "actions": [ + { + "key": "document-studio-plan", + "name": "Plan a document", + "workflow_id": "document-studio-plan", + "workflow_version": "1" + }, + { + "key": "document-studio-draft", + "name": "Draft a document", + "workflow_id": "document-studio-draft", + "workflow_version": "1" + }, + { + "key": "document-studio-render", + "name": "Render a document preview", + "workflow_id": "document-studio-render", + "workflow_version": "1" + }, + { + "key": "document-studio-finalize", + "name": "Approve a document", + "workflow_id": "document-studio-finalize", + "workflow_version": "1" + }, + { + "key": "document-studio-publish", + "name": "Issue a document", + "workflow_id": "document-studio-publish", + "workflow_version": "1" + }, + { + "key": "document-studio-cancel", + "name": "Cancel a document", + "workflow_id": "document-studio-cancel", + "workflow_version": "1" + }, + { + "key": "document-studio-export", + "name": "Export a document", + "workflow_id": "document-studio-export", + "workflow_version": "1" + }, + { + "key": "document-studio-profile-save", + "name": "Save the company profile", + "workflow_id": "document-studio-profile-save", + "workflow_version": "1" + } + ], + "queries": [ + { + "key": "document-studio-list", + "name": "List documents", + "workflow_id": "document-studio-list", + "workflow_version": "1" + }, + { + "key": "document-studio-review-read", + "name": "Read a document for review", + "workflow_id": "document-studio-review-read", + "workflow_version": "1" + }, + { + "key": "document-studio-template-read", + "name": "Read the templates", + "workflow_id": "document-studio-template-read", + "workflow_version": "1" + } + ], + "apps": [ + { + "key": "document-studio-review", + "name": "Document studio", + "miniapp_id": "document-studio-review", + "miniapp_version": "1" + } + ] + }, + "requires": {} +} diff --git a/inventory/modules.json b/inventory/modules.json index 960dfa2..3f5ce0d 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1203,6 +1203,310 @@ "publication": "present in historical GitHub source at specified commit", "migration_m5_m6": "to define and qualify; deployment status is not inferred" }, + { + "key": "document-studio", + "version": "0.1.0", + "manifest": "document-studio/module.yaml", + "workflows": 11, + "miniapps": 1, + "source": { + "repository": "github.com/agentmaurice/modules", + "native": true + }, + "generators_and_composers": [ + "tooling/document-studio/build.py" + ], + "resources": { + "workflows": [ + "document-studio/agents/main/workflows/document-studio-cancel.json", + "document-studio/agents/main/workflows/document-studio-draft.json", + "document-studio/agents/main/workflows/document-studio-export.json", + "document-studio/agents/main/workflows/document-studio-finalize.json", + "document-studio/agents/main/workflows/document-studio-list.json", + "document-studio/agents/main/workflows/document-studio-plan.json", + "document-studio/agents/main/workflows/document-studio-profile-save.json", + "document-studio/agents/main/workflows/document-studio-publish.json", + "document-studio/agents/main/workflows/document-studio-render.json", + "document-studio/agents/main/workflows/document-studio-review-read.json", + "document-studio/agents/main/workflows/document-studio-template-read.json" + ], + "miniapps": [ + "document-studio/agents/main/miniapps/document-studio-review.json" + ], + "sha256": { + "document-studio/module.yaml": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", + "document-studio/agents/main/workflows/document-studio-cancel.json": "0432c9b1b735f76e59bb81ef3fd7752a2731d42f0a5a6d149b940f5e353462d4", + "document-studio/agents/main/workflows/document-studio-draft.json": "c73e995684eb920fabc042089f6479aca0b56e9de6554507b2bf22f6908969d8", + "document-studio/agents/main/workflows/document-studio-export.json": "e2db93c9e1645ce1e89d93f41fc03483a24d7e661249834c7ccba9ad759900e5", + "document-studio/agents/main/workflows/document-studio-finalize.json": "9f303f666de8498d2ce550cbf76c012fd587378ca7901bd71c56a7b1b127a3a0", + "document-studio/agents/main/workflows/document-studio-list.json": "7918dfde416e54d990801c936f0ad2371b53feffd85559ae1bbcd5578f7fdd53", + "document-studio/agents/main/workflows/document-studio-plan.json": "e25bae2637cd2acbd26a46b04a2e334797d8e09dbdf16dfaaecf13544bf41f8a", + "document-studio/agents/main/workflows/document-studio-profile-save.json": "08761c5dca9fdb518a343f498bd1c76249069677bcf5af43b506654461c40823", + "document-studio/agents/main/workflows/document-studio-publish.json": "2710078846b86065901d6abf86d5c358302de6dab56b9617a575945619f17862", + "document-studio/agents/main/workflows/document-studio-render.json": "106f73564245e9779342f089ad17921bd75b0ec9a5fd2548efd1b31c6e6da7bf", + "document-studio/agents/main/workflows/document-studio-review-read.json": "0ee90b45f6e0b8b8fe6dcbf144599322ac5884e83b042f22a409a18ca58c7347", + "document-studio/agents/main/workflows/document-studio-template-read.json": "fd3dc261617828143dc3001c80fd0a3e75f899e6e898d7f57663e0540cd9b498", + "document-studio/agents/main/miniapps/document-studio-review.json": "f0cbd478fba14f030465c2edb9d608d2781ff4c74b39d8a98ca924f46b212f83" + } + }, + "workflow_actions": { + "document-studio/agents/main/workflows/document-studio-cancel.json": { + "workflow_id": "document-studio-cancel", + "actions": [ + { + "path": "/actions/0", + "id": "cancel", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "e81e33a18cb18f3b7b36a79c9b38ee4fb4e7b7e6176824efe33a328bbde19991" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-draft.json": { + "workflow_id": "document-studio-draft", + "actions": [ + { + "path": "/actions/0", + "id": "prepare", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "cfd879c34989575c524ce92c53af6f879d9e1e0da1653e76b979c6808ef9662b" + }, + { + "path": "/actions/1", + "id": "draft-llm", + "type": "llm_call" + }, + { + "path": "/actions/2", + "id": "create", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "46553a9537b798bbc6b8942b46687cda2e4f114851f44a668ae9d68f04e05c44" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-export.json": { + "workflow_id": "document-studio-export", + "actions": [ + { + "path": "/actions/0", + "id": "export", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "9c142bc571ba70871304d915ef9fe59723c3d7e761e5ad2879ddfe7d3cbc5038" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-finalize.json": { + "workflow_id": "document-studio-finalize", + "actions": [ + { + "path": "/actions/0", + "id": "finalize", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "73bd6acf2e250bcbb3889039f5a8b76f43b04c4c01fc6cca0b3874390a6a6052" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-list.json": { + "workflow_id": "document-studio-list", + "actions": [ + { + "path": "/actions/0", + "id": "list", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "ac18cb9f0c4f23f35c1284a6afae17bd6eaf55bcec5737b7da32a55782bed985" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-plan.json": { + "workflow_id": "document-studio-plan", + "actions": [ + { + "path": "/actions/0", + "id": "prepare", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "8851378d173f44c79bedde735dd5173a6f38e63d91a382f4202cfd4bce682e84" + }, + { + "path": "/actions/1", + "id": "plan-llm", + "type": "llm_call" + }, + { + "path": "/actions/2", + "id": "normalize", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "dc6a36447e6708d3e180bc775b071e60d189f8e8b1dadee152bd7ccc181d6bb3" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-profile-save.json": { + "workflow_id": "document-studio-profile-save", + "actions": [ + { + "path": "/actions/0", + "id": "save", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "ec220966d563ccf4b446a4e1a9efb2eb902d355b1d77a7f8602b49cef188499d" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-publish.json": { + "workflow_id": "document-studio-publish", + "actions": [ + { + "path": "/actions/0", + "id": "publish", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "fe9e6999acea0f197058310f7bebc3cc2e1e673cb3c46b7157a5b6ee8a130580" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-render.json": { + "workflow_id": "document-studio-render", + "actions": [ + { + "path": "/actions/0", + "id": "render", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "1ef4fedc0f5c1f2e83a124d9e8183455cb6f41f1661b680d439c49b42ef44957" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-review-read.json": { + "workflow_id": "document-studio-review-read", + "actions": [ + { + "path": "/actions/0", + "id": "read", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "f34f8cc836a018e5ddab24303991c4669c11c5c6a92f2b2379691020b03ad438" + } + ] + }, + "document-studio/agents/main/workflows/document-studio-template-read.json": { + "workflow_id": "document-studio-template-read", + "actions": [ + { + "path": "/actions/0", + "id": "read", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "e2fb49e05f7138b1bac1838571ae11327c47c85316e00944b7de1dd03be68aa6" + } + ] + } + }, + "provides": { + "actions": [ + { + "key": "document-studio-plan", + "name": "Plan a document", + "workflow_id": "document-studio-plan", + "workflow_version": "1" + }, + { + "key": "document-studio-draft", + "name": "Draft a document", + "workflow_id": "document-studio-draft", + "workflow_version": "1" + }, + { + "key": "document-studio-render", + "name": "Render a document preview", + "workflow_id": "document-studio-render", + "workflow_version": "1" + }, + { + "key": "document-studio-finalize", + "name": "Approve a document", + "workflow_id": "document-studio-finalize", + "workflow_version": "1" + }, + { + "key": "document-studio-publish", + "name": "Issue a document", + "workflow_id": "document-studio-publish", + "workflow_version": "1" + }, + { + "key": "document-studio-cancel", + "name": "Cancel a document", + "workflow_id": "document-studio-cancel", + "workflow_version": "1" + }, + { + "key": "document-studio-export", + "name": "Export a document", + "workflow_id": "document-studio-export", + "workflow_version": "1" + }, + { + "key": "document-studio-profile-save", + "name": "Save the company profile", + "workflow_id": "document-studio-profile-save", + "workflow_version": "1" + } + ], + "queries": [ + { + "key": "document-studio-list", + "name": "List documents", + "workflow_id": "document-studio-list", + "workflow_version": "1" + }, + { + "key": "document-studio-review-read", + "name": "Read a document for review", + "workflow_id": "document-studio-review-read", + "workflow_version": "1" + }, + { + "key": "document-studio-template-read", + "name": "Read the templates", + "workflow_id": "document-studio-template-read", + "workflow_version": "1" + } + ], + "apps": [ + { + "key": "document-studio-review", + "name": "Document studio", + "miniapp_id": "document-studio-review", + "miniapp_version": "1" + } + ] + }, + "requires": {}, + "composition_dependencies": [], + "known_consumers": [], + "language": "English source", + "runtime": "Static observation of Agent Spec V2 definitions; runtime execution and qualification are not inferred", + "publication": "native to this repository, unpublished" + }, { "key": "cib-enterprise-admin", "version": "0.2.2", diff --git a/modules.json b/modules.json index 760a62c..c13a094 100644 --- a/modules.json +++ b/modules.json @@ -29,6 +29,13 @@ "workflows": 4, "miniapps": 3 }, + { + "key": "document-studio", + "version": "0.1.0", + "manifest": "document-studio/module.yaml", + "workflows": 11, + "miniapps": 1 + }, { "key": "cib-enterprise-admin", "version": "0.2.2", diff --git a/scripts/inventory.py b/scripts/inventory.py index ea6c43c..f5cb227 100644 --- a/scripts/inventory.py +++ b/scripts/inventory.py @@ -50,6 +50,8 @@ 'language': 'English source', 'publication': 'native to this repository, unpublished'}, 'profile': {'generators': ['tooling/profile/build.py', 'tooling/profile/compose.py'], 'language': 'English source', 'publication': 'native to this repository, unpublished'}, + 'document-studio': {'generators': ['tooling/document-studio/build.py'], + 'language': 'English source', 'publication': 'native to this repository, unpublished'}, } CONSUMERS = { 'watch-memory': ['watch', 'company-memory'], 'content-memory': ['content', 'company-memory'], diff --git a/scripts/test.py b/scripts/test.py index 1e93eb9..32f0a80 100644 --- a/scripts/test.py +++ b/scripts/test.py @@ -3,7 +3,7 @@ import os, shutil, subprocess, sys, tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -PYTHON_SUITES = ['templates/company-in-a-box/tests'] + [f'tooling/{name}/tests' for name in ('company-memory', 'memory-integration', 'daily-routine', 'work-cases', 'enterprise-admin', 'marketing-launch', 'image-studio', 'profile', 'catalog')] +PYTHON_SUITES = ['templates/company-in-a-box/tests'] + [f'tooling/{name}/tests' for name in ('company-memory', 'memory-integration', 'daily-routine', 'work-cases', 'enterprise-admin', 'marketing-launch', 'image-studio', 'profile', 'document-studio', 'catalog')] NODE_TESTS = [f'tooling/{path}' for path in ('memory-integration/tests/test_publication.mjs', 'daily-routine/tests/metrics.test.mjs', 'work-cases/tests/domain.test.mjs', 'marketing-launch/tests/test_domain.cjs', 'marketing-launch/tests/test_generated_runtime.cjs')] def main(): env = {**os.environ, 'PYTHONDONTWRITEBYTECODE': '1'} @@ -18,7 +18,7 @@ def main(): subprocess.run([sys.executable, '-m', 'unittest', 'discover', '-s', str(work / name), '-p', 'test_*.py', '-v'], env=env, cwd=work, check=True) for name in NODE_TESTS: subprocess.run(['node', str(work / name)], env=env, cwd=work, check=True) - for name in ('work-cases', 'daily-routine', 'enterprise-admin', 'marketing-launch', 'image-studio', 'profile'): + for name in ('work-cases', 'daily-routine', 'enterprise-admin', 'marketing-launch', 'image-studio', 'profile', 'document-studio'): module = work / name before = {p.relative_to(module): p.read_bytes() for p in module.rglob('*') if p.is_file()} extras = [work / 'templates/company-in-a-box/tests/marketing-launch-plan.json', work / 'tooling/marketing-launch/service-gates.json'] if name == 'marketing-launch' else [] @@ -28,5 +28,5 @@ def main(): if before != after or any(p.read_bytes() != data for p, data in extra_before.items()): raise SystemExit(f'{name}: le générateur ne reproduit pas les ressources publiées') - print('PASS: 10 suites unittest, contrat ACL Python et 5 contrôles Node et 6 reconstructions à octets identiques, sans réseau ni runtime.') + print('PASS: 11 suites unittest, contrat ACL Python et 5 contrôles Node et 7 reconstructions à octets identiques, sans réseau ni runtime.') if __name__ == '__main__': main() diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py new file mode 100644 index 0000000..c6d7f89 --- /dev/null +++ b/tooling/document-studio/build.py @@ -0,0 +1,857 @@ +#!/usr/bin/env python3 +"""Generate the document-studio Module resources (manifest, Workflows, MiniApp). + +No rendering engine lives in the Module: rendering goes through the MCP tool +`artifact--artifact_render_v1`. The two reference templates (quote and +meeting-minutes) are embedded as text in the Workflows that render; they are +the files of document-studio/examples/templates, pinned by contract/PIN.json. +Code steps are plain JavaScript (code_execution). The code never contains a +double-brace sequence: the Workflow engine would read it as a template action, +so template files are embedded with escaped braces (see js_embed). +Run this script after any change; the offline tests check that the published +resources match its output byte for byte. +""" +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +MODULE = ROOT.parents[1] / 'document-studio' +DEST = MODULE / 'agents/main' +TEMPLATES_DIR = MODULE / 'examples/templates' +VERSION = '0.1.0' +RENDER_TOOL = 'artifact--artifact_render_v1' +STORAGE_TOOLS = ['read_file', 'write_file', 'list_files'] +RENDER_TOOLS = STORAGE_TOOLS + [RENDER_TOOL] +I18N = json.loads((ROOT / 'contract/i18n.fr.json').read_text(encoding='utf-8')) + +# Draft data of a quote: numbers, never formatted amounts and never totals. +# The Workflow computes amounts and totals from the lines (integer cents). +QUOTE_DRAFT_SCHEMA = { + 'type': 'object', + 'required': ['customer', 'lines', 'valid_until', 'terms', 'payment_terms'], + 'properties': { + 'reference': {'type': 'string'}, + 'customer': { + 'type': 'object', 'required': ['name'], + 'properties': {'name': {'type': 'string', 'minLength': 1}, + 'address_lines': {'type': 'array', 'items': {'type': 'string'}}, + 'contact': {'type': 'string'}}}, + 'lines': { + 'type': 'array', 'minItems': 1, 'maxItems': 40, + 'items': { + 'type': 'object', 'required': ['description', 'quantity', 'unit_price_ht', 'vat_rate'], + 'properties': { + 'description': {'type': 'string', 'minLength': 1}, + 'quantity': {'type': 'number', 'exclusiveMinimum': 0, 'maximum': 1000000}, + 'unit': {'type': 'string'}, + 'unit_price_ht': {'type': 'number', 'minimum': 0, 'maximum': 1000000000}, + 'vat_rate': {'type': 'number', 'minimum': 0, 'maximum': 100}}}}, + 'valid_until': {'type': 'string', 'format': 'date'}, + 'terms': {'type': 'array', 'items': {'type': 'string'}}, + 'payment_terms': {'type': 'string'}}, +} +TEMPLATE_META = { + 'quote': {'prefix': 'DEV', 'draft_schema': QUOTE_DRAFT_SCHEMA, + 'summary': 'Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.'}, + 'meeting-minutes': {'prefix': 'CR', 'draft_schema': None, + 'summary': 'Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).'}, +} + + +def dump(path, data): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') + + +def js_embed(value): + """A JavaScript expression that rebuilds `value`, with every brace written as a unicode escape.""" + literal = json.dumps(json.dumps(value, ensure_ascii=False, sort_keys=True), ensure_ascii=False) + return 'JSON.parse(' + literal.replace('{', '\\u007b').replace('}', '\\u007d') + ')' + + +def load_templates(with_files): + templates = {} + for key, meta in TEMPLATE_META.items(): + directory = TEMPLATES_DIR / key + manifest = json.loads((directory / 'manifest.json').read_text(encoding='utf-8')) + input_schema = json.loads((directory / 'input.schema.json').read_text(encoding='utf-8')) + entry = {'manifest': manifest, 'input_schema': input_schema, 'prefix': meta['prefix'], + 'title': manifest['title'], 'summary': meta['summary'], + 'draft_schema': meta['draft_schema'] or input_schema} + if with_files: + entry['files'] = {p.relative_to(directory).as_posix(): p.read_text(encoding='utf-8') + for p in sorted(directory.rglob('*')) if p.is_file()} + templates[key] = entry + return templates + + +# --------------------------------------------------------------------------- +# JavaScript (Deno sandbox). No double-brace sequence anywhere in this text. +# --------------------------------------------------------------------------- +IMPORT = "import { callTool } from './tools/nats_bridge.ts';\n" + +CORE = r''' +const ROOT = "/document-studio"; +const ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/; +const STATUSES = ["draft", "approved", "issued", "cancelled"]; + +function fail(code, message) { throw new Error(message ? code + ": " + message : code); } +function isObject(v) { return v !== null && typeof v === "object" && !Array.isArray(v); } +function confirmed(v) { return v === true || v === "true" || v === "oui"; } +function requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail("manual_confirmation_required", "confirmez explicitement (confirmation_manuelle = oui)"); } +function today() { return new Date().toISOString().slice(0, 10); } +function nowIso() { return new Date().toISOString(); } +function docIdOf(v) { if (typeof v !== "string" || !ID_RE.test(v)) fail("doc_id_invalid", "attendu : minuscules, chiffres et tirets, 48 caractères au plus"); return v; } +function slugify(text) { + const base = String(text || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/g, ""); + return base || "doc"; +} +function shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, "0")).join(""); } +function validDate(v) { + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(typeof v === "string" ? v : ""); + if (!m) return false; + const d = new Date(v + "T00:00:00Z"); + return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]); +} +function text(v, name, max, required) { + if (v === undefined || v === null || v === "") { if (required) fail(name + "_required"); return ""; } + if (typeof v !== "string" || v.length > max) fail(name + "_invalid"); + const t = v.trim(); + if (required && !t) fail(name + "_required"); + return t; +} +function b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } +async function sha256Hex(bytes) { const d = await crypto.subtle.digest("SHA-256", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, "0")).join(""); } +function parseJsonValue(v) { + if (typeof v !== "string") return v; + const cleaned = v.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, ""); + try { return JSON.parse(cleaned); } catch (e) { fail("llm_output_invalid", "réponse non JSON"); } +} + +// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false, +// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum. +function checkSchema(schema, value, path, root, errors) { + if (errors.length >= 8) return; + if (schema.$ref) { + if (!schema.$ref.startsWith("#/")) fail("schema_ref_unsupported", schema.$ref); + let node = root; + for (const part of schema.$ref.slice(2).split("/")) node = node ? node[part] : undefined; + if (!node) fail("schema_ref_unknown", schema.$ref); + return checkSchema(node, value, path, root, errors); + } + const t = schema.type; + if (t) { + const ok = t === "string" ? typeof value === "string" : t === "number" ? (typeof value === "number" && Number.isFinite(value)) : t === "integer" ? Number.isInteger(value) : t === "boolean" ? typeof value === "boolean" : t === "array" ? Array.isArray(value) : t === "object" ? isObject(value) : true; + if (!ok) { errors.push(path + " : type " + t + " attendu"); return; } + } + if (schema.enum && !schema.enum.includes(value)) errors.push(path + " : valeur hors liste"); + if (typeof value === "string") { + if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + " : vide ou trop court"); + if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + " : format invalide"); + if (schema.format === "date" && !validDate(value)) errors.push(path + " : date AAAA-MM-JJ invalide"); + } + if (typeof value === "number") { + if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + " : inférieur au minimum"); + if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + " : doit être supérieur à " + schema.exclusiveMinimum); + if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + " : supérieur au maximum"); + } + if (Array.isArray(value)) { + if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + " : trop peu d'éléments"); + if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + " : trop d'éléments"); + if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + "[" + i + "]", root, errors)); + } + if (isObject(value)) { + for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + "." + key + " : requis"); + const props = schema.properties || {}; + for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + "." + key, root, errors); + if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + "." + key + " : champ inconnu"); + } +} +function validateSchema(schema, value, label) { + const errors = []; + checkSchema(schema, value, "$", schema, errors); + if (errors.length) fail("data_invalid", label + " : " + errors.join(" ; ")); +} + +function fmtMoney(cents) { + const abs = Math.abs(cents); + const grouped = String(Math.floor(abs / 100)).replace(/\B(?=(\d{3})+(?!\d))/g, " "); + return (cents < 0 ? "-" : "") + grouped + "," + String(abs % 100).padStart(2, "0") + " €"; +} +function fmtNumber(n) { return String(n).replace(".", ","); } +function fmtRate(r) { return fmtNumber(r) + " %"; } + +// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model. +function quoteData(d) { + const lines = []; + let ht = 0; + const groups = new Map(); + for (const l of d.lines) { + const unitCents = Math.round(l.unit_price_ht * 100); + const totalCents = Math.round(l.quantity * unitCents); + const rateHundredths = Math.round(l.vat_rate * 100); + ht += totalCents; + groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents); + lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? " " + l.unit : ""), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)}); + } + let vatTotal = 0; + const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => { + const cents = Math.round(base * rate / 10000); + vatTotal += cents; + return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)}; + }); + const customer = d.customer; + return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || ""}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || ""}; +} +function templateData(key, data) { return key === "quote" ? quoteData(data) : data; } + +// Draft data: reference default, validation against the draft schema, then against the template input schema. +function normalizeData(key, data, id) { + if (!isObject(data)) fail("data_invalid", "les données doivent être un objet"); + let d = data; + if (key === "quote" && (d.reference === undefined || d.reference === null || d.reference === "")) d = {...d, reference: id.toUpperCase()}; + const tpl = TEMPLATES[key]; + validateSchema(tpl.draft_schema, d, "données du gabarit " + key); + validateSchema(tpl.input_schema, templateData(key, d), "gabarit " + key); + return d; +} + +function summarize(rec) { + const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null; + return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued}; +} +function checkRecord(rec, id) { + if (!isObject(rec) || rec.schema !== "document-studio.record/v1" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== "string" || !isObject(rec.data)) fail("record_invalid", id); + return rec; +} +''' + +IO = r''' +function unwrap(r) { + if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data; + return r; +} +async function readText(path, extra) { + const r = unwrap(await callTool("read_file", {path, ...(extra || {})})); + if (typeof r === "string") return r; + if (isObject(r) && typeof r.content === "string") return r.content; + fail("storage_read_failed", path); +} +async function readJson(path) { return JSON.parse(await readText(path)); } +async function writeJson(path, value, overwrite) { + await callTool("write_file", {path, content: JSON.stringify(value, null, 2) + "\n", overwrite}); +} +async function listPaths(path) { + let r; + try { r = unwrap(await callTool("list_files", {path})); } catch (e) { return []; } + const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []); + return entries.map((e) => (typeof e === "string" ? e : (isObject(e) && typeof e.path === "string" ? e.path : ""))).filter(Boolean); +} +function recordPath(id) { return ROOT + "/docs/" + id + "/record.json"; } +async function loadRecord(id) { + let rec; + try { rec = await readJson(recordPath(id)); } catch (e) { fail("document_not_found", id); } + return checkRecord(rec, id); +} +async function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); } +async function loadProfile() { + let stored = null; + try { stored = await readJson(ROOT + "/profile.json"); } catch (e) { stored = null; } + if (!isObject(stored)) fail("profile_missing", "enregistrez la charte par document-studio-profile-save"); + return projectProfile(normalizeProfile(stored)); +} +''' + +PROFILE = r''' +const COLOR = /^#[0-9a-fA-F]{6}$/; +const IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/; +const BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/; +const COLOR_TOKENS = ["primary", "secondary", "accent", "text", "muted", "background"]; +const FONT_ROLES = ["heading", "body", "mono"]; +const MARGIN_SIDES = ["top", "right", "bottom", "left"]; +const ADDRESS_PARTS = ["line1", "line2", "postal_code", "city", "country"]; +const COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000}; +function onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + "_unknown_field", k); } + +// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload. +function normalizeProfile(p) { + if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail("profile_invalid", "schema_version 1 attendu"); + onlyKeys(p, ["schema_version", "company", "brand"], "profile"); + const c = p.company, b = p.brand; + if (!isObject(c) || !isObject(b)) fail("profile_invalid", "company et brand sont requis"); + if (c.logo !== undefined) fail("profile_invalid", "company.logo est dérivé de brand.logo.ref"); + onlyKeys(c, ["legal_name", ...Object.keys(COMPANY_TEXT), "address", "bank"], "company"); + const company = {legal_name: text(c.legal_name, "legal_name", 200, true)}; + for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; } + if (c.address !== undefined) { + if (!isObject(c.address)) fail("address_invalid"); + onlyKeys(c.address, ADDRESS_PARTS, "address"); + const address = {}; + for (const part of ADDRESS_PARTS) { const v = text(c.address[part], "address_" + part, 200, false); if (v) address[part] = v; } + if (Object.keys(address).length) company.address = address; + } + if (c.bank !== undefined) { + if (!isObject(c.bank)) fail("bank_invalid"); + onlyKeys(c.bank, ["account_holder", "iban", "bic", "bank_name"], "bank"); + const bank = {}; + for (const key of ["account_holder", "bank_name"]) { const v = text(c.bank[key], "bank_" + key, 200, false); if (v) bank[key] = v; } + if (c.bank.iban !== undefined && c.bank.iban !== "") { + const iban = typeof c.bank.iban === "string" ? c.bank.iban.replace(/\s+/g, "").toUpperCase() : ""; + if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail("iban_invalid"); + bank.iban = iban; + } + if (c.bank.bic !== undefined && c.bank.bic !== "") { + const bic = typeof c.bank.bic === "string" ? c.bank.bic.replace(/\s+/g, "").toUpperCase() : ""; + if (!BIC.test(bic)) fail("bic_invalid"); + bank.bic = bic; + } + if (Object.keys(bank).length) company.bank = bank; + } + onlyKeys(b, ["colors", "fonts", "logo", "page", "spacing"], "brand"); + if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail("brand_invalid"); + const colors = {}; + for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== "string" || !COLOR.test(b.colors[token])) fail("color_" + token + "_invalid", "attendu #RRGGBB"); colors[token] = b.colors[token]; } + const fonts = {}; + for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail("font_" + role + "_invalid"); fonts[role] = {family: text(b.fonts[role].family, "font_" + role, 100, true)}; } + const ref = b.logo.ref; + if (typeof ref !== "string" || !ref || ref.length > 500 || /\s/.test(ref) || ref.includes("..") || ref.toLowerCase().includes("secret://")) fail("logo_ref_invalid"); + if (b.page.size !== "A4" && b.page.size !== "Letter") fail("page_size_invalid"); + const margins_mm = {}; + for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== "number" || !Number.isFinite(m) || m < 0 || m > 100) fail("margin_" + side + "_invalid"); margins_mm[side] = m; } + const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, "logo_alt", 200, true)}, page: {size: b.page.size, margins_mm}}; + if (b.spacing !== undefined) { + if (!isObject(b.spacing)) fail("spacing_invalid"); + for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== "number" || v < 0) fail("spacing_invalid", k); + brand.spacing = b.spacing; + } + return {schema_version: 1, company, brand}; +} + +// The templates read these company fields without a guard: an absent value becomes an empty string. +function projectProfile(body) { + const company = {...body.company}; + if (!company.trade_name) company.trade_name = company.legal_name; + for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = ""; + company.address = {line1: "", line2: "", postal_code: "", city: "", country: "", ...(company.address || {})}; + company.logo = {ref: body.brand.logo.ref}; + return {company, brand: body.brand}; +} +''' + +RENDER = r''' +function safeName(name, fallback) { + const base = typeof name === "string" ? name.split("/").pop() : ""; + return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(".") ? base : fallback; +} + +async function renderDocument(rec, data, profile, mode, number, status, revision) { + const tpl = TEMPLATES[rec.template_key]; + if (!tpl) fail("template_unknown", rec.template_key); + const tdata = templateData(rec.template_key, data); + validateSchema(tpl.input_schema, tdata, "gabarit " + rec.template_key); + const doc = {number: number || "BROUILLON", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale}; + const raw = await callTool("artifact--artifact_render_v1", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: "pdf", mode}); + const res = unwrap(raw); + if (isObject(res) && res.error) fail("render_failed", res.error + (res.message ? " : " + res.message : "")); + if (!isObject(res) || res.status !== "ok" || !isObject(res.file)) fail("render_failed", "réponse inattendue du moteur de rendu"); + return res; +} + +// Stores one rendered file: by buffer reference when the engine gives one, else from base64. +async function storeFile(path, f) { + const args = {path, overwrite: true}; + let sha = typeof f.sha256 === "string" ? f.sha256 : ""; + if (f.ref !== undefined && f.ref !== null && f.ref !== "") args.buffer_ref = f.ref; + else if (typeof f.content_base64 === "string") { + const computed = await sha256Hex(b64ToBytes(f.content_base64)); + if (sha && sha !== computed) fail("render_integrity_failed", path); + sha = computed; + args.content = f.content_base64; + args.encoding = "base64"; + } else fail("render_output_missing", path); + await callTool("write_file", args); + return {path, sha256: sha, bytes: typeof f.bytes === "number" ? f.bytes : null, mime: typeof f.mime_type === "string" ? f.mime_type : "application/octet-stream"}; +} +async function storePreviews(dir, res) { + const previews = []; + for (const p of Array.isArray(res.previews) ? res.previews : []) { + const page = Number.isInteger(p.page) ? p.page : previews.length + 1; + const stored = await storeFile(dir + "/" + safeName(p.filename, "page-" + page + ".png"), p); + previews.push({page, path: stored.path, sha256: stored.sha256}); + } + return previews; +} +''' + +NUMBERING = r''' +// Number reservation: lists the year folder, takes max + 1, writes the token without overwrite, reads it back and +// checks the owner. Not atomic: the check narrows the window, it does not close it. +async function reserveNumber(rec) { + const year = new Date().getUTCFullYear(); + const dir = ROOT + "/numbers/" + rec.template_key + "/" + year; + let last = ""; + for (let attempt = 0; attempt < 5; attempt++) { + const paths = await listPaths(dir); + let max = 0; + for (const p of paths) { const m = /(?:^|\/)(\d{4,})\.json$/.exec(p); if (m) max = Math.max(max, Number(m[1])); } + const seq = String(max + 1).padStart(4, "0"); + const path = dir + "/" + seq + ".json"; + try { await writeJson(path, {doc_id: rec.doc_id, at: nowIso()}, false); } catch (e) { last = String(e && e.message); continue; } + let token = null; + try { token = await readJson(path); } catch (e) { last = String(e && e.message); continue; } + if (isObject(token) && token.doc_id === rec.doc_id) return TEMPLATES[rec.template_key].prefix + "-" + year + "-" + seq; + last = "numéro " + seq + " pris par un autre document"; + } + fail("number_conflict", "5 essais sans numéro libre (" + last + ")"); +} +''' + + +def code(*parts): + body = ''.join(parts) + assert '{{' not in body.replace('{{ json . }}', ''), 'a double-brace sequence in the JavaScript' + return body + + +def node(action_id, source, output_key, tools=None): + data = {'id': action_id, 'type': 'code_execution'} + if tools: + data['context'] = {'allowed_tools': tools} + data.update({'code': source, 'output_key': output_key}) + return data + + +def lib(*, templates=None, io=False, profile=False, render=False, numbering=False): + parts = [IMPORT if io else ''] + if templates is not None: + parts.append('const TEMPLATES = ' + js_embed(load_templates(templates == 'full')) + ';\n') + if render: + parts.append('const I18N = ' + js_embed(I18N) + ';\n') + parts.append(CORE) + if profile: + parts.append(PROFILE) + if io: + parts.append(IO) + if render: + parts.append(RENDER) + if numbering: + parts.append(NUMBERING) + return ''.join(parts) + + +def text(description, **extra): + return {'type': 'string', 'description': description, **extra} + + +def schema(required, **props): + return {'type': 'object', 'required': required, 'additionalProperties': False, 'properties': props} + + +DOC_ID = text('Document identifier: lowercase letters, digits and hyphens', pattern='^[a-z0-9][a-z0-9-]{0,47}$') +CONFIRM = {'type': ['boolean', 'string'], 'description': 'Manual confirmation: oui (or true) to proceed'} +LOCALE = text('Document language; fr only in V0', enum=['fr']) +TEMPLATE_KEY = text('Template key', enum=['quote', 'meeting-minutes']) +SUMMARY_OUT = {'doc_id': '{{ result.doc_id }}', 'template_key': '{{ result.template_key }}', 'title': '{{ result.title }}', + 'status': '{{ result.status }}', 'number': '{{ result.number }}', 'revision': '{{ result.revision }}', + 'renders': '{{ result.renders }}', 'last_render': '{{ result.last_render }}', 'issued': '{{ result.issued }}'} +CONFIRM_FIELD = {'name': 'confirmation_manuelle', 'title': 'Confirmation manuelle', 'type': 'select', 'required': True, + 'options': [{'value': 'non', 'label': 'Non'}, {'value': 'oui', 'label': 'Oui'}], 'default': 'non'} + + +def workflow(workflow_id, title, description, input_schema, actions, output, forms=None): + data = {'$schema': 'agentmaurice.workflow/v2', 'schema_version': 2, 'workflow_id': workflow_id, 'kind': 'workflow', + 'title': title, 'version': '1', 'description': description, 'input_schema': input_schema} + if forms: + data['forms'] = forms + data.update({'actions': actions, 'output': output}) + dump(DEST / 'workflows' / f'{workflow_id}.json', data) + return data + + +def form(form_id, title, fields, actions): + return {'id': form_id, 'title': title, 'fields': fields, 'actions_on_submit': actions} + + +def field(name, title, kind, required, **extra): + return {'name': name, 'title': title, 'type': kind, 'required': required, **extra} + + +def llm(action_id, prompt_ref, system, output_key, tokens): + return {'id': action_id, 'type': 'llm_call', 'llm_prompt': prompt_ref, 'llm_system_prompt': system, + 'llm_temperature': 0.2, 'llm_max_tokens': tokens, 'llm_response_format': 'json', + 'llm_response_schema': {'type': 'object'}, 'output_key': output_key} + + +SYSTEM = 'Tu es un assistant de rédaction de documents professionnels. Tu réponds uniquement par un objet JSON, sans texte autour.' + +PLAN_PREPARE = r''' +const input = {{ json . }}; +const brief = text(input.brief, "brief", 8000, true); +let key = null; +if (input.template_key !== undefined && input.template_key !== null && input.template_key !== "") { key = input.template_key; if (!TEMPLATES[key]) fail("template_unknown", String(key)); } +const locale = input.locale || "fr"; +if (locale !== "fr") fail("locale_unsupported", "seul fr est disponible en V0"); +const catalogue = Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, summary: TEMPLATES[k].summary, data_schema: TEMPLATES[k].draft_schema})); +const prompt = "Brief du demandeur :\n" + brief + "\n\n" + (key ? "Gabarit imposé : " + key + "\n\n" : "") + "Gabarits disponibles (avec le schéma JSON des données attendues) :\n" + JSON.stringify(catalogue) + "\n\nChoisis le gabarit adapté, propose un titre court et liste ce qui manque dans le brief pour remplir toutes les données requises du schéma. Ne remplis aucune donnée. Réponds par un objet JSON : {\"template_key\": string, \"title\": string, \"missing\": [string], \"questions\": [string]}. \"missing\" nomme les données absentes, \"questions\" les formule en questions au demandeur, en français."; +return {prompt, template_key: key, locale}; +''' +PLAN_NORMALIZE = r''' +const input = {{ json . }}; +const prep = input.prep; +const out = parseJsonValue(input.plan_draft); +if (!isObject(out)) fail("llm_output_invalid", "objet attendu"); +const key = prep.template_key || out.template_key; +if (typeof key !== "string" || !TEMPLATES[key]) fail("template_unknown", String(key)); +const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string" && x.trim()).map((x) => x.trim().slice(0, 300)).slice(0, 20) : []); +const title = typeof out.title === "string" && out.title.trim() ? out.title.trim().slice(0, 120) : TEMPLATES[key].title; +return {template_key: key, title, locale: prep.locale, missing: list(out.missing), questions: list(out.questions)}; +''' + +DRAFT_PREPARE = r''' +const input = {{ json . }}; +const brief = text(input.brief, "brief", 8000, true); +const key = input.template_key; +if (typeof key !== "string" || !TEMPLATES[key]) fail("template_unknown", String(key)); +const locale = input.locale || "fr"; +if (locale !== "fr") fail("locale_unsupported", "seul fr est disponible en V0"); +if (input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== "") docIdOf(input.doc_id); +if (input.answers !== undefined && input.answers !== null && !isObject(input.answers)) fail("answers_invalid", "objet attendu"); +const prompt = "Brief du demandeur :\n" + brief + "\n\n" + (input.answers && Object.keys(input.answers).length ? "Réponses complémentaires du demandeur :\n" + JSON.stringify(input.answers) + "\n\n" : "") + "Date du jour : " + today() + ".\n\nRemplis les données du document \"" + key + "\" selon ce schéma JSON :\n" + JSON.stringify(TEMPLATES[key].draft_schema) + "\n\nRègles : réponds par l'objet de données seul, conforme au schéma. N'invente ni client, ni prix, ni date, ni participant : si une donnée requise manque, réponds uniquement {\"missing\": [\"description de ce qui manque\"]}. Ne calcule aucun total ni montant TTC. Dates au format AAAA-MM-JJ. Texte en français."; +return {prompt, template_key: key, locale}; +''' +DRAFT_CREATE = r''' +const input = {{ json . }}; +const prep = input.prep; +const key = prep.template_key; +let data = parseJsonValue(input.draft); +if (!isObject(data)) fail("llm_output_invalid", "objet attendu"); +if (Array.isArray(data.missing) && data.missing.length) fail("data_missing", data.missing.filter((x) => typeof x === "string").join(" ; ")); +let title = typeof input.title === "string" && input.title.trim() ? input.title.trim().slice(0, 120) : ""; +const given = input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== ""; +const id = given ? docIdOf(input.doc_id) : slugify(title || (key === "quote" ? "devis " + (isObject(data.customer) ? data.customer.name : "") : (isObject(data.meeting) ? data.meeting.title : key))) + "-" + shortSuffix(); +data = normalizeData(key, data, id); +if (!title) title = key === "quote" ? "Devis " + data.customer.name : data.meeting.title; +title = title.slice(0, 120); +const at = nowIso(); +const rec = {schema: "document-studio.record/v1", doc_id: id, template_key: key, template_version: TEMPLATES[key].manifest.version, title, locale: prep.locale, status: "draft", number: null, revision: 1, data, history: [{at, action: "created", note: "brouillon créé depuis un brief"}], renders: [], issued: null}; +try { await writeJson(recordPath(id), rec, false); } catch (e) { fail("document_create_failed", id + " : " + String(e && e.message)); } +return {...summarize(rec), data, computed: templateData(key, data)}; +''' + +RENDER_CODE = r''' +const input = {{ json . }}; +const id = docIdOf(input.doc_id); +const rec = await loadRecord(id); +if (rec.status === "issued" || rec.status === "cancelled") fail("document_locked", "un document " + (rec.status === "issued" ? "émis" : "annulé") + " ne se rend plus"); +let data = rec.data; +if (input.data_patch !== undefined && input.data_patch !== null) { + if (!isObject(input.data_patch)) fail("data_patch_invalid", "objet attendu"); + data = {...rec.data, ...input.data_patch}; +} +data = normalizeData(rec.template_key, data, id); +const profile = await loadProfile(); +const revision = rec.revision + 1; +const res = await renderDocument(rec, data, profile, "preview", null, "draft", revision); +const dir = ROOT + "/docs/" + id + "/r" + revision; +const file = await storeFile(dir + "/" + safeName(res.file.filename, "document.pdf"), res.file); +const previews = await storePreviews(dir, res); +const at = nowIso(); +if (rec.status === "approved") rec.history.push({at, action: "reopened", note: "nouveau rendu : l'approbation est à renouveler"}); +rec.history.push({at, action: "rendered", note: "r" + revision + ", " + (Number.isInteger(res.pages) ? res.pages : previews.length) + " page(s)"}); +rec.status = "draft"; +rec.data = data; +rec.revision = revision; +rec.renders.push({revision, mode: "preview", file, previews, provenance: res.provenance === undefined ? null : res.provenance}); +await saveRecord(rec); +return summarize(rec); +''' + +FINALIZE_CODE = r''' +const input = {{ json . }}; +requireConfirmation(input); +const id = docIdOf(input.doc_id); +const rec = await loadRecord(id); +if (rec.status !== "draft") fail("status_invalid", "seul un brouillon s'approuve (statut actuel : " + rec.status + ")"); +const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null; +if (!last || last.revision !== rec.revision) fail("render_required", "rendez la révision courante avant de l'approuver"); +rec.status = "approved"; +rec.revision += 1; +rec.history.push({at: nowIso(), action: "approved", note: "rendu r" + last.revision + " approuvé"}); +await saveRecord(rec); +return summarize(rec); +''' + +PUBLISH_CODE = r''' +const input = {{ json . }}; +requireConfirmation(input); +const id = docIdOf(input.doc_id); +const rec = await loadRecord(id); +if (rec.status !== "approved") fail("status_invalid", "seul un document approuvé s'émet (statut actuel : " + rec.status + ")"); +const profile = await loadProfile(); +if (!rec.number) { + rec.number = await reserveNumber(rec); + rec.revision += 1; + rec.history.push({at: nowIso(), action: "number_reserved", note: rec.number}); + await saveRecord(rec); +} +const data = normalizeData(rec.template_key, rec.data, id); +const revision = rec.revision + 1; +const res = await renderDocument(rec, data, profile, "final", rec.number, "issued", revision); +const dir = ROOT + "/docs/" + id; +const file = await storeFile(dir + "/issued/" + rec.number + ".pdf", res.file); +const previews = await storePreviews(dir + "/r" + revision, res); +const at = nowIso(); +rec.status = "issued"; +rec.revision = revision; +rec.renders.push({revision, mode: "final", file, previews, provenance: res.provenance === undefined ? null : res.provenance}); +rec.issued = {number: rec.number, file: {path: file.path, sha256: file.sha256}, at}; +rec.history.push({at, action: "issued", note: rec.number}); +await saveRecord(rec); +return summarize(rec); +''' + +CANCEL_CODE = r''' +const input = {{ json . }}; +requireConfirmation(input); +const id = docIdOf(input.doc_id); +const reason = text(input.reason, "reason", 500, true); +const rec = await loadRecord(id); +if (rec.status === "cancelled") fail("status_invalid", "document déjà annulé"); +rec.status = "cancelled"; +rec.revision += 1; +rec.history.push({at: nowIso(), action: "cancelled", note: reason}); +await saveRecord(rec); +return summarize(rec); +''' + +EXPORT_CODE = r''' +const input = {{ json . }}; +const id = docIdOf(input.doc_id); +const dest = input.destination_path; +if (typeof dest !== "string" || !dest.startsWith("/") || dest.length > 300 || dest.includes("..") || dest.includes("//") || /\s$/.test(dest) || dest.endsWith("/")) fail("destination_invalid", "chemin Storage absolu attendu"); +if (dest === ROOT || dest.startsWith(ROOT + "/")) fail("destination_invalid", "la destination doit être hors de " + ROOT); +const rec = await loadRecord(id); +const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null; +const source = rec.issued ? rec.issued.file : (last ? last.file : null); +if (!source) fail("no_render", "aucun rendu à exporter"); +const encoded = await readText(source.path, {encoding: "base64"}); +const bytes = b64ToBytes(encoded.replace(/\s+/g, "")); +const sha = await sha256Hex(bytes); +if (sha !== source.sha256) fail("export_integrity_failed", "l'empreinte du fichier lu ne correspond pas au rendu"); +await callTool("write_file", {path: dest, content: encoded.replace(/\s+/g, ""), encoding: "base64", overwrite: false}); +return {doc_id: id, destination_path: dest, source_path: source.path, sha256: sha, bytes: bytes.length, draft: !rec.issued, warning: rec.issued ? "" : "document non émis : copie du dernier rendu, marquée brouillon"}; +''' + +PROFILE_SAVE_CODE = r''' +const input = {{ json . }}; +requireConfirmation(input); +const body = normalizeProfile(input.profile); +await callTool("write_file", {path: ROOT + "/profile.json", content: JSON.stringify(body, null, 2) + "\n", overwrite: true}); +return {path: ROOT + "/profile.json", legal_name: body.company.legal_name, colors: body.brand.colors, message: "Charte enregistrée dans Storage."}; +''' + +LIST_CODE = r''' +const input = {{ json . }}; +if (input.status !== undefined && input.status !== null && input.status !== "" && !STATUSES.includes(input.status)) fail("status_invalid", String(input.status)); +const paths = await listPaths(ROOT + "/docs"); +const ids = []; +for (const p of paths) { const m = /document-studio\/docs\/([a-z0-9][a-z0-9-]{0,47})(?:\/|$)/.exec(p); if (m && !ids.includes(m[1])) ids.push(m[1]); } +if (ids.length > 200) fail("too_many_documents", "plus de 200 documents : filtrez ou archivez"); +const items = []; +for (const id of ids.sort()) { + let rec; + try { rec = await loadRecord(id); } catch (e) { continue; } + if (input.status && rec.status !== input.status) continue; + if (input.template_key && rec.template_key !== input.template_key) continue; + const s = summarize(rec); + items.push({doc_id: s.doc_id, title: s.title, template_key: s.template_key, status: s.status, number: s.number, revision: s.revision, sha256: s.issued ? s.issued.file.sha256 : (s.last_render ? s.last_render.sha256 : null)}); +} +return {count: items.length, items}; +''' + +REVIEW_CODE = r''' +const input = {{ json . }}; +const id = docIdOf(input.doc_id); +const rec = await loadRecord(id); +const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null; +const s = summarize(rec); +return {doc_id: id, title: rec.title, template_key: rec.template_key, status: rec.status, number: rec.number === null ? "" : rec.number, revision: rec.revision, pages: last ? last.previews.length : 0, previews: last ? last.previews : [], renders: rec.renders.map((r) => ({revision: r.revision, mode: r.mode, sha256: r.file.sha256, path: r.file.path})), history: rec.history, issued: rec.issued, record: rec}; +''' + +TEMPLATE_READ_CODE = r''' +const input = {{ json . }}; +if (input.template_key === undefined || input.template_key === null || input.template_key === "") { + return {templates: Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, version: TEMPLATES[k].manifest.version, prefix: TEMPLATES[k].prefix, summary: TEMPLATES[k].summary})), template: null}; +} +const tpl = TEMPLATES[input.template_key]; +if (!tpl) fail("template_unknown", String(input.template_key)); +return {templates: [], template: {template_key: input.template_key, title: tpl.title, version: tpl.manifest.version, prefix: tpl.prefix, summary: tpl.summary, manifest: tpl.manifest, input_schema: tpl.input_schema, draft_schema: tpl.draft_schema}}; +''' + + +def build(): + out_summary = dict(SUMMARY_OUT) + workflow('document-studio-plan', 'Plan a document', + 'Chooses the template for a brief, proposes a title and lists the missing data with questions. Writes nothing.', + schema(['brief'], brief=text('Brief of the document'), template_key=TEMPLATE_KEY, locale=LOCALE), + [node('prepare', code(lib(templates='meta'), PLAN_PREPARE), 'prep'), + llm('plan-llm', '{{ prep.prompt }}', SYSTEM, 'plan_draft', 2000), + node('normalize', code(lib(templates='meta'), PLAN_NORMALIZE), 'result')], + {'template_key': '{{ result.template_key }}', 'title': '{{ result.title }}', 'missing': '{{ result.missing }}', + 'questions': '{{ result.questions }}'}, + forms=[form('plan', 'Planifier un document', [ + field('brief', 'Brief', 'text', True), field('template_key', 'Gabarit (facultatif)', 'select', False, options=[ + {'value': 'quote', 'label': 'Devis'}, {'value': 'meeting-minutes', 'label': 'Compte rendu de réunion'}])], + ['prepare', 'plan-llm', 'normalize'])]) + + workflow('document-studio-draft', 'Draft a document', + 'Fills the data of a template from a brief (model call, then strict validation; quote totals are computed ' + 'here from the lines) and creates the record in Storage with status draft. Nothing is rendered yet.', + schema(['brief', 'template_key'], brief=text('Brief of the document'), template_key=TEMPLATE_KEY, + title=text('Document title; derived from the data when absent'), doc_id=DOC_ID, + answers={'type': 'object', 'description': 'Answers to the questions of the plan'}, locale=LOCALE), + [node('prepare', code(lib(templates='meta'), DRAFT_PREPARE), 'prep'), + llm('draft-llm', '{{ prep.prompt }}', SYSTEM, 'draft', 6000), + node('create', code(lib(templates='meta', io=True), DRAFT_CREATE), 'result', tools=STORAGE_TOOLS)], + {**out_summary, 'data': '{{ result.data }}', 'computed': '{{ result.computed }}'}, + forms=[form('draft', 'Rédiger un brouillon', [ + field('brief', 'Brief', 'text', True), + field('template_key', 'Gabarit', 'select', True, options=[ + {'value': 'quote', 'label': 'Devis'}, {'value': 'meeting-minutes', 'label': 'Compte rendu de réunion'}]), + field('title', 'Titre (facultatif)', 'string', False), field('doc_id', 'Identifiant (facultatif)', 'string', False)], + ['prepare', 'draft-llm', 'create'])]) + + workflow('document-studio-render', 'Render a document preview', + 'Renders the current data with the company profile through the artifact tool (mode preview), stores the PDF ' + 'and its page previews in Storage and appends a revision. An issued or cancelled document is locked.', + schema(['doc_id'], doc_id=DOC_ID, data_patch={'type': 'object', 'description': 'Shallow merge into the draft data, then revalidated'}), + [node('render', code(lib(templates='full', io=True, profile=True, render=True), RENDER_CODE), 'result', tools=RENDER_TOOLS)], + out_summary, + forms=[form('render', 'Nouveau rendu', [field('doc_id', 'Identifiant du document', 'string', True)], ['render'])]) + + workflow('document-studio-finalize', 'Approve a document', + 'Moves a rendered draft to approved. Requires a render of the current revision and a manual confirmation.', + schema(['doc_id', 'confirmation_manuelle'], doc_id=DOC_ID, confirmation_manuelle=CONFIRM), + [node('finalize', code(lib(io=True), FINALIZE_CODE), 'result', tools=STORAGE_TOOLS)], + out_summary, + forms=[form('approve', 'Approuver un document', [field('doc_id', 'Identifiant du document', 'string', True), CONFIRM_FIELD], ['finalize'])]) + + workflow('document-studio-publish', 'Issue a document', + 'Reserves the next number of the template for the year, renders the final PDF (mode final) and stores it as the ' + 'issued file. Requires an approved document and a manual confirmation. The reservation is not atomic.', + schema(['doc_id', 'confirmation_manuelle'], doc_id=DOC_ID, confirmation_manuelle=CONFIRM), + [node('publish', code(lib(templates='full', io=True, profile=True, render=True, numbering=True), PUBLISH_CODE), 'result', tools=RENDER_TOOLS)], + out_summary, + forms=[form('issue', 'Émettre un document', [field('doc_id', 'Identifiant du document', 'string', True), CONFIRM_FIELD], ['publish'])]) + + workflow('document-studio-cancel', 'Cancel a document', + 'Marks a document cancelled with a reason. An issued number is never reused.', + schema(['doc_id', 'confirmation_manuelle', 'reason'], doc_id=DOC_ID, confirmation_manuelle=CONFIRM, reason=text('Reason of the cancellation')), + [node('cancel', code(lib(io=True), CANCEL_CODE), 'result', tools=STORAGE_TOOLS)], + out_summary, + forms=[form('cancel', 'Annuler un document', [field('doc_id', 'Identifiant du document', 'string', True), + field('reason', 'Motif', 'text', True), CONFIRM_FIELD], ['cancel'])]) + + workflow('document-studio-export', 'Export a document', + 'Copies the issued PDF (or the last render, flagged as a draft) to a Storage path outside /document-studio/. ' + 'Sending by mail or SFTP is out of scope.', + schema(['doc_id', 'destination_path'], doc_id=DOC_ID, destination_path=text('Absolute Storage path of the copy, outside /document-studio/')), + [node('export', code(lib(io=True), EXPORT_CODE), 'result', tools=STORAGE_TOOLS)], + {'doc_id': '{{ result.doc_id }}', 'destination_path': '{{ result.destination_path }}', 'source_path': '{{ result.source_path }}', + 'sha256': '{{ result.sha256 }}', 'bytes': '{{ result.bytes }}', 'draft': '{{ result.draft }}', 'warning': '{{ result.warning }}'}, + forms=[form('export', 'Exporter un document', [field('doc_id', 'Identifiant du document', 'string', True), + field('destination_path', 'Chemin de destination', 'string', True)], ['export'])]) + + workflow('document-studio-profile-save', 'Save the company profile', + 'Validates the profile (company identity and brand tokens of the template contract) and stores it as ' + '/document-studio/profile.json. Requires a manual confirmation.', + schema(['profile', 'confirmation_manuelle'], profile={'type': 'object', 'description': 'Body {schema_version: 1, company, brand}'}, + confirmation_manuelle=CONFIRM), + [node('save', code(lib(io=True, profile=True), PROFILE_SAVE_CODE), 'result', tools=STORAGE_TOOLS)], + {'path': '{{ result.path }}', 'legal_name': '{{ result.legal_name }}', 'colors': '{{ result.colors }}', 'message': '{{ result.message }}'}) + + workflow('document-studio-list', 'List documents', + 'Lists the documents of the studio: identifier, title, status, number, revision and last fingerprint.', + schema([], status=text('Filter on a status', enum=['draft', 'approved', 'issued', 'cancelled']), template_key=TEMPLATE_KEY), + [node('list', code(lib(io=True), LIST_CODE), 'result', tools=STORAGE_TOOLS)], + {'count': '{{ result.count }}', 'items': '{{ result.items }}'}) + + workflow('document-studio-review-read', 'Read a document for review', + 'Returns the record of a document with the previews of its last render, for the review MiniApp.', + schema(['doc_id'], doc_id=DOC_ID), + [node('read', code(lib(io=True), REVIEW_CODE), 'result', tools=STORAGE_TOOLS)], + {k: '{{ result.%s }}' % k for k in ('doc_id', 'title', 'template_key', 'status', 'number', 'revision', 'pages', 'previews', 'renders', 'history', 'issued', 'record')}, + forms=[form('review', 'Relire un document', [field('doc_id', 'Identifiant du document', 'string', True)], ['read'])]) + + workflow('document-studio-template-read', 'Read the templates', + 'Lists the available templates, or returns the manifest and the data schemas of one of them.', + schema([], template_key=TEMPLATE_KEY), + [node('read', code(lib(templates='meta'), TEMPLATE_READ_CODE), 'result')], + {'templates': '{{ result.templates }}', 'template': '{{ result.template }}'}) + + miniapp() + manifest() + + +def miniapp(): + data = { + '$schema': 'agentmaurice.miniapp/v2', 'schema_version': 2, 'miniapp_id': 'document-studio-review', 'kind': 'miniapp', + 'title': 'Document studio', 'version': '1', + 'description': 'Relire un document, relancer un rendu, l\'approuver puis l\'émettre.', + 'ui': {'renderer': 'component', 'component': 'document-studio-review', 'configuration': {'layout': [ + {'type': 'callout', 'title': 'Relecture humaine', 'tone': 'info', + 'value': 'Chargez un document par son identifiant, relisez les rendus, puis approuvez et émettez avec une confirmation manuelle. ' + 'Un document émis est verrouillé et son numéro n\'est jamais réutilisé.'}, + {'type': 'button', 'label': 'Charger le document', 'on_click': 'load'}, + {'type': 'section', 'title': 'Document', 'children': [ + {'type': 'kpi_grid', 'items': [ + {'label': 'Statut', 'value': {'state': 'review.status'}}, + {'label': 'Révision', 'value': {'state': 'review.revision'}}, + {'label': 'Numéro', 'value': {'state': 'review.number'}}, + {'label': 'Pages', 'value': {'state': 'review.pages'}}]}, + {'type': 'stat', 'label': 'Titre', 'value': {'state': 'review.title'}}, + {'type': 'table', 'columns': ['revision', 'mode', 'sha256', 'path'], + 'column_labels': {'revision': 'Révision', 'mode': 'Mode', 'sha256': 'Empreinte SHA-256', 'path': 'Chemin'}, + 'rows': {'state': 'review.renders'}}]}, + {'type': 'section', 'title': 'Actions', 'children': [ + {'type': 'button', 'label': 'Nouveau rendu', 'on_click': 'render'}, + {'type': 'text', 'value': 'Approuver et Émettre ouvrent un formulaire de confirmation manuelle dans les interactions disponibles.'}, + {'type': 'text', 'value': {'state': 'result.message'}}]}, + ]}}, + 'state_schema': {'type': 'object', 'properties': { + 'doc_id': {'type': 'string'}, 'confirmation_manuelle': {'type': 'string'}, 'review': {'type': 'object'}, 'result': {'type': 'object'}}}, + 'initial_state': {'doc_id': '', 'confirmation_manuelle': 'non', + 'review': {'status': '', 'revision': 0, 'number': '', 'pages': 0, 'title': '', 'renders': []}, + 'result': {'message': 'Aucune action.'}}, + 'events': [ + {'event_id': 'load', 'trigger': 'action.click', 'workflow': {'workflow_id': 'document-studio-review-read', 'input': {'doc_id': '{{ state.doc_id }}'}}, 'result_to_state': 'review'}, + {'event_id': 'review', 'trigger': 'form.submit', 'workflow': {'workflow_id': 'document-studio-review-read', 'input': {'doc_id': '{{ state.doc_id }}'}}, 'result_to_state': 'review'}, + {'event_id': 'render', 'trigger': 'action.click', 'workflow': {'workflow_id': 'document-studio-render', 'input': {'doc_id': '{{ state.doc_id }}'}}, 'result_to_state': 'result'}, + {'event_id': 'approve', 'trigger': 'form.submit', 'workflow': {'workflow_id': 'document-studio-finalize', 'input': {'doc_id': '{{ state.doc_id }}', 'confirmation_manuelle': '{{ state.confirmation_manuelle }}'}}, 'result_to_state': 'result'}, + {'event_id': 'issue', 'trigger': 'form.submit', 'workflow': {'workflow_id': 'document-studio-publish', 'input': {'doc_id': '{{ state.doc_id }}', 'confirmation_manuelle': '{{ state.confirmation_manuelle }}'}}, 'result_to_state': 'result'}], + } + dump(DEST / 'miniapps' / 'document-studio-review.json', data) + + +def manifest(): + def ref(key, name): + return {'key': key, 'name': name, 'workflow_id': key, 'workflow_version': '1'} + data = { + '$schema': 'agentmaurice.module/v2', 'schema_version': 2, 'key': 'document-studio', 'name': 'Document studio', + 'version': VERSION, + 'provides': { + 'actions': [ref('document-studio-plan', 'Plan a document'), ref('document-studio-draft', 'Draft a document'), + ref('document-studio-render', 'Render a document preview'), ref('document-studio-finalize', 'Approve a document'), + ref('document-studio-publish', 'Issue a document'), ref('document-studio-cancel', 'Cancel a document'), + ref('document-studio-export', 'Export a document'), ref('document-studio-profile-save', 'Save the company profile')], + 'queries': [ref('document-studio-list', 'List documents'), ref('document-studio-review-read', 'Read a document for review'), + ref('document-studio-template-read', 'Read the templates')], + 'apps': [{'key': 'document-studio-review', 'name': 'Document studio', 'miniapp_id': 'document-studio-review', + 'miniapp_version': '1'}]}, + 'requires': {}, + } + dump(MODULE / 'module.yaml', data) + + +if __name__ == '__main__': + build() diff --git a/tooling/document-studio/contract/PIN.json b/tooling/document-studio/contract/PIN.json new file mode 100644 index 0000000..8d60793 --- /dev/null +++ b/tooling/document-studio/contract/PIN.json @@ -0,0 +1,122 @@ +{ + "contract": "agentmaurice.template/v1", + "source_path": "contracts/template/v1", + "source_commit": "b2133665efeb7ed8b3358d0aafed8914587526d6", + "note": "Frozen copies of the reference templates and their shared fragments. \"sha256\" is the hash of the file in this Module, \"source_sha256\" the hash of the file in the contract at source_commit; a file with \"modified\": true was changed here on purpose. Refresh with a new commit only through a reviewed change.", + "templates": { + "quote": { + "examples/default.json": { + "source": "golden/valid/quote/examples/default.json", + "sha256": "c77832ef47dea2ff02b9cfc7cf04e47b5d3830a8719d99f68fecc6eddde12c04", + "source_sha256": "c77832ef47dea2ff02b9cfc7cf04e47b5d3830a8719d99f68fecc6eddde12c04", + "modified": false + }, + "fragments/footer.typ": { + "source": "fragments/footer.typ", + "sha256": "d2e39519e8be16615ec1cbcaed286336f10a6063f30853d2093d88ae7cbf55e8", + "source_sha256": "d2e39519e8be16615ec1cbcaed286336f10a6063f30853d2093d88ae7cbf55e8", + "modified": false + }, + "fragments/header.typ": { + "source": "fragments/header.typ", + "sha256": "f07498658f437939a053c333eb75a026861bd7901a3542350d89d734d21f1f2f", + "source_sha256": "f07498658f437939a053c333eb75a026861bd7901a3542350d89d734d21f1f2f", + "modified": false + }, + "fragments/legal-mentions.typ": { + "source": "fragments/legal-mentions.typ", + "sha256": "2afa5a85a1cda3df02d2b1300a0379c7be21d7c5f8a7902d8c59ba590b24535b", + "source_sha256": "2afa5a85a1cda3df02d2b1300a0379c7be21d7c5f8a7902d8c59ba590b24535b", + "modified": false + }, + "fragments/lines-table.typ": { + "source": "fragments/lines-table.typ", + "sha256": "bf816c0b8b6e652a4382d6293a2a1186500cd2ca762ae9a15146a85edbdf2a08", + "source_sha256": "bf816c0b8b6e652a4382d6293a2a1186500cd2ca762ae9a15146a85edbdf2a08", + "modified": false + }, + "input.schema.json": { + "source": "golden/valid/quote/input.schema.json", + "sha256": "512325c63e3cd39a6b015bda172c323417d236f0d8b77dd924dc412790623c0d", + "source_sha256": "512325c63e3cd39a6b015bda172c323417d236f0d8b77dd924dc412790623c0d", + "modified": false + }, + "main.typ": { + "source": "golden/valid/quote/main.typ", + "sha256": "dab983866937730fc40e391a0cec5cb525014893404e40eb66de9e8977eb3c8e", + "source_sha256": "78044191b1569c5c6203e2bffcf612260de565e31178ec5c9ff476e26e697ca6", + "modified": true + }, + "manifest.json": { + "source": "golden/valid/quote/manifest.json", + "sha256": "c2bb0c970d4b085c1817f0f6b376fb6200059c71f92410770596eb131f54d1f7", + "source_sha256": "c2bb0c970d4b085c1817f0f6b376fb6200059c71f92410770596eb131f54d1f7", + "modified": false + } + }, + "meeting-minutes": { + "examples/default.json": { + "source": "golden/valid/meeting-minutes/examples/default.json", + "sha256": "01b23415d897ca8af699514df156fd7a6ff324a51e761e4c31e931f473eab172", + "source_sha256": "01b23415d897ca8af699514df156fd7a6ff324a51e761e4c31e931f473eab172", + "modified": false + }, + "examples/minimal.json": { + "source": "golden/valid/meeting-minutes/examples/minimal.json", + "sha256": "3db4b99a6060ed10d470a80505464b61c142ddec80f3331297ae06ff1e9e8eeb", + "source_sha256": "3db4b99a6060ed10d470a80505464b61c142ddec80f3331297ae06ff1e9e8eeb", + "modified": false + }, + "fragments/footer.typ": { + "source": "fragments/footer.typ", + "sha256": "d2e39519e8be16615ec1cbcaed286336f10a6063f30853d2093d88ae7cbf55e8", + "source_sha256": "d2e39519e8be16615ec1cbcaed286336f10a6063f30853d2093d88ae7cbf55e8", + "modified": false + }, + "fragments/header.typ": { + "source": "fragments/header.typ", + "sha256": "f07498658f437939a053c333eb75a026861bd7901a3542350d89d734d21f1f2f", + "source_sha256": "f07498658f437939a053c333eb75a026861bd7901a3542350d89d734d21f1f2f", + "modified": false + }, + "fragments/legal-mentions.typ": { + "source": "fragments/legal-mentions.typ", + "sha256": "2afa5a85a1cda3df02d2b1300a0379c7be21d7c5f8a7902d8c59ba590b24535b", + "source_sha256": "2afa5a85a1cda3df02d2b1300a0379c7be21d7c5f8a7902d8c59ba590b24535b", + "modified": false + }, + "fragments/lines-table.typ": { + "source": "fragments/lines-table.typ", + "sha256": "bf816c0b8b6e652a4382d6293a2a1186500cd2ca762ae9a15146a85edbdf2a08", + "source_sha256": "bf816c0b8b6e652a4382d6293a2a1186500cd2ca762ae9a15146a85edbdf2a08", + "modified": false + }, + "input.schema.json": { + "source": "golden/valid/meeting-minutes/input.schema.json", + "sha256": "7412e969fff179641ca1f909ec290d3a85efa8bbfb21c32fe2c3b317bab61b15", + "source_sha256": "7412e969fff179641ca1f909ec290d3a85efa8bbfb21c32fe2c3b317bab61b15", + "modified": false + }, + "main.typ": { + "source": "golden/valid/meeting-minutes/main.typ", + "sha256": "b2b0bec20b76b557c7a150664fbf531d63275b8ce2ec18843c996665e4431a92", + "source_sha256": "b2b0bec20b76b557c7a150664fbf531d63275b8ce2ec18843c996665e4431a92", + "modified": false + }, + "manifest.json": { + "source": "golden/valid/meeting-minutes/manifest.json", + "sha256": "a7bf1b08964d4cb0569daad0e2da9b117fe7029f3db21fa1c189898449897180", + "source_sha256": "a7bf1b08964d4cb0569daad0e2da9b117fe7029f3db21fa1c189898449897180", + "modified": false + } + } + }, + "shared": { + "i18n.fr.json": { + "source": "golden/context/i18n.fr.json", + "sha256": "1fd7fde8819aef77a9c9c8a95ce38465a9cdd5f1926e32435f38ba3c277a5840", + "source_sha256": "1fd7fde8819aef77a9c9c8a95ce38465a9cdd5f1926e32435f38ba3c277a5840", + "modified": false + } + } +} diff --git a/tooling/document-studio/contract/i18n.fr.json b/tooling/document-studio/contract/i18n.fr.json new file mode 100644 index 0000000..94445e7 --- /dev/null +++ b/tooling/document-studio/contract/i18n.fr.json @@ -0,0 +1,35 @@ +{ + "locale": "fr", + "strings": { + "common_page": "Page", + "common_legal_notice": "Mentions légales", + "common_unsubscribe": "Se désinscrire", + "quote_title": "Devis", + "quote_customer": "Client", + "quote_reference": "Référence", + "quote_valid_until": "Valable jusqu'au", + "quote_col_description": "Désignation", + "quote_col_quantity": "Quantité", + "quote_col_unit_price": "PU HT", + "quote_col_vat": "TVA", + "quote_col_total": "Total HT", + "quote_total_ht": "Total HT", + "quote_total_vat": "Total TVA", + "quote_total_ttc": "Total TTC", + "quote_terms": "Conditions", + "quote_payment": "Règlement", + "minutes_title": "Compte rendu de réunion", + "minutes_meeting": "Réunion", + "minutes_date": "Date", + "minutes_place": "Lieu", + "minutes_participants": "Participants", + "minutes_present": "présent", + "minutes_absent": "excusé", + "minutes_agenda": "Ordre du jour", + "minutes_decisions": "Décisions", + "minutes_actions": "Actions", + "minutes_col_action": "Action", + "minutes_col_owner": "Responsable", + "minutes_col_due": "Échéance" + } +} diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py new file mode 100644 index 0000000..2d51972 --- /dev/null +++ b/tooling/document-studio/tests/test_module.py @@ -0,0 +1,520 @@ +"""Offline checks of the document-studio Module: references, pins, embedded templates, JavaScript steps. + +Every code step is executed under Node with a mocked Storage and a mocked artifact tool, on synthetic data. Nothing +here touches a One, a model or the network, so none of it proves the runtime behaviour: that is a separate replay. +""" +import base64 +import datetime +import hashlib +import importlib.util +import json +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +YEAR = datetime.datetime.now(datetime.timezone.utc).year +MODULE = ROOT / 'document-studio' +TOOLING = ROOT / 'tooling/document-studio' +WORKFLOWS = MODULE / 'agents/main/workflows' +TEMPLATES = MODULE / 'examples/templates' +CONTRACT_CHECK = ROOT.parent.parent / 'pilote-maurice/contracts/template/v1/tools/template_check.py' + + +def load(path): + return json.loads(Path(path).read_text(encoding='utf-8')) + + +spec = importlib.util.spec_from_file_location('document_studio_build', TOOLING / 'build.py') +build = importlib.util.module_from_spec(spec) +spec.loader.exec_module(build) + +HARNESS = r''' +const fs = require("fs"); +const payload = JSON.parse(fs.readFileSync(0, "utf8")); +const {code, ctx, opts} = payload; +const store = payload.fs; +const calls = []; +const sha = (buf) => require("crypto").createHash("sha256").update(buf).digest("hex"); +const b64 = (s) => Buffer.from(s).toString("base64"); +const buffers = {}; +let races = opts.race || 0, hijacks = opts.hijack || 0; +function pdf(label) { const bytes = Buffer.from("%PDF-1.7 fake " + label); return {bytes, sha: sha(bytes)}; } +async function callTool(name, args) { + calls.push({name, args: JSON.parse(JSON.stringify(args, (k, v) => (k === "files" ? "[files]" : v)))}); + if (name === "artifact--artifact_render_v1") { + if (opts.render_error) throw new Error(opts.render_error); + calls[calls.length - 1].full = args; + const f = pdf(args.mode + ":" + args.context.doc.number), p = pdf("png:" + args.mode); + const file = {filename: "document.pdf", mime_type: "application/pdf", bytes: f.bytes.length, sha256: f.sha}; + const prev = {page: 1, filename: "page-1.png", mime_type: "image/png", bytes: p.bytes.length, sha256: p.sha}; + if (opts.render_mode === "ref") { buffers["buf-doc-" + calls.length] = f.bytes.toString("base64"); file.ref = "buf-doc-" + calls.length; buffers["buf-png-" + calls.length] = p.bytes.toString("base64"); prev.ref = "buf-png-" + calls.length; } + else { file.content_base64 = f.bytes.toString("base64"); prev.content_base64 = p.bytes.toString("base64"); } + return {status: "ok", mode: args.mode, output: "pdf", file, pages: 1, previews: [prev], provenance: {engine: "mock"}}; + } + if (name === "read_file") { + const e = store[args.path]; + if (!e) throw new Error("not found: " + args.path); + if (args.encoding === "base64") return {content: e.b64 !== undefined ? e.b64 : b64(e.text)}; + if (e.text === undefined) throw new Error("binary file"); + return {content: e.text}; + } + if (name === "write_file") { + if (args.overwrite === false) { + if (races > 0 && /\/numbers\//.test(args.path)) { races--; store[args.path] = {text: JSON.stringify({doc_id: "other-doc"})}; } + if (store[args.path]) throw new Error("file exists: " + args.path); + } + if (args.buffer_ref) store[args.path] = {b64: buffers[args.buffer_ref]}; + else if (args.encoding === "base64") store[args.path] = {b64: args.content}; + else store[args.path] = {text: args.content}; + if (hijacks > 0 && /\/numbers\//.test(args.path)) { hijacks--; store[args.path] = {text: JSON.stringify({doc_id: "other-doc"})}; } + return {ok: true}; + } + if (name === "list_files") { + const prefix = args.path.replace(/\/$/, "") + "/"; + const paths = Object.keys(store).filter((p) => p.startsWith(prefix)); + if (opts.list_mode === "dirs") return Array.from(new Set(paths.map((p) => prefix + p.slice(prefix.length).split("/")[0]))).map((p) => ({path: p})); + return paths.map((p) => ({path: p})); + } + throw new Error("unexpected tool " + name); +} +const source = code.replace("import { callTool } from './tools/nats_bridge.ts';", "").split("{{ json . }}").join(JSON.stringify(ctx)); +const main = new Function("callTool", "return (async () => {" + source + "})();"); +main(callTool).then((result) => console.log(JSON.stringify({result, fs: store, calls}))) + .catch((error) => console.log(JSON.stringify({error: String(error.message), fs: store, calls}))); +''' + + +def run_node(workflow, node_id, ctx, fs=None, **opts): + wf = load(WORKFLOWS / f'{workflow}.json') + action = next(a for a in wf['actions'] if a['id'] == node_id) + payload = json.dumps({'code': action['code'], 'ctx': ctx, 'fs': fs or {}, 'opts': opts}) + with tempfile.TemporaryDirectory() as tmp: + harness = Path(tmp) / 'harness.js' + harness.write_text(HARNESS, encoding='utf-8') + proc = subprocess.run(['node', str(harness)], input=payload, capture_output=True, text=True) + if proc.returncode != 0: + raise AssertionError(proc.stderr) + return json.loads(proc.stdout) + + +def ok(case, out): + case.assertNotIn('error', out, out.get('error')) + return out['result'] + + +def text_file(content): + return {'text': content} + + +PROFILE = { + 'schema_version': 1, + 'company': {'legal_name': 'Atelier Exemple SAS', 'trade_name': 'Atelier Exemple', 'siret': '000 000 000 00000', + 'address': {'line1': '1 rue de l\'Exemple', 'postal_code': '00000', 'city': 'Exemple-sur-Seine', 'country': 'France'}, + 'email': 'contact@atelier-exemple.invalid', 'legal_mentions': 'Societe fictive.'}, + 'brand': {'colors': {'primary': '#1F3A5F', 'secondary': '#4F6D8F', 'accent': '#E07A1F', 'text': '#1B1B1F', 'muted': '#6B7280', 'background': '#F5F7FA'}, + 'fonts': {'heading': {'family': 'Libertinus Serif'}, 'body': {'family': 'Libertinus Serif'}, 'mono': {'family': 'DejaVu Sans Mono'}}, + 'logo': {'ref': 'storage:///logos/exemple.svg', 'alt': 'Logo Atelier Exemple'}, + 'page': {'size': 'A4', 'margins_mm': {'top': 22, 'right': 20, 'bottom': 22, 'left': 20}}}, +} +QUOTE_DRAFT = { + 'customer': {'name': 'Cabinet Fictif & Associes', 'address_lines': ['12 avenue de l\'Echantillon'], 'contact': 'contact@fictif.invalid'}, + 'lines': [{'description': 'Atelier de cadrage', 'quantity': 2, 'unit': 'forfaits', 'unit_price_ht': 600, 'vat_rate': 20}, + {'description': 'Developpement du prototype', 'quantity': 5, 'unit': 'jours', 'unit_price_ht': 700, 'vat_rate': 20}, + {'description': 'Formation', 'quantity': 1, 'unit': 'jour', 'unit_price_ht': 650.5, 'vat_rate': 5.5}], + 'valid_until': '2026-12-06', 'terms': ['Acompte de 30 %.'], 'payment_terms': '30 jours.', +} +MINUTES_DRAFT = load(TEMPLATES / 'meeting-minutes/examples/default.json') + + +def seeded(profile=True): + return {'/document-studio/profile.json': text_file(json.dumps(PROFILE))} if profile else {} + + +def create_quote(case, fs, **extra): + ctx = {'prep': {'template_key': 'quote', 'locale': 'fr'}, 'draft': QUOTE_DRAFT, 'doc_id': 'devis-test', **extra} + out = run_node('document-studio-draft', 'create', ctx, fs) + return ok(case, out), out['fs'] + + +class ResourcesTest(unittest.TestCase): + def setUp(self): + self.workflows = {p.stem: load(p) for p in WORKFLOWS.glob('*.json')} + + def test_manifest_lists_every_resource(self): + manifest = load(MODULE / 'module.yaml') + refs = {r['workflow_id'] for kind in ('actions', 'queries') for r in manifest['provides'][kind]} + self.assertEqual(refs, set(self.workflows)) + self.assertEqual(len(refs), 11) + apps = {r['miniapp_id'] for r in manifest['provides']['apps']} + self.assertEqual(apps, {p.stem for p in (MODULE / 'agents/main/miniapps').glob('*.json')}) + self.assertEqual((manifest['key'], manifest['schema_version']), ('document-studio', 2)) + + def test_input_schemas_are_closed(self): + for name, wf in self.workflows.items(): + self.assertEqual(wf['input_schema']['type'], 'object', name) + self.assertIs(wf['input_schema']['additionalProperties'], False, name) + for form in wf.get('forms', []): + for field in form['fields']: + self.assertIn(field['name'], wf['input_schema']['properties'], f'{name}: {field["name"]}') + + def test_code_has_no_template_action_and_declares_its_tools(self): + for name, wf in self.workflows.items(): + for action in wf['actions']: + if action['type'] != 'code_execution': + continue + source = action['code'] + self.assertNotIn('{{', source.replace('{{ json . }}', ''), f'{name}/{action["id"]}') + used = set(re.findall(r'callTool\("([^"]+)"', source)) + declared = set(action.get('context', {}).get('allowed_tools', [])) + self.assertLessEqual(used, declared, f'{name}/{action["id"]}') + self.assertEqual('callTool' in source.replace("import { callTool }", ''), bool(used), name) + + def test_publish_and_finalize_and_cancel_demand_a_manual_confirmation(self): + for name in ('document-studio-finalize', 'document-studio-publish', 'document-studio-cancel', 'document-studio-profile-save'): + self.assertIn('confirmation_manuelle', self.workflows[name]['input_schema']['required'], name) + for name, extra in (('document-studio-finalize', {}), ('document-studio-publish', {}), ('document-studio-cancel', {'reason': 'test'})): + node = self.workflows[name]['actions'][0]['id'] + for value in ('non', False, '', None, 'false'): + out = run_node(name, node, {'doc_id': 'devis-test', 'confirmation_manuelle': value, **extra}, {}) + self.assertTrue(out['error'].startswith('manual_confirmation_required'), (name, value, out)) + self.assertEqual(out['calls'], [], 'nothing may be read or written before the confirmation') + out = run_node('document-studio-profile-save', 'save', {'profile': PROFILE, 'confirmation_manuelle': 'non'}, {}) + self.assertTrue(out['error'].startswith('manual_confirmation_required')) + + def test_no_llm_step_writes_and_llm_steps_are_json(self): + for name, wf in self.workflows.items(): + for action in wf['actions']: + if action['type'] == 'llm_call': + self.assertEqual(action['llm_response_format'], 'json', name) + for name in ('document-studio-plan',): + self.assertFalse(any('write_file' in json.dumps(a) for a in self.workflows[name]['actions'])) + + def test_miniapp_events_point_at_existing_workflows(self): + app = load(MODULE / 'agents/main/miniapps/document-studio-review.json') + for event in app['events']: + self.assertIn(event['workflow']['workflow_id'], self.workflows) + props = self.workflows[event['workflow']['workflow_id']]['input_schema']['properties'] + self.assertLessEqual(set(event['workflow']['input']), set(props)) + + def test_generator_reproduces_the_published_files(self): + files = [p for p in MODULE.rglob('*') if p.is_file() and 'examples' not in p.relative_to(MODULE).parts[:1] and p.name != 'README.md'] + before = {p: p.read_bytes() for p in files} + build.build() + after = {p: p.read_bytes() for p in MODULE.rglob('*') if p.is_file() and p in before} + self.assertEqual(before, after) + self.assertEqual({p for p in MODULE.rglob('*') if p.is_file() and p.suffix == '.json' and 'examples' not in p.relative_to(MODULE).parts[:1]} - set(before), set()) + + +class TemplatesTest(unittest.TestCase): + def test_pin_matches_the_local_files(self): + pin = load(TOOLING / 'contract/PIN.json') + self.assertRegex(pin['source_commit'], r'^[0-9a-f]{40}$') + self.assertEqual(sorted(pin['templates']), ['meeting-minutes', 'quote']) + for key, files in pin['templates'].items(): + local = {p.relative_to(TEMPLATES / key).as_posix() for p in (TEMPLATES / key).rglob('*') if p.is_file()} + self.assertEqual(local, set(files), key) + for rel, entry in files.items(): + self.assertEqual(hashlib.sha256((TEMPLATES / key / rel).read_bytes()).hexdigest(), entry['sha256'], f'{key}/{rel}') + self.assertEqual(entry['modified'], entry['sha256'] != entry['source_sha256'], f'{key}/{rel}') + modified = sorted(f'{k}/{r}' for k, files in pin['templates'].items() for r, e in files.items() if e['modified']) + self.assertEqual(modified, ['quote/main.typ']) + shared = pin['shared']['i18n.fr.json'] + self.assertEqual(hashlib.sha256((TOOLING / 'contract/i18n.fr.json').read_bytes()).hexdigest(), shared['sha256']) + + def test_quote_states_it_is_not_an_invoice(self): + self.assertIn("ce n'est pas une facture", (TEMPLATES / 'quote/main.typ').read_text(encoding='utf-8')) + + @unittest.skipUnless(CONTRACT_CHECK.exists(), 'the contract checkout is not next to this repository') + def test_contract_checker_accepts_both_templates(self): + for key in ('quote', 'meeting-minutes'): + proc = subprocess.run(['python3', str(CONTRACT_CHECK), 'check', str(TEMPLATES / key)], capture_output=True, text=True) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + + def test_example_data_matches_the_input_schema(self): + for key in ('quote', 'meeting-minutes'): + manifest = load(TEMPLATES / key / 'manifest.json') + self.assertEqual(manifest['source']['engine'], 'typst') + for example in manifest['examples']: + self.assertTrue((TEMPLATES / key / example['data']).exists()) + + def test_render_receives_the_embedded_templates_unchanged(self): + fs = seeded() + quote, fs = create_quote(self, fs) + out = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs) + ok(self, out) + call = next(c for c in out['calls'] if c['name'] == 'artifact--artifact_render_v1')['full'] + directory = TEMPLATES / 'quote' + self.assertEqual(call['template']['files'], {p.relative_to(directory).as_posix(): p.read_text(encoding='utf-8') for p in sorted(directory.rglob('*')) if p.is_file()}) + self.assertEqual(call['template']['manifest'], load(directory / 'manifest.json')) + self.assertEqual(call['context']['i18n'], load(TOOLING / 'contract/i18n.fr.json')) + self.assertEqual((call['output'], call['mode']), ('pdf', 'preview')) + self.assertEqual(call['context']['doc']['number'], 'BROUILLON') + self.assertEqual(call['context']['company']['trade_name'], 'Atelier Exemple') + self.assertEqual(call['context']['company']['phone'], '') + + +class DraftTest(unittest.TestCase): + def test_quote_totals_are_computed_from_the_lines_and_never_from_the_model(self): + draft = {**QUOTE_DRAFT, 'totals': {'total_ht': '1,00 €', 'total_ttc': '1,00 €'}, 'amount': 5} + summary, _ = create_quote(self, seeded(), draft=draft) + computed = summary['computed'] + self.assertEqual(computed['lines'][0], {'description': 'Atelier de cadrage', 'quantity': '2 forfaits', 'unit_price_ht': '600,00 €', 'vat_rate': '20 %', 'total_ht': '1 200,00 €'}) + self.assertEqual(computed['lines'][2]['unit_price_ht'], '650,50 €') + self.assertEqual(computed['lines'][2]['vat_rate'], '5,5 %') + # 1200 + 3500 + 650.50 = 5350.50 ; VAT 20 % on 4700 = 940.00 ; VAT 5.5 % on 650.50 = 35.78 (35.7775) + self.assertEqual(computed['totals'], {'total_ht': '5 350,50 €', 'vat': [{'rate': '5,5 %', 'amount': '35,78 €'}, {'rate': '20 %', 'amount': '940,00 €'}], 'total_ttc': '6 326,28 €'}) + self.assertEqual(computed['reference'], 'DEVIS-TEST') + self.assertEqual(summary['status'], 'draft') + self.assertEqual((summary['revision'], summary['renders']), (1, 0)) + + def test_the_stored_record_is_complete_and_created_without_overwrite(self): + summary, fs = create_quote(self, seeded()) + record = json.loads(fs['/document-studio/docs/devis-test/record.json']['text']) + self.assertEqual(record['schema'], 'document-studio.record/v1') + self.assertEqual((record['status'], record['number'], record['revision'], record['issued']), ('draft', None, 1, None)) + self.assertEqual(record['template_version'], '1.0.0') + self.assertEqual(record['title'], 'Devis Cabinet Fictif & Associes') + self.assertEqual(record['history'][0]['action'], 'created') + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'quote', 'locale': 'fr'}, 'draft': QUOTE_DRAFT, 'doc_id': 'devis-test'}, fs) + self.assertTrue(out['error'].startswith('document_create_failed')) + create = [c for c in out['calls'] if c['name'] == 'write_file'][0] + self.assertIs(create['args']['overwrite'], False) + + def test_invalid_drafts_are_refused_before_any_write(self): + cases = { + 'negative price': {**QUOTE_DRAFT, 'lines': [{**QUOTE_DRAFT['lines'][0], 'unit_price_ht': -1}]}, + 'zero quantity': {**QUOTE_DRAFT, 'lines': [{**QUOTE_DRAFT['lines'][0], 'quantity': 0}]}, + 'impossible date': {**QUOTE_DRAFT, 'valid_until': '2026-02-30'}, + 'no line': {**QUOTE_DRAFT, 'lines': []}, + 'text price': {**QUOTE_DRAFT, 'lines': [{**QUOTE_DRAFT['lines'][0], 'unit_price_ht': '600,00 €'}]}, + 'no customer': {k: v for k, v in QUOTE_DRAFT.items() if k != 'customer'}, + } + for label, draft in cases.items(): + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'quote', 'locale': 'fr'}, 'draft': draft, 'doc_id': 'devis-test'}, {}) + self.assertTrue(out['error'].startswith('data_invalid'), (label, out)) + self.assertEqual(out['calls'], [], label) + + def test_a_model_that_reports_missing_data_stops_the_draft(self): + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'quote', 'locale': 'fr'}, 'draft': {'missing': ['le nom du client']}}, {}) + self.assertTrue(out['error'].startswith('data_missing: le nom du client')) + + def test_draft_accepts_a_json_string_from_the_model_and_derives_the_id(self): + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'quote', 'locale': 'fr'}, 'draft': '```json\n' + json.dumps(QUOTE_DRAFT) + '\n```'}, {}) + summary = ok(self, out) + self.assertRegex(summary['doc_id'], r'^devis-cabinet-fictif-associes-[0-9a-f]{6}$') + + def test_meeting_minutes_draft_and_prepare_steps(self): + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'meeting-minutes', 'locale': 'fr'}, 'draft': MINUTES_DRAFT, 'doc_id': 'cr-test'}, {}) + summary = ok(self, out) + self.assertEqual(summary['template_key'], 'meeting-minutes') + prep = ok(self, run_node('document-studio-draft', 'prepare', {'brief': 'Compte rendu du comite', 'template_key': 'meeting-minutes'})) + self.assertIn('Compte rendu du comite', prep['prompt']) + for bad in ({'brief': '', 'template_key': 'quote'}, {'brief': 'x', 'template_key': 'invoice'}, {'brief': 'x', 'template_key': 'quote', 'doc_id': 'Bad Id'}, {'brief': 'x', 'template_key': 'quote', 'locale': 'en'}): + self.assertIn('error', run_node('document-studio-draft', 'prepare', bad)) + + def test_plan_normalizes_the_model_answer_and_writes_nothing(self): + prep = ok(self, run_node('document-studio-plan', 'prepare', {'brief': 'Un devis pour un client'})) + out = run_node('document-studio-plan', 'normalize', {'prep': prep, 'plan_draft': json.dumps({'template_key': 'quote', 'title': ' Devis client ', 'missing': ['client', 3, ''], 'questions': ['Quel client ?']})}) + plan = ok(self, out) + self.assertEqual((plan['template_key'], plan['title'], plan['missing'], plan['questions']), ('quote', 'Devis client', ['client'], ['Quel client ?'])) + self.assertEqual(out['calls'], []) + bad = run_node('document-studio-plan', 'normalize', {'prep': prep, 'plan_draft': {'template_key': 'invoice'}}) + self.assertTrue(bad['error'].startswith('template_unknown')) + forced = ok(self, run_node('document-studio-plan', 'prepare', {'brief': 'x', 'template_key': 'meeting-minutes'})) + self.assertEqual(forced['template_key'], 'meeting-minutes') + + def test_template_read(self): + listing = ok(self, run_node('document-studio-template-read', 'read', {})) + self.assertEqual({t['template_key'] for t in listing['templates']}, {'quote', 'meeting-minutes'}) + one = ok(self, run_node('document-studio-template-read', 'read', {'template_key': 'quote'})) + self.assertEqual(one['template']['prefix'], 'DEV') + self.assertIn('required', one['template']['input_schema']) + self.assertIn('error', run_node('document-studio-template-read', 'read', {'template_key': 'invoice'})) + + +class LifecycleTest(unittest.TestCase): + def render(self, fs, **opts): + out = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs, **opts) + return ok(self, out), out['fs'] + + def run_lifecycle(self, **opts): + _, fs = create_quote(self, seeded()) + rendered, fs = self.render(fs, **opts) + self.assertEqual((rendered['status'], rendered['revision'], rendered['renders']), ('draft', 2, 1)) + self.assertEqual(rendered['last_render']['path'], '/document-studio/docs/devis-test/r2/document.pdf') + self.assertIn('/document-studio/docs/devis-test/r2/page-1.png', fs) + approved = run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs) + self.assertEqual(ok(self, approved)['status'], 'approved') + published = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': True}, approved['fs'], **opts) + return ok(self, published), published + + def test_full_lifecycle_with_inline_base64(self): + result, out = self.run_lifecycle() + number = f'DEV-{YEAR}-0001' + self.assertEqual((result['status'], result['number']), ('issued', number)) + fs = out['fs'] + record = json.loads(fs['/document-studio/docs/devis-test/record.json']['text']) + pdf = fs[f'/document-studio/docs/devis-test/issued/{number}.pdf']['b64'] + self.assertEqual(record['issued']['file']['sha256'], hashlib.sha256(base64.b64decode(pdf)).hexdigest()) + self.assertEqual(record['issued']['number'], number) + self.assertEqual([r['mode'] for r in record['renders']], ['preview', 'final']) + self.assertEqual(record['revision'], 5) + self.assertEqual([h['action'] for h in record['history']], ['created', 'rendered', 'approved', 'number_reserved', 'issued']) + self.assertEqual(json.loads(fs[f'/document-studio/numbers/quote/{YEAR}/0001.json']['text'])['doc_id'], 'devis-test') + call = [c for c in out['calls'] if c['name'] == 'artifact--artifact_render_v1'][0]['full'] + self.assertEqual((call['mode'], call['context']['doc']['number'], call['context']['doc']['status']), ('final', number, 'issued')) + write = [c for c in out['calls'] if c['name'] == 'write_file' and c['args']['path'].endswith('.pdf')][0]['args'] + self.assertEqual((write['encoding'], write['overwrite']), ('base64', True)) + + def test_lifecycle_stores_by_buffer_reference_when_the_engine_gives_one(self): + result, out = self.run_lifecycle(render_mode='ref') + self.assertEqual(result['status'], 'issued') + writes = [c['args'] for c in out['calls'] if c['name'] == 'write_file' and 'buffer_ref' in c['args']] + self.assertTrue(writes) + for args in writes: + self.assertNotIn('content', args) + record = json.loads(out['fs']['/document-studio/docs/devis-test/record.json']['text']) + pdf = out['fs'][record['issued']['file']['path']]['b64'] + self.assertEqual(record['issued']['file']['sha256'], hashlib.sha256(base64.b64decode(pdf)).hexdigest()) + + def test_issued_and_cancelled_documents_are_locked(self): + _, out = self.run_lifecycle() + locked = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, out['fs']) + self.assertTrue(locked['error'].startswith('document_locked')) + self.assertEqual([c['name'] for c in locked['calls']], ['read_file']) + cancelled = run_node('document-studio-cancel', 'cancel', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'reason': 'erreur de client'}, out['fs']) + record = ok(self, cancelled) + self.assertEqual((record['status'], record['number'] is not None), ('cancelled', True)) + again = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, cancelled['fs']) + self.assertTrue(again['error'].startswith('document_locked')) + twice = run_node('document-studio-cancel', 'cancel', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'reason': 'x'}, cancelled['fs']) + self.assertTrue(twice['error'].startswith('status_invalid')) + self.assertIn('error', run_node('document-studio-cancel', 'cancel', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'reason': ' '}, out['fs'])) + + def test_numbers_continue_and_are_never_reused(self): + _, out = self.run_lifecycle() + fs = out['fs'] + run_node('document-studio-cancel', 'cancel', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'reason': 'x'}, fs) + _, fs = create_quote(self, fs, doc_id='devis-deux') + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-deux'}, fs)['fs'] + fs = run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-deux', 'confirmation_manuelle': 'oui'}, fs)['fs'] + second = ok(self, run_node('document-studio-publish', 'publish', {'doc_id': 'devis-deux', 'confirmation_manuelle': 'oui'}, fs)) + self.assertEqual(second['number'], f'DEV-{YEAR}-0002') + + def test_number_reservation_survives_lost_races_and_gives_up_after_five(self): + def approved_fs(): + _, fs = create_quote(self, seeded()) + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs)['fs'] + return run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['fs'] + raced = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, approved_fs(), race=2) + self.assertEqual(ok(self, raced)['number'], f'DEV-{YEAR}-0003') + hijacked = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, approved_fs(), hijack=1) + self.assertEqual(ok(self, hijacked)['number'], f'DEV-{YEAR}-0002') + lost = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, approved_fs(), race=9) + self.assertTrue(lost['error'].startswith('number_conflict'), lost) + record = json.loads(lost['fs']['/document-studio/docs/devis-test/record.json']['text']) + self.assertEqual((record['status'], record['number']), ('approved', None)) + self.assertFalse([c for c in lost['calls'] if c['name'] == 'artifact--artifact_render_v1']) + + def test_a_reserved_number_is_kept_when_the_render_fails(self): + _, fs = create_quote(self, seeded()) + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs)['fs'] + fs = run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['fs'] + failed = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs, render_error='moteur indisponible') + self.assertIn('moteur indisponible', failed['error']) + record = json.loads(failed['fs']['/document-studio/docs/devis-test/record.json']['text']) + self.assertEqual(record['status'], 'approved') + number = record['number'] + self.assertTrue(number) + retry = ok(self, run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, failed['fs'])) + self.assertEqual(retry['number'], number) + + def test_status_rules(self): + _, fs = create_quote(self, seeded()) + self.assertTrue(run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['error'].startswith('render_required')) + self.assertTrue(run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['error'].startswith('status_invalid')) + self.assertTrue(run_node('document-studio-render', 'render', {'doc_id': 'devis-absent'}, fs)['error'].startswith('document_not_found')) + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs)['fs'] + fs = run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['fs'] + reopened = ok(self, run_node('document-studio-render', 'render', {'doc_id': 'devis-test', 'data_patch': {'payment_terms': '45 jours.'}}, fs)) + self.assertEqual(reopened['status'], 'draft') + + def test_render_patch_is_validated_and_merged(self): + _, fs = create_quote(self, seeded()) + bad = run_node('document-studio-render', 'render', {'doc_id': 'devis-test', 'data_patch': {'valid_until': 'demain'}}, fs) + self.assertTrue(bad['error'].startswith('data_invalid')) + self.assertFalse([c for c in bad['calls'] if c['name'] == 'artifact--artifact_render_v1']) + good = run_node('document-studio-render', 'render', {'doc_id': 'devis-test', 'data_patch': {'valid_until': '2027-01-31'}}, fs) + ok(self, good) + record = json.loads(good['fs']['/document-studio/docs/devis-test/record.json']['text']) + self.assertEqual(record['data']['valid_until'], '2027-01-31') + self.assertEqual(record['data']['customer']['name'], QUOTE_DRAFT['customer']['name']) + self.assertIn('error', run_node('document-studio-render', 'render', {'doc_id': 'devis-test', 'data_patch': 'texte'}, fs)) + + def test_render_needs_the_company_profile(self): + _, fs = create_quote(self, seeded(profile=False)) + out = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs) + self.assertTrue(out['error'].startswith('profile_missing')) + self.assertIn('document-studio-profile-save', out['error']) + + def test_profile_save_validates_and_writes(self): + out = run_node('document-studio-profile-save', 'save', {'profile': PROFILE, 'confirmation_manuelle': 'oui'}, {}) + result = ok(self, out) + self.assertEqual(result['legal_name'], 'Atelier Exemple SAS') + stored = json.loads(out['fs']['/document-studio/profile.json']['text']) + self.assertEqual(stored['company']['legal_name'], 'Atelier Exemple SAS') + bad_colour = json.loads(json.dumps(PROFILE)) + bad_colour['brand']['colors']['primary'] = 'blue' + no_name = json.loads(json.dumps(PROFILE)) + del no_name['company']['legal_name'] + bad_iban = json.loads(json.dumps(PROFILE)) + bad_iban['company']['bank'] = {'iban': 'FR76'} + for label, profile in (('colour', bad_colour), ('name', no_name), ('iban', bad_iban)): + refused = run_node('document-studio-profile-save', 'save', {'profile': profile, 'confirmation_manuelle': 'oui'}, {}) + self.assertIn('error', refused, label) + self.assertNotIn('/document-studio/profile.json', refused['fs'], label) + example = load(MODULE / 'examples/profile.example.json') + self.assertIn('result', run_node('document-studio-profile-save', 'save', {'profile': example, 'confirmation_manuelle': 'oui'}, {})) + + def test_export_copies_the_issued_pdf_outside_the_studio(self): + _, out = self.run_lifecycle() + copied = run_node('document-studio-export', 'export', {'doc_id': 'devis-test', 'destination_path': '/envois/devis.pdf'}, out['fs']) + result = ok(self, copied) + record = json.loads(copied['fs']['/document-studio/docs/devis-test/record.json']['text']) + self.assertEqual((result['sha256'], result['draft']), (record['issued']['file']['sha256'], False)) + self.assertEqual(copied['fs']['/envois/devis.pdf']['b64'], copied['fs'][record['issued']['file']['path']]['b64']) + for bad in ('/document-studio/copie.pdf', 'relatif.pdf', '/envois/../x.pdf', '/envois/'): + self.assertTrue(run_node('document-studio-export', 'export', {'doc_id': 'devis-test', 'destination_path': bad}, out['fs'])['error'].startswith('destination_invalid'), bad) + clash = run_node('document-studio-export', 'export', {'doc_id': 'devis-test', 'destination_path': '/envois/devis.pdf'}, copied['fs']) + self.assertIn('error', clash) + + def test_export_of_a_draft_is_flagged(self): + _, fs = create_quote(self, seeded()) + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs)['fs'] + result = ok(self, run_node('document-studio-export', 'export', {'doc_id': 'devis-test', 'destination_path': '/envois/brouillon.pdf'}, fs)) + self.assertIs(result['draft'], True) + self.assertIn('brouillon', result['warning']) + empty = run_node('document-studio-export', 'export', {'doc_id': 'devis-test', 'destination_path': '/envois/x.pdf'}, create_quote(self, seeded())[1]) + self.assertTrue(empty['error'].startswith('no_render')) + + def test_list_and_review_read(self): + _, fs = create_quote(self, seeded()) + _, fs = create_quote(self, fs, doc_id='devis-deux') + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs)['fs'] + for mode in ('recursive', 'dirs'): + listing = ok(self, run_node('document-studio-list', 'list', {}, fs, list_mode=mode)) + self.assertEqual([i['doc_id'] for i in listing['items']], ['devis-deux', 'devis-test'], mode) + only = ok(self, run_node('document-studio-list', 'list', {'status': 'approved'}, fs)) + self.assertEqual(only['count'], 0) + self.assertIn('error', run_node('document-studio-list', 'list', {'status': 'wip'}, fs)) + review = ok(self, run_node('document-studio-review-read', 'read', {'doc_id': 'devis-test'}, fs)) + self.assertEqual((review['status'], review['revision'], review['pages'], review['number']), ('draft', 2, 1, '')) + self.assertEqual(review['previews'], [{'page': 1, 'path': '/document-studio/docs/devis-test/r2/page-1.png', 'sha256': review['previews'][0]['sha256']}]) + self.assertEqual(review['renders'][0]['mode'], 'preview') + + +if __name__ == '__main__': + unittest.main() From 0b723cd2fef085edad973240f7a968bd773feea9 Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Sat, 7 Nov 2026 09:13:43 +0100 Subject: [PATCH 02/13] fix(document-studio): One replay fixes: bare render tool name, text LLM output, no platform fragments (AGENT-1578) - Registry sidecar tools are published under their bare name: call artifact_render_v1, not artifact--artifact_render_v1. - llm_call json requires a closed llm_response_schema; the schema depends on the template, so the step answers text and the next step parses {text}. - fragments/, brand.typ and values.json are written by the renderer from its pinned contract: they are no longer embedded (reserved_file_name). Co-Authored-By: Claude Opus 5.5 --- catalog.json | 2 +- document-studio/README.md | 2 +- .../workflows/document-studio-cancel.json | 2 +- .../main/workflows/document-studio-draft.json | 9 ++-- .../workflows/document-studio-export.json | 2 +- .../workflows/document-studio-finalize.json | 2 +- .../main/workflows/document-studio-list.json | 2 +- .../main/workflows/document-studio-plan.json | 9 ++-- .../document-studio-profile-save.json | 2 +- .../workflows/document-studio-publish.json | 4 +- .../workflows/document-studio-render.json | 4 +- .../document-studio-review-read.json | 2 +- .../document-studio-template-read.json | 2 +- inventory/modules.json | 48 +++++++++---------- tooling/document-studio/build.py | 22 ++++++--- tooling/document-studio/tests/test_module.py | 29 +++++++---- 16 files changed, 80 insertions(+), 63 deletions(-) diff --git a/catalog.json b/catalog.json index f4f52cf..6fdc2dd 100644 --- a/catalog.json +++ b/catalog.json @@ -647,7 +647,7 @@ "subpath": "document-studio", "manifest": "document-studio/module.yaml", "manifest_sha256": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", - "tree_sha256": "482bcfbdc1e544c43c8f61962fae37359f2464af1168969945e8178131658863", + "tree_sha256": "1245028d05ec772852fd7f627732d84fd386ba0f13520a0eef96509db2a8844e", "description": { "en": "Document studio: draft business documents from a brief, render them to PDF from templates and the company profile, review, approve and issue them with a number, and keep every revision in Storage.", "fr": "Studio de documents : rédiger des documents professionnels depuis un brief, les rendre en PDF avec des gabarits et la fiche entreprise, les relire, les approuver et les émettre avec un numéro, en gardant chaque révision dans Storage." diff --git a/document-studio/README.md b/document-studio/README.md index a6ff4e1..0518a7b 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -6,7 +6,7 @@ fiche entreprise, relecture, approbation, émission avec un numéro. Tout vit dans Storage ; rien n'est envoyé à l'extérieur. Le Module ne contient aucun moteur de rendu. Le rendu passe par le tool MCP -`artifact--artifact_render_v1` (mode `preview` pour les brouillons, `final` pour +`artifact_render_v1` (mode `preview` pour les brouillons, `final` pour l'émission). Les étapes de code sont du JavaScript (`code_execution`) : pas de WASM en V0. Aucun binaire n'est versionné ici (ni PDF ni PNG). diff --git a/document-studio/agents/main/workflows/document-studio-cancel.json b/document-studio/agents/main/workflows/document-studio-cancel.json index 29533b4..e581f78 100644 --- a/document-studio/agents/main/workflows/document-studio-cancel.json +++ b/document-studio/agents/main/workflows/document-studio-cancel.json @@ -84,7 +84,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst reason = text(input.reason, \"reason\", 500, true);\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"status_invalid\", \"document déjà annulé\");\nrec.status = \"cancelled\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"cancelled\", note: reason});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst reason = text(input.reason, \"reason\", 500, true);\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"status_invalid\", \"document déjà annulé\");\nrec.status = \"cancelled\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"cancelled\", note: reason});\nawait saveRecord(rec);\nreturn summarize(rec);\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-draft.json b/document-studio/agents/main/workflows/document-studio-draft.json index 1a8a03e..eeb07ec 100644 --- a/document-studio/agents/main/workflows/document-studio-draft.json +++ b/document-studio/agents/main/workflows/document-studio-draft.json @@ -99,7 +99,7 @@ { "id": "prepare", "type": "code_execution", - "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst brief = text(input.brief, \"brief\", 8000, true);\nconst key = input.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst locale = input.locale || \"fr\";\nif (locale !== \"fr\") fail(\"locale_unsupported\", \"seul fr est disponible en V0\");\nif (input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\") docIdOf(input.doc_id);\nif (input.answers !== undefined && input.answers !== null && !isObject(input.answers)) fail(\"answers_invalid\", \"objet attendu\");\nconst prompt = \"Brief du demandeur :\\n\" + brief + \"\\n\\n\" + (input.answers && Object.keys(input.answers).length ? \"Réponses complémentaires du demandeur :\\n\" + JSON.stringify(input.answers) + \"\\n\\n\" : \"\") + \"Date du jour : \" + today() + \".\\n\\nRemplis les données du document \\\"\" + key + \"\\\" selon ce schéma JSON :\\n\" + JSON.stringify(TEMPLATES[key].draft_schema) + \"\\n\\nRègles : réponds par l'objet de données seul, conforme au schéma. N'invente ni client, ni prix, ni date, ni participant : si une donnée requise manque, réponds uniquement {\\\"missing\\\": [\\\"description de ce qui manque\\\"]}. Ne calcule aucun total ni montant TTC. Dates au format AAAA-MM-JJ. Texte en français.\";\nreturn {prompt, template_key: key, locale};\n", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst brief = text(input.brief, \"brief\", 8000, true);\nconst key = input.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst locale = input.locale || \"fr\";\nif (locale !== \"fr\") fail(\"locale_unsupported\", \"seul fr est disponible en V0\");\nif (input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\") docIdOf(input.doc_id);\nif (input.answers !== undefined && input.answers !== null && !isObject(input.answers)) fail(\"answers_invalid\", \"objet attendu\");\nconst prompt = \"Brief du demandeur :\\n\" + brief + \"\\n\\n\" + (input.answers && Object.keys(input.answers).length ? \"Réponses complémentaires du demandeur :\\n\" + JSON.stringify(input.answers) + \"\\n\\n\" : \"\") + \"Date du jour : \" + today() + \".\\n\\nRemplis les données du document \\\"\" + key + \"\\\" selon ce schéma JSON :\\n\" + JSON.stringify(TEMPLATES[key].draft_schema) + \"\\n\\nRègles : réponds par l'objet de données seul, conforme au schéma. N'invente ni client, ni prix, ni date, ni participant : si une donnée requise manque, réponds uniquement {\\\"missing\\\": [\\\"description de ce qui manque\\\"]}. Ne calcule aucun total ni montant TTC. Dates au format AAAA-MM-JJ. Texte en français.\";\nreturn {prompt, template_key: key, locale};\n", "output_key": "prep" }, { @@ -109,10 +109,7 @@ "llm_system_prompt": "Tu es un assistant de rédaction de documents professionnels. Tu réponds uniquement par un objet JSON, sans texte autour.", "llm_temperature": 0.2, "llm_max_tokens": 6000, - "llm_response_format": "json", - "llm_response_schema": { - "type": "object" - }, + "llm_response_format": "text", "output_key": "draft" }, { @@ -125,7 +122,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst key = prep.template_key;\nlet data = parseJsonValue(input.draft);\nif (!isObject(data)) fail(\"llm_output_invalid\", \"objet attendu\");\nif (Array.isArray(data.missing) && data.missing.length) fail(\"data_missing\", data.missing.filter((x) => typeof x === \"string\").join(\" ; \"));\nlet title = typeof input.title === \"string\" && input.title.trim() ? input.title.trim().slice(0, 120) : \"\";\nconst given = input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\";\nconst id = given ? docIdOf(input.doc_id) : slugify(title || (key === \"quote\" ? \"devis \" + (isObject(data.customer) ? data.customer.name : \"\") : (isObject(data.meeting) ? data.meeting.title : key))) + \"-\" + shortSuffix();\ndata = normalizeData(key, data, id);\nif (!title) title = key === \"quote\" ? \"Devis \" + data.customer.name : data.meeting.title;\ntitle = title.slice(0, 120);\nconst at = nowIso();\nconst rec = {schema: \"document-studio.record/v1\", doc_id: id, template_key: key, template_version: TEMPLATES[key].manifest.version, title, locale: prep.locale, status: \"draft\", number: null, revision: 1, data, history: [{at, action: \"created\", note: \"brouillon créé depuis un brief\"}], renders: [], issued: null};\ntry { await writeJson(recordPath(id), rec, false); } catch (e) { fail(\"document_create_failed\", id + \" : \" + String(e && e.message)); }\nreturn {...summarize(rec), data, computed: templateData(key, data)};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst key = prep.template_key;\nlet data = parseJsonValue(input.draft);\nif (!isObject(data)) fail(\"llm_output_invalid\", \"objet attendu\");\nif (Array.isArray(data.missing) && data.missing.length) fail(\"data_missing\", data.missing.filter((x) => typeof x === \"string\").join(\" ; \"));\nlet title = typeof input.title === \"string\" && input.title.trim() ? input.title.trim().slice(0, 120) : \"\";\nconst given = input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\";\nconst id = given ? docIdOf(input.doc_id) : slugify(title || (key === \"quote\" ? \"devis \" + (isObject(data.customer) ? data.customer.name : \"\") : (isObject(data.meeting) ? data.meeting.title : key))) + \"-\" + shortSuffix();\ndata = normalizeData(key, data, id);\nif (!title) title = key === \"quote\" ? \"Devis \" + data.customer.name : data.meeting.title;\ntitle = title.slice(0, 120);\nconst at = nowIso();\nconst rec = {schema: \"document-studio.record/v1\", doc_id: id, template_key: key, template_version: TEMPLATES[key].manifest.version, title, locale: prep.locale, status: \"draft\", number: null, revision: 1, data, history: [{at, action: \"created\", note: \"brouillon créé depuis un brief\"}], renders: [], issued: null};\ntry { await writeJson(recordPath(id), rec, false); } catch (e) { fail(\"document_create_failed\", id + \" : \" + String(e && e.message)); }\nreturn {...summarize(rec), data, computed: templateData(key, data)};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-export.json b/document-studio/agents/main/workflows/document-studio-export.json index 00d38d5..1ad96f4 100644 --- a/document-studio/agents/main/workflows/document-studio-export.json +++ b/document-studio/agents/main/workflows/document-studio-export.json @@ -59,7 +59,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst dest = input.destination_path;\nif (typeof dest !== \"string\" || !dest.startsWith(\"/\") || dest.length > 300 || dest.includes(\"..\") || dest.includes(\"//\") || /\\s$/.test(dest) || dest.endsWith(\"/\")) fail(\"destination_invalid\", \"chemin Storage absolu attendu\");\nif (dest === ROOT || dest.startsWith(ROOT + \"/\")) fail(\"destination_invalid\", \"la destination doit être hors de \" + ROOT);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst source = rec.issued ? rec.issued.file : (last ? last.file : null);\nif (!source) fail(\"no_render\", \"aucun rendu à exporter\");\nconst encoded = await readText(source.path, {encoding: \"base64\"});\nconst bytes = b64ToBytes(encoded.replace(/\\s+/g, \"\"));\nconst sha = await sha256Hex(bytes);\nif (sha !== source.sha256) fail(\"export_integrity_failed\", \"l'empreinte du fichier lu ne correspond pas au rendu\");\nawait callTool(\"write_file\", {path: dest, content: encoded.replace(/\\s+/g, \"\"), encoding: \"base64\", overwrite: false});\nreturn {doc_id: id, destination_path: dest, source_path: source.path, sha256: sha, bytes: bytes.length, draft: !rec.issued, warning: rec.issued ? \"\" : \"document non émis : copie du dernier rendu, marquée brouillon\"};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst dest = input.destination_path;\nif (typeof dest !== \"string\" || !dest.startsWith(\"/\") || dest.length > 300 || dest.includes(\"..\") || dest.includes(\"//\") || /\\s$/.test(dest) || dest.endsWith(\"/\")) fail(\"destination_invalid\", \"chemin Storage absolu attendu\");\nif (dest === ROOT || dest.startsWith(ROOT + \"/\")) fail(\"destination_invalid\", \"la destination doit être hors de \" + ROOT);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst source = rec.issued ? rec.issued.file : (last ? last.file : null);\nif (!source) fail(\"no_render\", \"aucun rendu à exporter\");\nconst encoded = await readText(source.path, {encoding: \"base64\"});\nconst bytes = b64ToBytes(encoded.replace(/\\s+/g, \"\"));\nconst sha = await sha256Hex(bytes);\nif (sha !== source.sha256) fail(\"export_integrity_failed\", \"l'empreinte du fichier lu ne correspond pas au rendu\");\nawait callTool(\"write_file\", {path: dest, content: encoded.replace(/\\s+/g, \"\"), encoding: \"base64\", overwrite: false});\nreturn {doc_id: id, destination_path: dest, source_path: source.path, sha256: sha, bytes: bytes.length, draft: !rec.issued, warning: rec.issued ? \"\" : \"document non émis : copie du dernier rendu, marquée brouillon\"};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-finalize.json b/document-studio/agents/main/workflows/document-studio-finalize.json index 68247e8..9b514d1 100644 --- a/document-studio/agents/main/workflows/document-studio-finalize.json +++ b/document-studio/agents/main/workflows/document-studio-finalize.json @@ -73,7 +73,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"draft\") fail(\"status_invalid\", \"seul un brouillon s'approuve (statut actuel : \" + rec.status + \")\");\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nif (!last || last.revision !== rec.revision) fail(\"render_required\", \"rendez la révision courante avant de l'approuver\");\nrec.status = \"approved\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"approved\", note: \"rendu r\" + last.revision + \" approuvé\"});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"draft\") fail(\"status_invalid\", \"seul un brouillon s'approuve (statut actuel : \" + rec.status + \")\");\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nif (!last || last.revision !== rec.revision) fail(\"render_required\", \"rendez la révision courante avant de l'approuver\");\nrec.status = \"approved\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"approved\", note: \"rendu r\" + last.revision + \" approuvé\"});\nawait saveRecord(rec);\nreturn summarize(rec);\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-list.json b/document-studio/agents/main/workflows/document-studio-list.json index 1b4c129..d757ef0 100644 --- a/document-studio/agents/main/workflows/document-studio-list.json +++ b/document-studio/agents/main/workflows/document-studio-list.json @@ -42,7 +42,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nif (input.status !== undefined && input.status !== null && input.status !== \"\" && !STATUSES.includes(input.status)) fail(\"status_invalid\", String(input.status));\nconst paths = await listPaths(ROOT + \"/docs\");\nconst ids = [];\nfor (const p of paths) { const m = /document-studio\\/docs\\/([a-z0-9][a-z0-9-]{0,47})(?:\\/|$)/.exec(p); if (m && !ids.includes(m[1])) ids.push(m[1]); }\nif (ids.length > 200) fail(\"too_many_documents\", \"plus de 200 documents : filtrez ou archivez\");\nconst items = [];\nfor (const id of ids.sort()) {\n let rec;\n try { rec = await loadRecord(id); } catch (e) { continue; }\n if (input.status && rec.status !== input.status) continue;\n if (input.template_key && rec.template_key !== input.template_key) continue;\n const s = summarize(rec);\n items.push({doc_id: s.doc_id, title: s.title, template_key: s.template_key, status: s.status, number: s.number, revision: s.revision, sha256: s.issued ? s.issued.file.sha256 : (s.last_render ? s.last_render.sha256 : null)});\n}\nreturn {count: items.length, items};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nif (input.status !== undefined && input.status !== null && input.status !== \"\" && !STATUSES.includes(input.status)) fail(\"status_invalid\", String(input.status));\nconst paths = await listPaths(ROOT + \"/docs\");\nconst ids = [];\nfor (const p of paths) { const m = /document-studio\\/docs\\/([a-z0-9][a-z0-9-]{0,47})(?:\\/|$)/.exec(p); if (m && !ids.includes(m[1])) ids.push(m[1]); }\nif (ids.length > 200) fail(\"too_many_documents\", \"plus de 200 documents : filtrez ou archivez\");\nconst items = [];\nfor (const id of ids.sort()) {\n let rec;\n try { rec = await loadRecord(id); } catch (e) { continue; }\n if (input.status && rec.status !== input.status) continue;\n if (input.template_key && rec.template_key !== input.template_key) continue;\n const s = summarize(rec);\n items.push({doc_id: s.doc_id, title: s.title, template_key: s.template_key, status: s.status, number: s.number, revision: s.revision, sha256: s.issued ? s.issued.file.sha256 : (s.last_render ? s.last_render.sha256 : null)});\n}\nreturn {count: items.length, items};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-plan.json b/document-studio/agents/main/workflows/document-studio-plan.json index 2f63194..2c312a6 100644 --- a/document-studio/agents/main/workflows/document-studio-plan.json +++ b/document-studio/agents/main/workflows/document-studio-plan.json @@ -73,7 +73,7 @@ { "id": "prepare", "type": "code_execution", - "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst brief = text(input.brief, \"brief\", 8000, true);\nlet key = null;\nif (input.template_key !== undefined && input.template_key !== null && input.template_key !== \"\") { key = input.template_key; if (!TEMPLATES[key]) fail(\"template_unknown\", String(key)); }\nconst locale = input.locale || \"fr\";\nif (locale !== \"fr\") fail(\"locale_unsupported\", \"seul fr est disponible en V0\");\nconst catalogue = Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, summary: TEMPLATES[k].summary, data_schema: TEMPLATES[k].draft_schema}));\nconst prompt = \"Brief du demandeur :\\n\" + brief + \"\\n\\n\" + (key ? \"Gabarit imposé : \" + key + \"\\n\\n\" : \"\") + \"Gabarits disponibles (avec le schéma JSON des données attendues) :\\n\" + JSON.stringify(catalogue) + \"\\n\\nChoisis le gabarit adapté, propose un titre court et liste ce qui manque dans le brief pour remplir toutes les données requises du schéma. Ne remplis aucune donnée. Réponds par un objet JSON : {\\\"template_key\\\": string, \\\"title\\\": string, \\\"missing\\\": [string], \\\"questions\\\": [string]}. \\\"missing\\\" nomme les données absentes, \\\"questions\\\" les formule en questions au demandeur, en français.\";\nreturn {prompt, template_key: key, locale};\n", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst brief = text(input.brief, \"brief\", 8000, true);\nlet key = null;\nif (input.template_key !== undefined && input.template_key !== null && input.template_key !== \"\") { key = input.template_key; if (!TEMPLATES[key]) fail(\"template_unknown\", String(key)); }\nconst locale = input.locale || \"fr\";\nif (locale !== \"fr\") fail(\"locale_unsupported\", \"seul fr est disponible en V0\");\nconst catalogue = Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, summary: TEMPLATES[k].summary, data_schema: TEMPLATES[k].draft_schema}));\nconst prompt = \"Brief du demandeur :\\n\" + brief + \"\\n\\n\" + (key ? \"Gabarit imposé : \" + key + \"\\n\\n\" : \"\") + \"Gabarits disponibles (avec le schéma JSON des données attendues) :\\n\" + JSON.stringify(catalogue) + \"\\n\\nChoisis le gabarit adapté, propose un titre court et liste ce qui manque dans le brief pour remplir toutes les données requises du schéma. Ne remplis aucune donnée. Réponds par un objet JSON : {\\\"template_key\\\": string, \\\"title\\\": string, \\\"missing\\\": [string], \\\"questions\\\": [string]}. \\\"missing\\\" nomme les données absentes, \\\"questions\\\" les formule en questions au demandeur, en français.\";\nreturn {prompt, template_key: key, locale};\n", "output_key": "prep" }, { @@ -83,16 +83,13 @@ "llm_system_prompt": "Tu es un assistant de rédaction de documents professionnels. Tu réponds uniquement par un objet JSON, sans texte autour.", "llm_temperature": 0.2, "llm_max_tokens": 2000, - "llm_response_format": "json", - "llm_response_schema": { - "type": "object" - }, + "llm_response_format": "text", "output_key": "plan_draft" }, { "id": "normalize", "type": "code_execution", - "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst out = parseJsonValue(input.plan_draft);\nif (!isObject(out)) fail(\"llm_output_invalid\", \"objet attendu\");\nconst key = prep.template_key || out.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === \"string\" && x.trim()).map((x) => x.trim().slice(0, 300)).slice(0, 20) : []);\nconst title = typeof out.title === \"string\" && out.title.trim() ? out.title.trim().slice(0, 120) : TEMPLATES[key].title;\nreturn {template_key: key, title, locale: prep.locale, missing: list(out.missing), questions: list(out.questions)};\n", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst out = parseJsonValue(input.plan_draft);\nif (!isObject(out)) fail(\"llm_output_invalid\", \"objet attendu\");\nconst key = prep.template_key || out.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === \"string\" && x.trim()).map((x) => x.trim().slice(0, 300)).slice(0, 20) : []);\nconst title = typeof out.title === \"string\" && out.title.trim() ? out.title.trim().slice(0, 120) : TEMPLATES[key].title;\nreturn {template_key: key, title, locale: prep.locale, missing: list(out.missing), questions: list(out.questions)};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-profile-save.json b/document-studio/agents/main/workflows/document-studio-profile-save.json index cd80194..7adf937 100644 --- a/document-studio/agents/main/workflows/document-studio-profile-save.json +++ b/document-studio/agents/main/workflows/document-studio-profile-save.json @@ -38,7 +38,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst body = normalizeProfile(input.profile);\nawait callTool(\"write_file\", {path: ROOT + \"/profile.json\", content: JSON.stringify(body, null, 2) + \"\\n\", overwrite: true});\nreturn {path: ROOT + \"/profile.json\", legal_name: body.company.legal_name, colors: body.brand.colors, message: \"Charte enregistrée dans Storage.\"};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst body = normalizeProfile(input.profile);\nawait callTool(\"write_file\", {path: ROOT + \"/profile.json\", content: JSON.stringify(body, null, 2) + \"\\n\", overwrite: true});\nreturn {path: ROOT + \"/profile.json\", legal_name: body.company.legal_name, colors: body.brand.colors, message: \"Charte enregistrée dans Storage.\"};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-publish.json b/document-studio/agents/main/workflows/document-studio-publish.json index 0783a90..870bfa1 100644 --- a/document-studio/agents/main/workflows/document-studio-publish.json +++ b/document-studio/agents/main/workflows/document-studio-publish.json @@ -71,10 +71,10 @@ "read_file", "write_file", "list_files", - "artifact--artifact_render_v1" + "artifact_render_v1" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"reference\\\\\\\": \\\\\\\"AFF-2026-017\\\\\\\",\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cabinet Fictif & Associés\\\\\\\",\\\\n \\\\\\\"address_lines\\\\\\\": [\\\\\\\"12 avenue de l'Échantillon\\\\\\\", \\\\\\\"00000 Exemple-sur-Seine\\\\\\\"],\\\\n \\\\\\\"contact\\\\\\\": \\\\\\\"Mme Dupont (exemple), contact@fictif.invalid\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Atelier de cadrage (2 demi-journées) #1\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"2 forfaits\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"600,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"1 200,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Développement du prototype_v1 [lot A]\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"5 jours\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"700,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"3 500,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Documentation et formation\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"1 jour\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"5 350,00 €\\\\\\\",\\\\n \\\\\\\"vat\\\\\\\": [\\u007b \\\\\\\"rate\\\\\\\": \\\\\\\"20 %\\\\\\\", \\\\\\\"amount\\\\\\\": \\\\\\\"1 070,00 €\\\\\\\" \\u007d],\\\\n \\\\\\\"total_ttc\\\\\\\": \\\\\\\"6 420,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\\\\\\"2026-12-06\\\\\\\",\\\\n \\\\\\\"terms\\\\\\\": [\\\\n \\\\\\\"Acompte de 30 % à la commande.\\\\\\\",\\\\n \\\\\\\"Livraison sous 6 semaines après acompte.\\\\\\\",\\\\n \\\\\\\"Toute prestation supplémentaire fait l'objet d'un avenant.\\\\\\\"\\\\n ],\\\\n \\\\\\\"payment_terms\\\\\\\": \\\\\\\"30 jours à réception de facture, par virement.\\\\\\\"\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"reference\\\\\\\", \\\\\\\"customer\\\\\\\", \\\\\\\"lines\\\\\\\", \\\\\\\"totals\\\\\\\", \\\\\\\"valid_until\\\\\\\", \\\\\\\"terms\\\\\\\", \\\\\\\"payment_terms\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"reference\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"address_lines\\\\\\\", \\\\\\\"contact\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"address_lines\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"contact\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"quantity\\\\\\\", \\\\\\\"unit_price_ht\\\\\\\", \\\\\\\"vat_rate\\\\\\\", \\\\\\\"total_ht\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"quantity\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"description\\\\\\\": \\\\\\\"Quantite et unite, par exemple `3 jours`.\\\\\\\" \\u007d,\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat_rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"pattern\\\\\\\": \\\\\\\"^[0-9]+([,.][0-9]+)? ?%$\\\\\\\" \\u007d,\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"total_ht\\\\\\\", \\\\\\\"vat\\\\\\\", \\\\\\\"total_ttc\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"rate\\\\\\\", \\\\\\\"amount\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"amount\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"total_ttc\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"payment_terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"money\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montant formate en amont, par exemple `1 250,00 €`.\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/.\\\\n// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .company.siret \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#set par(justify: false)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_title \\u007d\\u007d \\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_reference \\u007d\\u007d \\u007b\\u007b .data.reference \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n#grid(\\\\n columns: (1fr, 1fr),\\\\n gutter: 10mm,\\\\n [\\\\n *\\u007b\\u007b .company.legal_name \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .company.address.line1 \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.address.postal_code \\u007d\\u007d \\u007b\\u007b .company.address.city \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.email \\u007d\\u007d\\\\n ],\\\\n [\\\\n *\\u007b\\u007b .i18n.strings.quote_customer \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .data.customer.name \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- range .data.customer.address_lines \\u007d\\u007d\\\\n \\u007b\\u007b . \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n \\u007b\\u007b .data.customer.contact \\u007d\\u007d\\\\n ],\\\\n)\\\\n\\\\n#v(6mm)\\\\n\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.quote_col_description \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_quantity \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_unit_price \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_vat \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_total \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.lines \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .quantity \\u007d\\u007d], [\\u007b\\u007b .unit_price_ht \\u007d\\u007d], [\\u007b\\u007b .vat_rate \\u007d\\u007d], [\\u007b\\u007b .total_ht \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n)\\\\n\\\\n#v(4mm)\\\\n#align(right, block(width: 60%, table(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n stroke: none,\\\\n inset: (x: 2mm, y: 1.5mm),\\\\n [\\u007b\\u007b .i18n.strings.quote_total_ht \\u007d\\u007d], [\\u007b\\u007b .data.totals.total_ht \\u007d\\u007d],\\\\n\\u007b\\u007b- range .data.totals.vat \\u007d\\u007d\\\\n [\\u007b\\u007b $.i18n.strings.quote_total_vat \\u007d\\u007d \\u007b\\u007b .rate \\u007d\\u007d], [\\u007b\\u007b .amount \\u007d\\u007d],\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n [*\\u007b\\u007b .i18n.strings.quote_total_ttc \\u007d\\u007d*], [*\\u007b\\u007b .data.totals.total_ttc \\u007d\\u007d*],\\\\n)))\\\\n\\\\n#v(4mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_valid_until \\u007d\\u007d* \\u007b\\u007b .data.valid_until \\u007d\\u007d\\\\n\\\\n#v(2mm)\\\\n*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement.\\\\n\\\\n#v(2mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_terms \\u007d\\u007d*\\\\n\\u007b\\u007b range .data.terms \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n*\\u007b\\u007b .i18n.strings.quote_payment \\u007d\\u007d* \\u007b\\u007b .data.payment_terms \\u007d\\u007d\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"quote\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\", \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\" \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\\\\"pdf\\\\\\\"],\\\\n \\\\\\\"locales\\\\\\\": [\\\\\\\"fr\\\\\\\"],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\u007b \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\", \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\" \\u007d],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b \\\\\\\"max_source_bytes\\\\\\\": 20000, \\\\\\\"max_pages\\\\\\\": 4 \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\nconst I18N = JSON.parse(\"\\u007b\\\"locale\\\": \\\"fr\\\", \\\"strings\\\": \\u007b\\\"common_legal_notice\\\": \\\"Mentions légales\\\", \\\"common_page\\\": \\\"Page\\\", \\\"common_unsubscribe\\\": \\\"Se désinscrire\\\", \\\"minutes_absent\\\": \\\"excusé\\\", \\\"minutes_actions\\\": \\\"Actions\\\", \\\"minutes_agenda\\\": \\\"Ordre du jour\\\", \\\"minutes_col_action\\\": \\\"Action\\\", \\\"minutes_col_due\\\": \\\"Échéance\\\", \\\"minutes_col_owner\\\": \\\"Responsable\\\", \\\"minutes_date\\\": \\\"Date\\\", \\\"minutes_decisions\\\": \\\"Décisions\\\", \\\"minutes_meeting\\\": \\\"Réunion\\\", \\\"minutes_participants\\\": \\\"Participants\\\", \\\"minutes_place\\\": \\\"Lieu\\\", \\\"minutes_present\\\": \\\"présent\\\", \\\"minutes_title\\\": \\\"Compte rendu de réunion\\\", \\\"quote_col_description\\\": \\\"Désignation\\\", \\\"quote_col_quantity\\\": \\\"Quantité\\\", \\\"quote_col_total\\\": \\\"Total HT\\\", \\\"quote_col_unit_price\\\": \\\"PU HT\\\", \\\"quote_col_vat\\\": \\\"TVA\\\", \\\"quote_customer\\\": \\\"Client\\\", \\\"quote_payment\\\": \\\"Règlement\\\", \\\"quote_reference\\\": \\\"Référence\\\", \\\"quote_terms\\\": \\\"Conditions\\\", \\\"quote_title\\\": \\\"Devis\\\", \\\"quote_total_ht\\\": \\\"Total HT\\\", \\\"quote_total_ttc\\\": \\\"Total TTC\\\", \\\"quote_total_vat\\\": \\\"Total TVA\\\", \\\"quote_valid_until\\\": \\\"Valable jusqu'au\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nfunction safeName(name, fallback) {\n const base = typeof name === \"string\" ? name.split(\"/\").pop() : \"\";\n return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(\".\") ? base : fallback;\n}\n\nasync function renderDocument(rec, data, profile, mode, number, status, revision) {\n const tpl = TEMPLATES[rec.template_key];\n if (!tpl) fail(\"template_unknown\", rec.template_key);\n const tdata = templateData(rec.template_key, data);\n validateSchema(tpl.input_schema, tdata, \"gabarit \" + rec.template_key);\n const doc = {number: number || \"BROUILLON\", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale};\n const raw = await callTool(\"artifact--artifact_render_v1\", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: \"pdf\", mode});\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"render_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file)) fail(\"render_failed\", \"réponse inattendue du moteur de rendu\");\n return res;\n}\n\n// Stores one rendered file: by buffer reference when the engine gives one, else from base64.\nasync function storeFile(path, f) {\n const args = {path, overwrite: true};\n let sha = typeof f.sha256 === \"string\" ? f.sha256 : \"\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") args.buffer_ref = f.ref;\n else if (typeof f.content_base64 === \"string\") {\n const computed = await sha256Hex(b64ToBytes(f.content_base64));\n if (sha && sha !== computed) fail(\"render_integrity_failed\", path);\n sha = computed;\n args.content = f.content_base64;\n args.encoding = \"base64\";\n } else fail(\"render_output_missing\", path);\n await callTool(\"write_file\", args);\n return {path, sha256: sha, bytes: typeof f.bytes === \"number\" ? f.bytes : null, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n for (const p of Array.isArray(res.previews) ? res.previews : []) {\n const page = Number.isInteger(p.page) ? p.page : previews.length + 1;\n const stored = await storeFile(dir + \"/\" + safeName(p.filename, \"page-\" + page + \".png\"), p);\n previews.push({page, path: stored.path, sha256: stored.sha256});\n }\n return previews;\n}\n\n// Number reservation: lists the year folder, takes max + 1, writes the token without overwrite, reads it back and\n// checks the owner. Not atomic: the check narrows the window, it does not close it.\nasync function reserveNumber(rec) {\n const year = new Date().getUTCFullYear();\n const dir = ROOT + \"/numbers/\" + rec.template_key + \"/\" + year;\n let last = \"\";\n for (let attempt = 0; attempt < 5; attempt++) {\n const paths = await listPaths(dir);\n let max = 0;\n for (const p of paths) { const m = /(?:^|\\/)(\\d{4,})\\.json$/.exec(p); if (m) max = Math.max(max, Number(m[1])); }\n const seq = String(max + 1).padStart(4, \"0\");\n const path = dir + \"/\" + seq + \".json\";\n try { await writeJson(path, {doc_id: rec.doc_id, at: nowIso()}, false); } catch (e) { last = String(e && e.message); continue; }\n let token = null;\n try { token = await readJson(path); } catch (e) { last = String(e && e.message); continue; }\n if (isObject(token) && token.doc_id === rec.doc_id) return TEMPLATES[rec.template_key].prefix + \"-\" + year + \"-\" + seq;\n last = \"numéro \" + seq + \" pris par un autre document\";\n }\n fail(\"number_conflict\", \"5 essais sans numéro libre (\" + last + \")\");\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"approved\") fail(\"status_invalid\", \"seul un document approuvé s'émet (statut actuel : \" + rec.status + \")\");\nconst profile = await loadProfile();\nif (!rec.number) {\n rec.number = await reserveNumber(rec);\n rec.revision += 1;\n rec.history.push({at: nowIso(), action: \"number_reserved\", note: rec.number});\n await saveRecord(rec);\n}\nconst data = normalizeData(rec.template_key, rec.data, id);\nconst revision = rec.revision + 1;\nconst res = await renderDocument(rec, data, profile, \"final\", rec.number, \"issued\", revision);\nconst dir = ROOT + \"/docs/\" + id;\nconst file = await storeFile(dir + \"/issued/\" + rec.number + \".pdf\", res.file);\nconst previews = await storePreviews(dir + \"/r\" + revision, res);\nconst at = nowIso();\nrec.status = \"issued\";\nrec.revision = revision;\nrec.renders.push({revision, mode: \"final\", file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nrec.issued = {number: rec.number, file: {path: file.path, sha256: file.sha256}, at};\nrec.history.push({at, action: \"issued\", note: rec.number});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"reference\\\\\\\": \\\\\\\"AFF-2026-017\\\\\\\",\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cabinet Fictif & Associés\\\\\\\",\\\\n \\\\\\\"address_lines\\\\\\\": [\\\\\\\"12 avenue de l'Échantillon\\\\\\\", \\\\\\\"00000 Exemple-sur-Seine\\\\\\\"],\\\\n \\\\\\\"contact\\\\\\\": \\\\\\\"Mme Dupont (exemple), contact@fictif.invalid\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Atelier de cadrage (2 demi-journées) #1\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"2 forfaits\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"600,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"1 200,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Développement du prototype_v1 [lot A]\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"5 jours\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"700,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"3 500,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Documentation et formation\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"1 jour\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"5 350,00 €\\\\\\\",\\\\n \\\\\\\"vat\\\\\\\": [\\u007b \\\\\\\"rate\\\\\\\": \\\\\\\"20 %\\\\\\\", \\\\\\\"amount\\\\\\\": \\\\\\\"1 070,00 €\\\\\\\" \\u007d],\\\\n \\\\\\\"total_ttc\\\\\\\": \\\\\\\"6 420,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\\\\\\"2026-12-06\\\\\\\",\\\\n \\\\\\\"terms\\\\\\\": [\\\\n \\\\\\\"Acompte de 30 % à la commande.\\\\\\\",\\\\n \\\\\\\"Livraison sous 6 semaines après acompte.\\\\\\\",\\\\n \\\\\\\"Toute prestation supplémentaire fait l'objet d'un avenant.\\\\\\\"\\\\n ],\\\\n \\\\\\\"payment_terms\\\\\\\": \\\\\\\"30 jours à réception de facture, par virement.\\\\\\\"\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"reference\\\\\\\", \\\\\\\"customer\\\\\\\", \\\\\\\"lines\\\\\\\", \\\\\\\"totals\\\\\\\", \\\\\\\"valid_until\\\\\\\", \\\\\\\"terms\\\\\\\", \\\\\\\"payment_terms\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"reference\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"address_lines\\\\\\\", \\\\\\\"contact\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"address_lines\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"contact\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"quantity\\\\\\\", \\\\\\\"unit_price_ht\\\\\\\", \\\\\\\"vat_rate\\\\\\\", \\\\\\\"total_ht\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"quantity\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"description\\\\\\\": \\\\\\\"Quantite et unite, par exemple `3 jours`.\\\\\\\" \\u007d,\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat_rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"pattern\\\\\\\": \\\\\\\"^[0-9]+([,.][0-9]+)? ?%$\\\\\\\" \\u007d,\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"total_ht\\\\\\\", \\\\\\\"vat\\\\\\\", \\\\\\\"total_ttc\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"rate\\\\\\\", \\\\\\\"amount\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"amount\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"total_ttc\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"payment_terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"money\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montant formate en amont, par exemple `1 250,00 €`.\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/.\\\\n// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .company.siret \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#set par(justify: false)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_title \\u007d\\u007d \\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_reference \\u007d\\u007d \\u007b\\u007b .data.reference \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n#grid(\\\\n columns: (1fr, 1fr),\\\\n gutter: 10mm,\\\\n [\\\\n *\\u007b\\u007b .company.legal_name \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .company.address.line1 \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.address.postal_code \\u007d\\u007d \\u007b\\u007b .company.address.city \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.email \\u007d\\u007d\\\\n ],\\\\n [\\\\n *\\u007b\\u007b .i18n.strings.quote_customer \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .data.customer.name \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- range .data.customer.address_lines \\u007d\\u007d\\\\n \\u007b\\u007b . \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n \\u007b\\u007b .data.customer.contact \\u007d\\u007d\\\\n ],\\\\n)\\\\n\\\\n#v(6mm)\\\\n\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.quote_col_description \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_quantity \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_unit_price \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_vat \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_total \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.lines \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .quantity \\u007d\\u007d], [\\u007b\\u007b .unit_price_ht \\u007d\\u007d], [\\u007b\\u007b .vat_rate \\u007d\\u007d], [\\u007b\\u007b .total_ht \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n)\\\\n\\\\n#v(4mm)\\\\n#align(right, block(width: 60%, table(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n stroke: none,\\\\n inset: (x: 2mm, y: 1.5mm),\\\\n [\\u007b\\u007b .i18n.strings.quote_total_ht \\u007d\\u007d], [\\u007b\\u007b .data.totals.total_ht \\u007d\\u007d],\\\\n\\u007b\\u007b- range .data.totals.vat \\u007d\\u007d\\\\n [\\u007b\\u007b $.i18n.strings.quote_total_vat \\u007d\\u007d \\u007b\\u007b .rate \\u007d\\u007d], [\\u007b\\u007b .amount \\u007d\\u007d],\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n [*\\u007b\\u007b .i18n.strings.quote_total_ttc \\u007d\\u007d*], [*\\u007b\\u007b .data.totals.total_ttc \\u007d\\u007d*],\\\\n)))\\\\n\\\\n#v(4mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_valid_until \\u007d\\u007d* \\u007b\\u007b .data.valid_until \\u007d\\u007d\\\\n\\\\n#v(2mm)\\\\n*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement.\\\\n\\\\n#v(2mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_terms \\u007d\\u007d*\\\\n\\u007b\\u007b range .data.terms \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n*\\u007b\\u007b .i18n.strings.quote_payment \\u007d\\u007d* \\u007b\\u007b .data.payment_terms \\u007d\\u007d\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"quote\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\", \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\" \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\\\\"pdf\\\\\\\"],\\\\n \\\\\\\"locales\\\\\\\": [\\\\\\\"fr\\\\\\\"],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\u007b \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\", \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\" \\u007d],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b \\\\\\\"max_source_bytes\\\\\\\": 20000, \\\\\\\"max_pages\\\\\\\": 4 \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\nconst I18N = JSON.parse(\"\\u007b\\\"locale\\\": \\\"fr\\\", \\\"strings\\\": \\u007b\\\"common_legal_notice\\\": \\\"Mentions légales\\\", \\\"common_page\\\": \\\"Page\\\", \\\"common_unsubscribe\\\": \\\"Se désinscrire\\\", \\\"minutes_absent\\\": \\\"excusé\\\", \\\"minutes_actions\\\": \\\"Actions\\\", \\\"minutes_agenda\\\": \\\"Ordre du jour\\\", \\\"minutes_col_action\\\": \\\"Action\\\", \\\"minutes_col_due\\\": \\\"Échéance\\\", \\\"minutes_col_owner\\\": \\\"Responsable\\\", \\\"minutes_date\\\": \\\"Date\\\", \\\"minutes_decisions\\\": \\\"Décisions\\\", \\\"minutes_meeting\\\": \\\"Réunion\\\", \\\"minutes_participants\\\": \\\"Participants\\\", \\\"minutes_place\\\": \\\"Lieu\\\", \\\"minutes_present\\\": \\\"présent\\\", \\\"minutes_title\\\": \\\"Compte rendu de réunion\\\", \\\"quote_col_description\\\": \\\"Désignation\\\", \\\"quote_col_quantity\\\": \\\"Quantité\\\", \\\"quote_col_total\\\": \\\"Total HT\\\", \\\"quote_col_unit_price\\\": \\\"PU HT\\\", \\\"quote_col_vat\\\": \\\"TVA\\\", \\\"quote_customer\\\": \\\"Client\\\", \\\"quote_payment\\\": \\\"Règlement\\\", \\\"quote_reference\\\": \\\"Référence\\\", \\\"quote_terms\\\": \\\"Conditions\\\", \\\"quote_title\\\": \\\"Devis\\\", \\\"quote_total_ht\\\": \\\"Total HT\\\", \\\"quote_total_ttc\\\": \\\"Total TTC\\\", \\\"quote_total_vat\\\": \\\"Total TVA\\\", \\\"quote_valid_until\\\": \\\"Valable jusqu'au\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nfunction safeName(name, fallback) {\n const base = typeof name === \"string\" ? name.split(\"/\").pop() : \"\";\n return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(\".\") ? base : fallback;\n}\n\nasync function renderDocument(rec, data, profile, mode, number, status, revision) {\n const tpl = TEMPLATES[rec.template_key];\n if (!tpl) fail(\"template_unknown\", rec.template_key);\n const tdata = templateData(rec.template_key, data);\n validateSchema(tpl.input_schema, tdata, \"gabarit \" + rec.template_key);\n const doc = {number: number || \"BROUILLON\", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale};\n const raw = await callTool(\"artifact_render_v1\", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: \"pdf\", mode});\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"render_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file)) fail(\"render_failed\", \"réponse inattendue du moteur de rendu\");\n return res;\n}\n\n// Stores one rendered file: by buffer reference when the engine gives one, else from base64.\nasync function storeFile(path, f) {\n const args = {path, overwrite: true};\n let sha = typeof f.sha256 === \"string\" ? f.sha256 : \"\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") args.buffer_ref = f.ref;\n else if (typeof f.content_base64 === \"string\") {\n const computed = await sha256Hex(b64ToBytes(f.content_base64));\n if (sha && sha !== computed) fail(\"render_integrity_failed\", path);\n sha = computed;\n args.content = f.content_base64;\n args.encoding = \"base64\";\n } else fail(\"render_output_missing\", path);\n await callTool(\"write_file\", args);\n return {path, sha256: sha, bytes: typeof f.bytes === \"number\" ? f.bytes : null, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n for (const p of Array.isArray(res.previews) ? res.previews : []) {\n const page = Number.isInteger(p.page) ? p.page : previews.length + 1;\n const stored = await storeFile(dir + \"/\" + safeName(p.filename, \"page-\" + page + \".png\"), p);\n previews.push({page, path: stored.path, sha256: stored.sha256});\n }\n return previews;\n}\n\n// Number reservation: lists the year folder, takes max + 1, writes the token without overwrite, reads it back and\n// checks the owner. Not atomic: the check narrows the window, it does not close it.\nasync function reserveNumber(rec) {\n const year = new Date().getUTCFullYear();\n const dir = ROOT + \"/numbers/\" + rec.template_key + \"/\" + year;\n let last = \"\";\n for (let attempt = 0; attempt < 5; attempt++) {\n const paths = await listPaths(dir);\n let max = 0;\n for (const p of paths) { const m = /(?:^|\\/)(\\d{4,})\\.json$/.exec(p); if (m) max = Math.max(max, Number(m[1])); }\n const seq = String(max + 1).padStart(4, \"0\");\n const path = dir + \"/\" + seq + \".json\";\n try { await writeJson(path, {doc_id: rec.doc_id, at: nowIso()}, false); } catch (e) { last = String(e && e.message); continue; }\n let token = null;\n try { token = await readJson(path); } catch (e) { last = String(e && e.message); continue; }\n if (isObject(token) && token.doc_id === rec.doc_id) return TEMPLATES[rec.template_key].prefix + \"-\" + year + \"-\" + seq;\n last = \"numéro \" + seq + \" pris par un autre document\";\n }\n fail(\"number_conflict\", \"5 essais sans numéro libre (\" + last + \")\");\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"approved\") fail(\"status_invalid\", \"seul un document approuvé s'émet (statut actuel : \" + rec.status + \")\");\nconst profile = await loadProfile();\nif (!rec.number) {\n rec.number = await reserveNumber(rec);\n rec.revision += 1;\n rec.history.push({at: nowIso(), action: \"number_reserved\", note: rec.number});\n await saveRecord(rec);\n}\nconst data = normalizeData(rec.template_key, rec.data, id);\nconst revision = rec.revision + 1;\nconst res = await renderDocument(rec, data, profile, \"final\", rec.number, \"issued\", revision);\nconst dir = ROOT + \"/docs/\" + id;\nconst file = await storeFile(dir + \"/issued/\" + rec.number + \".pdf\", res.file);\nconst previews = await storePreviews(dir + \"/r\" + revision, res);\nconst at = nowIso();\nrec.status = \"issued\";\nrec.revision = revision;\nrec.renders.push({revision, mode: \"final\", file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nrec.issued = {number: rec.number, file: {path: file.path, sha256: file.sha256}, at};\nrec.history.push({at, action: \"issued\", note: rec.number});\nawait saveRecord(rec);\nreturn summarize(rec);\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-render.json b/document-studio/agents/main/workflows/document-studio-render.json index 9699a4b..df3928d 100644 --- a/document-studio/agents/main/workflows/document-studio-render.json +++ b/document-studio/agents/main/workflows/document-studio-render.json @@ -50,10 +50,10 @@ "read_file", "write_file", "list_files", - "artifact--artifact_render_v1" + "artifact_render_v1" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"reference\\\\\\\": \\\\\\\"AFF-2026-017\\\\\\\",\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cabinet Fictif & Associés\\\\\\\",\\\\n \\\\\\\"address_lines\\\\\\\": [\\\\\\\"12 avenue de l'Échantillon\\\\\\\", \\\\\\\"00000 Exemple-sur-Seine\\\\\\\"],\\\\n \\\\\\\"contact\\\\\\\": \\\\\\\"Mme Dupont (exemple), contact@fictif.invalid\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Atelier de cadrage (2 demi-journées) #1\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"2 forfaits\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"600,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"1 200,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Développement du prototype_v1 [lot A]\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"5 jours\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"700,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"3 500,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Documentation et formation\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"1 jour\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"5 350,00 €\\\\\\\",\\\\n \\\\\\\"vat\\\\\\\": [\\u007b \\\\\\\"rate\\\\\\\": \\\\\\\"20 %\\\\\\\", \\\\\\\"amount\\\\\\\": \\\\\\\"1 070,00 €\\\\\\\" \\u007d],\\\\n \\\\\\\"total_ttc\\\\\\\": \\\\\\\"6 420,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\\\\\\"2026-12-06\\\\\\\",\\\\n \\\\\\\"terms\\\\\\\": [\\\\n \\\\\\\"Acompte de 30 % à la commande.\\\\\\\",\\\\n \\\\\\\"Livraison sous 6 semaines après acompte.\\\\\\\",\\\\n \\\\\\\"Toute prestation supplémentaire fait l'objet d'un avenant.\\\\\\\"\\\\n ],\\\\n \\\\\\\"payment_terms\\\\\\\": \\\\\\\"30 jours à réception de facture, par virement.\\\\\\\"\\\\n\\u007d\\\\n\\\", \\\"fragments/footer.typ\\\": \\\"// Fragment partage : pied de page avec pagination. A passer a `set page(footer: ...)`.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-footer(company-line) = \\u007b\\\\n set text(size: 8pt, fill: brand.colors.muted)\\\\n line(length: 100%, stroke: 0.4pt + brand.colors.muted)\\\\n v(1mm)\\\\n grid(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n company-line,\\\\n context [#counter(page).display() / #counter(page).final().first()],\\\\n )\\\\n\\u007d\\\\n\\\", \\\"fragments/header.typ\\\": \\\"// Fragment partage : en-tete de document. Fonction pure, aucune balise Go.\\\\n// Les valeurs arrivent en contenu ([...]) : le moteur les a deja echappees.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let doc-header(company-name, doc-title, doc-number, doc-date) = \\u007b\\\\n grid(\\\\n columns: (1fr, auto),\\\\n gutter: 8mm,\\\\n align: (left + horizon, right + horizon),\\\\n \\u007b\\\\n if brand.logo != none \\u007b\\\\n image(brand.logo, height: 12mm, alt: brand.logo-alt)\\\\n \\u007d else \\u007b\\\\n text(font: brand.fonts.heading, size: 14pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, company-name)\\\\n \\u007d\\\\n \\u007d,\\\\n \\u007b\\\\n text(size: 9pt, fill: brand.colors.muted)[#doc-number \\\\\\\\ #doc-date]\\\\n \\u007d,\\\\n )\\\\n v(2mm)\\\\n line(length: 100%, stroke: 0.8pt + brand.colors.primary)\\\\n v(4mm)\\\\n text(font: brand.fonts.heading, size: 20pt, weight: \\\\\\\"bold\\\\\\\", fill: brand.colors.primary, doc-title)\\\\n v(4mm)\\\\n\\u007d\\\\n\\\", \\\"fragments/legal-mentions.typ\\\": \\\"// Fragment partage : mentions legales. Le texte vient de la fiche entreprise\\\\n// (`company.legal_mentions`), jamais ecrit en dur dans un gabarit.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let legal-mentions(title, body) = \\u007b\\\\n v(6mm)\\\\n block(breakable: false, width: 100%)[\\\\n #set text(size: 8pt, fill: brand.colors.muted)\\\\n #text(weight: \\\\\\\"bold\\\\\\\")[#title] \\\\\\\\\\\\n #body\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"fragments/lines-table.typ\\\": \\\"// Fragment partage : tableau de lignes (devis, facture lisible, commande).\\\\n// `headers` : tableau de contenus. `rows` : tableau de tableaux de contenus.\\\\n// Le fragment affiche ; il ne calcule rien (les montants sont fournis en amont).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand\\\\n\\\\n#let lines-table(headers, rows, widths: auto, right-from: 1) = \\u007b\\\\n let ncols = headers.len()\\\\n let aligns = range(ncols).map(i => if i >= right-from \\u007b right \\u007d else \\u007b left \\u007d)\\\\n table(\\\\n columns: if widths == auto \\u007b (1fr,) + (auto,) * (ncols - 1) \\u007d else \\u007b widths \\u007d,\\\\n align: aligns,\\\\n inset: (x: 3mm, y: 2.2mm),\\\\n stroke: (x: none, y: 0.4pt + brand.colors.muted),\\\\n fill: (_, y) => if y == 0 \\u007b brand.colors.primary \\u007d else \\u007b none \\u007d,\\\\n ..headers.map(h => text(fill: white, weight: \\\\\\\"bold\\\\\\\", h)),\\\\n ..rows.flatten(),\\\\n )\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"reference\\\\\\\", \\\\\\\"customer\\\\\\\", \\\\\\\"lines\\\\\\\", \\\\\\\"totals\\\\\\\", \\\\\\\"valid_until\\\\\\\", \\\\\\\"terms\\\\\\\", \\\\\\\"payment_terms\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"reference\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"address_lines\\\\\\\", \\\\\\\"contact\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"address_lines\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"contact\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"quantity\\\\\\\", \\\\\\\"unit_price_ht\\\\\\\", \\\\\\\"vat_rate\\\\\\\", \\\\\\\"total_ht\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"quantity\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"description\\\\\\\": \\\\\\\"Quantite et unite, par exemple `3 jours`.\\\\\\\" \\u007d,\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat_rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"pattern\\\\\\\": \\\\\\\"^[0-9]+([,.][0-9]+)? ?%$\\\\\\\" \\u007d,\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"total_ht\\\\\\\", \\\\\\\"vat\\\\\\\", \\\\\\\"total_ttc\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"rate\\\\\\\", \\\\\\\"amount\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"amount\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"total_ttc\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"payment_terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"money\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montant formate en amont, par exemple `1 250,00 €`.\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/.\\\\n// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .company.siret \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#set par(justify: false)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_title \\u007d\\u007d \\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_reference \\u007d\\u007d \\u007b\\u007b .data.reference \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n#grid(\\\\n columns: (1fr, 1fr),\\\\n gutter: 10mm,\\\\n [\\\\n *\\u007b\\u007b .company.legal_name \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .company.address.line1 \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.address.postal_code \\u007d\\u007d \\u007b\\u007b .company.address.city \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.email \\u007d\\u007d\\\\n ],\\\\n [\\\\n *\\u007b\\u007b .i18n.strings.quote_customer \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .data.customer.name \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- range .data.customer.address_lines \\u007d\\u007d\\\\n \\u007b\\u007b . \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n \\u007b\\u007b .data.customer.contact \\u007d\\u007d\\\\n ],\\\\n)\\\\n\\\\n#v(6mm)\\\\n\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.quote_col_description \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_quantity \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_unit_price \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_vat \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_total \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.lines \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .quantity \\u007d\\u007d], [\\u007b\\u007b .unit_price_ht \\u007d\\u007d], [\\u007b\\u007b .vat_rate \\u007d\\u007d], [\\u007b\\u007b .total_ht \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n)\\\\n\\\\n#v(4mm)\\\\n#align(right, block(width: 60%, table(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n stroke: none,\\\\n inset: (x: 2mm, y: 1.5mm),\\\\n [\\u007b\\u007b .i18n.strings.quote_total_ht \\u007d\\u007d], [\\u007b\\u007b .data.totals.total_ht \\u007d\\u007d],\\\\n\\u007b\\u007b- range .data.totals.vat \\u007d\\u007d\\\\n [\\u007b\\u007b $.i18n.strings.quote_total_vat \\u007d\\u007d \\u007b\\u007b .rate \\u007d\\u007d], [\\u007b\\u007b .amount \\u007d\\u007d],\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n [*\\u007b\\u007b .i18n.strings.quote_total_ttc \\u007d\\u007d*], [*\\u007b\\u007b .data.totals.total_ttc \\u007d\\u007d*],\\\\n)))\\\\n\\\\n#v(4mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_valid_until \\u007d\\u007d* \\u007b\\u007b .data.valid_until \\u007d\\u007d\\\\n\\\\n#v(2mm)\\\\n*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement.\\\\n\\\\n#v(2mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_terms \\u007d\\u007d*\\\\n\\u007b\\u007b range .data.terms \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n*\\u007b\\u007b .i18n.strings.quote_payment \\u007d\\u007d* \\u007b\\u007b .data.payment_terms \\u007d\\u007d\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"quote\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\", \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\" \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\\\\"pdf\\\\\\\"],\\\\n \\\\\\\"locales\\\\\\\": [\\\\\\\"fr\\\\\\\"],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\u007b \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\", \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\" \\u007d],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b \\\\\\\"max_source_bytes\\\\\\\": 20000, \\\\\\\"max_pages\\\\\\\": 4 \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\nconst I18N = JSON.parse(\"\\u007b\\\"locale\\\": \\\"fr\\\", \\\"strings\\\": \\u007b\\\"common_legal_notice\\\": \\\"Mentions légales\\\", \\\"common_page\\\": \\\"Page\\\", \\\"common_unsubscribe\\\": \\\"Se désinscrire\\\", \\\"minutes_absent\\\": \\\"excusé\\\", \\\"minutes_actions\\\": \\\"Actions\\\", \\\"minutes_agenda\\\": \\\"Ordre du jour\\\", \\\"minutes_col_action\\\": \\\"Action\\\", \\\"minutes_col_due\\\": \\\"Échéance\\\", \\\"minutes_col_owner\\\": \\\"Responsable\\\", \\\"minutes_date\\\": \\\"Date\\\", \\\"minutes_decisions\\\": \\\"Décisions\\\", \\\"minutes_meeting\\\": \\\"Réunion\\\", \\\"minutes_participants\\\": \\\"Participants\\\", \\\"minutes_place\\\": \\\"Lieu\\\", \\\"minutes_present\\\": \\\"présent\\\", \\\"minutes_title\\\": \\\"Compte rendu de réunion\\\", \\\"quote_col_description\\\": \\\"Désignation\\\", \\\"quote_col_quantity\\\": \\\"Quantité\\\", \\\"quote_col_total\\\": \\\"Total HT\\\", \\\"quote_col_unit_price\\\": \\\"PU HT\\\", \\\"quote_col_vat\\\": \\\"TVA\\\", \\\"quote_customer\\\": \\\"Client\\\", \\\"quote_payment\\\": \\\"Règlement\\\", \\\"quote_reference\\\": \\\"Référence\\\", \\\"quote_terms\\\": \\\"Conditions\\\", \\\"quote_title\\\": \\\"Devis\\\", \\\"quote_total_ht\\\": \\\"Total HT\\\", \\\"quote_total_ttc\\\": \\\"Total TTC\\\", \\\"quote_total_vat\\\": \\\"Total TVA\\\", \\\"quote_valid_until\\\": \\\"Valable jusqu'au\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nfunction safeName(name, fallback) {\n const base = typeof name === \"string\" ? name.split(\"/\").pop() : \"\";\n return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(\".\") ? base : fallback;\n}\n\nasync function renderDocument(rec, data, profile, mode, number, status, revision) {\n const tpl = TEMPLATES[rec.template_key];\n if (!tpl) fail(\"template_unknown\", rec.template_key);\n const tdata = templateData(rec.template_key, data);\n validateSchema(tpl.input_schema, tdata, \"gabarit \" + rec.template_key);\n const doc = {number: number || \"BROUILLON\", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale};\n const raw = await callTool(\"artifact--artifact_render_v1\", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: \"pdf\", mode});\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"render_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file)) fail(\"render_failed\", \"réponse inattendue du moteur de rendu\");\n return res;\n}\n\n// Stores one rendered file: by buffer reference when the engine gives one, else from base64.\nasync function storeFile(path, f) {\n const args = {path, overwrite: true};\n let sha = typeof f.sha256 === \"string\" ? f.sha256 : \"\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") args.buffer_ref = f.ref;\n else if (typeof f.content_base64 === \"string\") {\n const computed = await sha256Hex(b64ToBytes(f.content_base64));\n if (sha && sha !== computed) fail(\"render_integrity_failed\", path);\n sha = computed;\n args.content = f.content_base64;\n args.encoding = \"base64\";\n } else fail(\"render_output_missing\", path);\n await callTool(\"write_file\", args);\n return {path, sha256: sha, bytes: typeof f.bytes === \"number\" ? f.bytes : null, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n for (const p of Array.isArray(res.previews) ? res.previews : []) {\n const page = Number.isInteger(p.page) ? p.page : previews.length + 1;\n const stored = await storeFile(dir + \"/\" + safeName(p.filename, \"page-\" + page + \".png\"), p);\n previews.push({page, path: stored.path, sha256: stored.sha256});\n }\n return previews;\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status === \"issued\" || rec.status === \"cancelled\") fail(\"document_locked\", \"un document \" + (rec.status === \"issued\" ? \"émis\" : \"annulé\") + \" ne se rend plus\");\nlet data = rec.data;\nif (input.data_patch !== undefined && input.data_patch !== null) {\n if (!isObject(input.data_patch)) fail(\"data_patch_invalid\", \"objet attendu\");\n data = {...rec.data, ...input.data_patch};\n}\ndata = normalizeData(rec.template_key, data, id);\nconst profile = await loadProfile();\nconst revision = rec.revision + 1;\nconst res = await renderDocument(rec, data, profile, \"preview\", null, \"draft\", revision);\nconst dir = ROOT + \"/docs/\" + id + \"/r\" + revision;\nconst file = await storeFile(dir + \"/\" + safeName(res.file.filename, \"document.pdf\"), res.file);\nconst previews = await storePreviews(dir, res);\nconst at = nowIso();\nif (rec.status === \"approved\") rec.history.push({at, action: \"reopened\", note: \"nouveau rendu : l'approbation est à renouveler\"});\nrec.history.push({at, action: \"rendered\", note: \"r\" + revision + \", \" + (Number.isInteger(res.pages) ? res.pages : previews.length) + \" page(s)\"});\nrec.status = \"draft\";\nrec.data = data;\nrec.revision = revision;\nrec.renders.push({revision, mode: \"preview\", file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"reference\\\\\\\": \\\\\\\"AFF-2026-017\\\\\\\",\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cabinet Fictif & Associés\\\\\\\",\\\\n \\\\\\\"address_lines\\\\\\\": [\\\\\\\"12 avenue de l'Échantillon\\\\\\\", \\\\\\\"00000 Exemple-sur-Seine\\\\\\\"],\\\\n \\\\\\\"contact\\\\\\\": \\\\\\\"Mme Dupont (exemple), contact@fictif.invalid\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Atelier de cadrage (2 demi-journées) #1\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"2 forfaits\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"600,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"1 200,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Développement du prototype_v1 [lot A]\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"5 jours\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"700,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"3 500,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Documentation et formation\\\\\\\",\\\\n \\\\\\\"quantity\\\\\\\": \\\\\\\"1 jour\\\\\\\",\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\",\\\\n \\\\\\\"vat_rate\\\\\\\": \\\\\\\"20 %\\\\\\\",\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"650,00 €\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\\\\\\"5 350,00 €\\\\\\\",\\\\n \\\\\\\"vat\\\\\\\": [\\u007b \\\\\\\"rate\\\\\\\": \\\\\\\"20 %\\\\\\\", \\\\\\\"amount\\\\\\\": \\\\\\\"1 070,00 €\\\\\\\" \\u007d],\\\\n \\\\\\\"total_ttc\\\\\\\": \\\\\\\"6 420,00 €\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\\\\\\"2026-12-06\\\\\\\",\\\\n \\\\\\\"terms\\\\\\\": [\\\\n \\\\\\\"Acompte de 30 % à la commande.\\\\\\\",\\\\n \\\\\\\"Livraison sous 6 semaines après acompte.\\\\\\\",\\\\n \\\\\\\"Toute prestation supplémentaire fait l'objet d'un avenant.\\\\\\\"\\\\n ],\\\\n \\\\\\\"payment_terms\\\\\\\": \\\\\\\"30 jours à réception de facture, par virement.\\\\\\\"\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"reference\\\\\\\", \\\\\\\"customer\\\\\\\", \\\\\\\"lines\\\\\\\", \\\\\\\"totals\\\\\\\", \\\\\\\"valid_until\\\\\\\", \\\\\\\"terms\\\\\\\", \\\\\\\"payment_terms\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"reference\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"customer\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"address_lines\\\\\\\", \\\\\\\"contact\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"address_lines\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"contact\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"lines\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"quantity\\\\\\\", \\\\\\\"unit_price_ht\\\\\\\", \\\\\\\"vat_rate\\\\\\\", \\\\\\\"total_ht\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"quantity\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"description\\\\\\\": \\\\\\\"Quantite et unite, par exemple `3 jours`.\\\\\\\" \\u007d,\\\\n \\\\\\\"unit_price_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat_rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"pattern\\\\\\\": \\\\\\\"^[0-9]+([,.][0-9]+)? ?%$\\\\\\\" \\u007d,\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"totals\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"total_ht\\\\\\\", \\\\\\\"vat\\\\\\\", \\\\\\\"total_ttc\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"total_ht\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d,\\\\n \\\\\\\"vat\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"rate\\\\\\\", \\\\\\\"amount\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"rate\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"amount\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"total_ttc\\\\\\\": \\u007b \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/money\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"valid_until\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"payment_terms\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"money\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Montant formate en amont, par exemple `1 250,00 €`.\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `quote` (devis). Contrat : contracts/template/v1/.\\\\n// Le gabarit affiche ; il ne calcule aucun montant (totaux fournis dans data).\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .company.siret \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#set par(justify: false)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_title \\u007d\\u007d \\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.quote_reference \\u007d\\u007d \\u007b\\u007b .data.reference \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n#grid(\\\\n columns: (1fr, 1fr),\\\\n gutter: 10mm,\\\\n [\\\\n *\\u007b\\u007b .company.legal_name \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .company.address.line1 \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.address.postal_code \\u007d\\u007d \\u007b\\u007b .company.address.city \\u007d\\u007d \\\\\\\\\\\\n \\u007b\\u007b .company.email \\u007d\\u007d\\\\n ],\\\\n [\\\\n *\\u007b\\u007b .i18n.strings.quote_customer \\u007d\\u007d* \\\\\\\\\\\\n \\u007b\\u007b .data.customer.name \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- range .data.customer.address_lines \\u007d\\u007d\\\\n \\u007b\\u007b . \\u007d\\u007d \\\\\\\\\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n \\u007b\\u007b .data.customer.contact \\u007d\\u007d\\\\n ],\\\\n)\\\\n\\\\n#v(6mm)\\\\n\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.quote_col_description \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_quantity \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_unit_price \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_vat \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.quote_col_total \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.lines \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .quantity \\u007d\\u007d], [\\u007b\\u007b .unit_price_ht \\u007d\\u007d], [\\u007b\\u007b .vat_rate \\u007d\\u007d], [\\u007b\\u007b .total_ht \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n)\\\\n\\\\n#v(4mm)\\\\n#align(right, block(width: 60%, table(\\\\n columns: (1fr, auto),\\\\n align: (left, right),\\\\n stroke: none,\\\\n inset: (x: 2mm, y: 1.5mm),\\\\n [\\u007b\\u007b .i18n.strings.quote_total_ht \\u007d\\u007d], [\\u007b\\u007b .data.totals.total_ht \\u007d\\u007d],\\\\n\\u007b\\u007b- range .data.totals.vat \\u007d\\u007d\\\\n [\\u007b\\u007b $.i18n.strings.quote_total_vat \\u007d\\u007d \\u007b\\u007b .rate \\u007d\\u007d], [\\u007b\\u007b .amount \\u007d\\u007d],\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n [*\\u007b\\u007b .i18n.strings.quote_total_ttc \\u007d\\u007d*], [*\\u007b\\u007b .data.totals.total_ttc \\u007d\\u007d*],\\\\n)))\\\\n\\\\n#v(4mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_valid_until \\u007d\\u007d* \\u007b\\u007b .data.valid_until \\u007d\\u007d\\\\n\\\\n#v(2mm)\\\\n*Ce document est un devis, ce n'est pas une facture.* Il n'a pas valeur de facture et ne constitue pas une demande de paiement.\\\\n\\\\n#v(2mm)\\\\n*\\u007b\\u007b .i18n.strings.quote_terms \\u007d\\u007d*\\\\n\\u007b\\u007b range .data.terms \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n*\\u007b\\u007b .i18n.strings.quote_payment \\u007d\\u007d* \\u007b\\u007b .data.payment_terms \\u007d\\u007d\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"quote\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Devis\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\", \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\" \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\\\\"pdf\\\\\\\"],\\\\n \\\\\\\"locales\\\\\\\": [\\\\\\\"fr\\\\\\\"],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\u007b \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\", \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\" \\u007d],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b \\\\\\\"max_source_bytes\\\\\\\": 20000, \\\\\\\"max_pages\\\\\\\": 4 \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\nconst I18N = JSON.parse(\"\\u007b\\\"locale\\\": \\\"fr\\\", \\\"strings\\\": \\u007b\\\"common_legal_notice\\\": \\\"Mentions légales\\\", \\\"common_page\\\": \\\"Page\\\", \\\"common_unsubscribe\\\": \\\"Se désinscrire\\\", \\\"minutes_absent\\\": \\\"excusé\\\", \\\"minutes_actions\\\": \\\"Actions\\\", \\\"minutes_agenda\\\": \\\"Ordre du jour\\\", \\\"minutes_col_action\\\": \\\"Action\\\", \\\"minutes_col_due\\\": \\\"Échéance\\\", \\\"minutes_col_owner\\\": \\\"Responsable\\\", \\\"minutes_date\\\": \\\"Date\\\", \\\"minutes_decisions\\\": \\\"Décisions\\\", \\\"minutes_meeting\\\": \\\"Réunion\\\", \\\"minutes_participants\\\": \\\"Participants\\\", \\\"minutes_place\\\": \\\"Lieu\\\", \\\"minutes_present\\\": \\\"présent\\\", \\\"minutes_title\\\": \\\"Compte rendu de réunion\\\", \\\"quote_col_description\\\": \\\"Désignation\\\", \\\"quote_col_quantity\\\": \\\"Quantité\\\", \\\"quote_col_total\\\": \\\"Total HT\\\", \\\"quote_col_unit_price\\\": \\\"PU HT\\\", \\\"quote_col_vat\\\": \\\"TVA\\\", \\\"quote_customer\\\": \\\"Client\\\", \\\"quote_payment\\\": \\\"Règlement\\\", \\\"quote_reference\\\": \\\"Référence\\\", \\\"quote_terms\\\": \\\"Conditions\\\", \\\"quote_title\\\": \\\"Devis\\\", \\\"quote_total_ht\\\": \\\"Total HT\\\", \\\"quote_total_ttc\\\": \\\"Total TTC\\\", \\\"quote_total_vat\\\": \\\"Total TVA\\\", \\\"quote_valid_until\\\": \\\"Valable jusqu'au\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nfunction onlyKeys(v, allowed, name) { for (const k of Object.keys(v)) if (!allowed.includes(k)) fail(name + \"_unknown_field\", k); }\n\n// Company and brand as expected by the template/v1 contract. A logo is a reference, never an upload.\nfunction normalizeProfile(p) {\n if (!isObject(p) || (p.schema_version !== undefined && p.schema_version !== 1)) fail(\"profile_invalid\", \"schema_version 1 attendu\");\n onlyKeys(p, [\"schema_version\", \"company\", \"brand\"], \"profile\");\n const c = p.company, b = p.brand;\n if (!isObject(c) || !isObject(b)) fail(\"profile_invalid\", \"company et brand sont requis\");\n if (c.logo !== undefined) fail(\"profile_invalid\", \"company.logo est dérivé de brand.logo.ref\");\n onlyKeys(c, [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"], \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const v = text(c[key], key, max, false); if (v) company[key] = v; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const v = text(c.address[part], \"address_\" + part, 200, false); if (v) address[part] = v; }\n if (Object.keys(address).length) company.address = address;\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const key of [\"account_holder\", \"bank_name\"]) { const v = text(c.bank[key], \"bank_\" + key, 200, false); if (v) bank[key] = v; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n const iban = typeof c.bank.iban === \"string\" ? c.bank.iban.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n const bic = typeof c.bank.bic === \"string\" ? c.bank.bic.replace(/\\s+/g, \"\").toUpperCase() : \"\";\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, [\"colors\", \"fonts\", \"logo\", \"page\", \"spacing\"], \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\", \"attendu #RRGGBB\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n const ref = b.logo.ref;\n if (typeof ref !== \"string\" || !ref || ref.length > 500 || /\\s/.test(ref) || ref.includes(\"..\") || ref.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) { const m = b.page.margins_mm[side]; if (typeof m !== \"number\" || !Number.isFinite(m) || m < 0 || m > 100) fail(\"margin_\" + side + \"_invalid\"); margins_mm[side] = m; }\n const brand = {colors, fonts, logo: {ref, alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n if (b.spacing !== undefined) {\n if (!isObject(b.spacing)) fail(\"spacing_invalid\");\n for (const [k, v] of Object.entries(b.spacing)) if (typeof v !== \"number\" || v < 0) fail(\"spacing_invalid\", k);\n brand.spacing = b.spacing;\n }\n return {schema_version: 1, company, brand};\n}\n\n// The templates read these company fields without a guard: an absent value becomes an empty string.\nfunction projectProfile(body) {\n const company = {...body.company};\n if (!company.trade_name) company.trade_name = company.legal_name;\n for (const key of Object.keys(COMPANY_TEXT)) if (company[key] === undefined) company[key] = \"\";\n company.address = {line1: \"\", line2: \"\", postal_code: \"\", city: \"\", country: \"\", ...(company.address || {})};\n company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nfunction safeName(name, fallback) {\n const base = typeof name === \"string\" ? name.split(\"/\").pop() : \"\";\n return /^[A-Za-z0-9._-]{1,100}$/.test(base) && !base.startsWith(\".\") ? base : fallback;\n}\n\nasync function renderDocument(rec, data, profile, mode, number, status, revision) {\n const tpl = TEMPLATES[rec.template_key];\n if (!tpl) fail(\"template_unknown\", rec.template_key);\n const tdata = templateData(rec.template_key, data);\n validateSchema(tpl.input_schema, tdata, \"gabarit \" + rec.template_key);\n const doc = {number: number || \"BROUILLON\", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale};\n const raw = await callTool(\"artifact_render_v1\", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: \"pdf\", mode});\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"render_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file)) fail(\"render_failed\", \"réponse inattendue du moteur de rendu\");\n return res;\n}\n\n// Stores one rendered file: by buffer reference when the engine gives one, else from base64.\nasync function storeFile(path, f) {\n const args = {path, overwrite: true};\n let sha = typeof f.sha256 === \"string\" ? f.sha256 : \"\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") args.buffer_ref = f.ref;\n else if (typeof f.content_base64 === \"string\") {\n const computed = await sha256Hex(b64ToBytes(f.content_base64));\n if (sha && sha !== computed) fail(\"render_integrity_failed\", path);\n sha = computed;\n args.content = f.content_base64;\n args.encoding = \"base64\";\n } else fail(\"render_output_missing\", path);\n await callTool(\"write_file\", args);\n return {path, sha256: sha, bytes: typeof f.bytes === \"number\" ? f.bytes : null, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n for (const p of Array.isArray(res.previews) ? res.previews : []) {\n const page = Number.isInteger(p.page) ? p.page : previews.length + 1;\n const stored = await storeFile(dir + \"/\" + safeName(p.filename, \"page-\" + page + \".png\"), p);\n previews.push({page, path: stored.path, sha256: stored.sha256});\n }\n return previews;\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status === \"issued\" || rec.status === \"cancelled\") fail(\"document_locked\", \"un document \" + (rec.status === \"issued\" ? \"émis\" : \"annulé\") + \" ne se rend plus\");\nlet data = rec.data;\nif (input.data_patch !== undefined && input.data_patch !== null) {\n if (!isObject(input.data_patch)) fail(\"data_patch_invalid\", \"objet attendu\");\n data = {...rec.data, ...input.data_patch};\n}\ndata = normalizeData(rec.template_key, data, id);\nconst profile = await loadProfile();\nconst revision = rec.revision + 1;\nconst res = await renderDocument(rec, data, profile, \"preview\", null, \"draft\", revision);\nconst dir = ROOT + \"/docs/\" + id + \"/r\" + revision;\nconst file = await storeFile(dir + \"/\" + safeName(res.file.filename, \"document.pdf\"), res.file);\nconst previews = await storePreviews(dir, res);\nconst at = nowIso();\nif (rec.status === \"approved\") rec.history.push({at, action: \"reopened\", note: \"nouveau rendu : l'approbation est à renouveler\"});\nrec.history.push({at, action: \"rendered\", note: \"r\" + revision + \", \" + (Number.isInteger(res.pages) ? res.pages : previews.length) + \" page(s)\"});\nrec.status = \"draft\";\nrec.data = data;\nrec.revision = revision;\nrec.renders.push({revision, mode: \"preview\", file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nawait saveRecord(rec);\nreturn summarize(rec);\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-review-read.json b/document-studio/agents/main/workflows/document-studio-review-read.json index 9b81cb8..8835269 100644 --- a/document-studio/agents/main/workflows/document-studio-review-read.json +++ b/document-studio/agents/main/workflows/document-studio-review-read.json @@ -48,7 +48,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst s = summarize(rec);\nreturn {doc_id: id, title: rec.title, template_key: rec.template_key, status: rec.status, number: rec.number === null ? \"\" : rec.number, revision: rec.revision, pages: last ? last.previews.length : 0, previews: last ? last.previews : [], renders: rec.renders.map((r) => ({revision: r.revision, mode: r.mode, sha256: r.file.sha256, path: r.file.path})), history: rec.history, issued: rec.issued, record: rec};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nasync function readText(path, extra) {\n const r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})}));\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) { return JSON.parse(await readText(path)); }\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) { return []; }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) { fail(\"document_not_found\", id); }\n return checkRecord(rec, id);\n}\nasync function saveRecord(rec) { await writeJson(recordPath(rec.doc_id), rec, true); }\nasync function loadProfile() {\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) { stored = null; }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst s = summarize(rec);\nreturn {doc_id: id, title: rec.title, template_key: rec.template_key, status: rec.status, number: rec.number === null ? \"\" : rec.number, revision: rec.revision, pages: last ? last.previews.length : 0, previews: last ? last.previews : [], renders: rec.renders.map((r) => ({revision: r.revision, mode: r.mode, sha256: r.file.sha256, path: r.file.path})), history: rec.history, issued: rec.issued, record: rec};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-template-read.json b/document-studio/agents/main/workflows/document-studio-template-read.json index 44fe8cd..a643992 100644 --- a/document-studio/agents/main/workflows/document-studio-template-read.json +++ b/document-studio/agents/main/workflows/document-studio-template-read.json @@ -25,7 +25,7 @@ { "id": "read", "type": "code_execution", - "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nif (input.template_key === undefined || input.template_key === null || input.template_key === \"\") {\n return {templates: Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, version: TEMPLATES[k].manifest.version, prefix: TEMPLATES[k].prefix, summary: TEMPLATES[k].summary})), template: null};\n}\nconst tpl = TEMPLATES[input.template_key];\nif (!tpl) fail(\"template_unknown\", String(input.template_key));\nreturn {templates: [], template: {template_key: input.template_key, title: tpl.title, version: tpl.manifest.version, prefix: tpl.prefix, summary: tpl.summary, manifest: tpl.manifest, input_schema: tpl.input_schema, draft_schema: tpl.draft_schema}};\n", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"maximum\\\": 100, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 40, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"customer\\\", \\\"lines\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"money\\\": \\u007b\\\"description\\\": \\\"Montant formate en amont, par exemple `1 250,00 €`.\\\", \\\"pattern\\\": \\\"^-?[0-9][0-9 ]*,[0-9]\\u007b2\\u007d (EUR|€)$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Montants fournis en amont sous forme de chaines deja formatees : le gabarit affiche, il ne calcule pas d'argent.\\\", \\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"address_lines\\\", \\\"contact\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"description\\\": \\\"Quantite et unite, par exemple `3 jours`.\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"pattern\\\": \\\"^[0-9]+([,.][0-9]+)? ?%$\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"quantity\\\", \\\"unit_price_ht\\\", \\\"vat_rate\\\", \\\"total_ht\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"payment_terms\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"reference\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"terms\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"totals\\\": \\u007b\\\"properties\\\": \\u007b\\\"total_ht\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"total_ttc\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"vat\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"amount\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/money\\\"\\u007d, \\\"rate\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"rate\\\", \\\"amount\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"total_ht\\\", \\\"vat\\\", \\\"total_ttc\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"valid_until\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"reference\\\", \\\"customer\\\", \\\"lines\\\", \\\"totals\\\", \\\"valid_until\\\", \\\"terms\\\", \\\"payment_terms\\\"], \\\"title\\\": \\\"Donnees metier du devis\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Devis avec lignes, quantités, prix unitaire HT, TVA, totaux fournis en amont, conditions et validité.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"quote\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 4, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Devis\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"DEV\\\", \\\"summary\\\": \\\"Devis : client, lignes (description, quantité, unité, prix unitaire HT, taux de TVA), validité, conditions, règlement. Les montants et les totaux sont calculés, jamais saisis.\\\", \\\"title\\\": \\\"Devis\\\"\\u007d\\u007d\");\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\nfunction today() { return new Date().toISOString().slice(0, 10); }\nfunction nowIso() { return new Date().toISOString(); }\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") return v;\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n try { return JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n const t = schema.type;\n if (t) {\n const ok = t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true;\n if (!ok) { errors.push(path + \" : type \" + t + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined && value[key] !== null) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in props)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const abs = Math.abs(cents);\n const grouped = String(Math.floor(abs / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (cents < 0 ? \"-\" : \"\") + grouped + \",\" + String(abs % 100).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in integer cents, from the lines. They are never taken from the model.\nfunction quoteData(d) {\n const lines = [];\n let ht = 0;\n const groups = new Map();\n for (const l of d.lines) {\n const unitCents = Math.round(l.unit_price_ht * 100);\n const totalCents = Math.round(l.quantity * unitCents);\n const rateHundredths = Math.round(l.vat_rate * 100);\n ht += totalCents;\n groups.set(rateHundredths, (groups.get(rateHundredths) || 0) + totalCents);\n lines.push({description: l.description, quantity: fmtNumber(Number(l.quantity.toFixed(3))) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unitCents), vat_rate: fmtRate(rateHundredths / 100), total_ht: fmtMoney(totalCents)});\n }\n let vatTotal = 0;\n const vat = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([rate, base]) => {\n const cents = Math.round(base * rate / 10000);\n vatTotal += cents;\n return {rate: fmtRate(rate / 100), amount: fmtMoney(cents)};\n });\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(ht), vat, total_ttc: fmtMoney(ht + vatTotal)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n let d = data;\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nconst input = {{ json . }};\nif (input.template_key === undefined || input.template_key === null || input.template_key === \"\") {\n return {templates: Object.keys(TEMPLATES).map((k) => ({template_key: k, title: TEMPLATES[k].title, version: TEMPLATES[k].manifest.version, prefix: TEMPLATES[k].prefix, summary: TEMPLATES[k].summary})), template: null};\n}\nconst tpl = TEMPLATES[input.template_key];\nif (!tpl) fail(\"template_unknown\", String(input.template_key));\nreturn {templates: [], template: {template_key: input.template_key, title: tpl.title, version: tpl.manifest.version, prefix: tpl.prefix, summary: tpl.summary, manifest: tpl.manifest, input_schema: tpl.input_schema, draft_schema: tpl.draft_schema}};\n", "output_key": "result" } ], diff --git a/inventory/modules.json b/inventory/modules.json index 3f5ce0d..a3bae81 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1235,17 +1235,17 @@ ], "sha256": { "document-studio/module.yaml": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", - "document-studio/agents/main/workflows/document-studio-cancel.json": "0432c9b1b735f76e59bb81ef3fd7752a2731d42f0a5a6d149b940f5e353462d4", - "document-studio/agents/main/workflows/document-studio-draft.json": "c73e995684eb920fabc042089f6479aca0b56e9de6554507b2bf22f6908969d8", - "document-studio/agents/main/workflows/document-studio-export.json": "e2db93c9e1645ce1e89d93f41fc03483a24d7e661249834c7ccba9ad759900e5", - "document-studio/agents/main/workflows/document-studio-finalize.json": "9f303f666de8498d2ce550cbf76c012fd587378ca7901bd71c56a7b1b127a3a0", - "document-studio/agents/main/workflows/document-studio-list.json": "7918dfde416e54d990801c936f0ad2371b53feffd85559ae1bbcd5578f7fdd53", - "document-studio/agents/main/workflows/document-studio-plan.json": "e25bae2637cd2acbd26a46b04a2e334797d8e09dbdf16dfaaecf13544bf41f8a", - "document-studio/agents/main/workflows/document-studio-profile-save.json": "08761c5dca9fdb518a343f498bd1c76249069677bcf5af43b506654461c40823", - "document-studio/agents/main/workflows/document-studio-publish.json": "2710078846b86065901d6abf86d5c358302de6dab56b9617a575945619f17862", - "document-studio/agents/main/workflows/document-studio-render.json": "106f73564245e9779342f089ad17921bd75b0ec9a5fd2548efd1b31c6e6da7bf", - "document-studio/agents/main/workflows/document-studio-review-read.json": "0ee90b45f6e0b8b8fe6dcbf144599322ac5884e83b042f22a409a18ca58c7347", - "document-studio/agents/main/workflows/document-studio-template-read.json": "fd3dc261617828143dc3001c80fd0a3e75f899e6e898d7f57663e0540cd9b498", + "document-studio/agents/main/workflows/document-studio-cancel.json": "ab84a922cbf436679bef95dcc45257bb8d58b68b268578a6b155e5d91c848fbc", + "document-studio/agents/main/workflows/document-studio-draft.json": "03f9fc13a22e52d5fc83d658b8de2011be05e9284dafe5a34e297d55c27fb5c7", + "document-studio/agents/main/workflows/document-studio-export.json": "b27e599c3ffac34b5ebaee5c09421f79223dc1737c7aaba4369da74d442bfc2f", + "document-studio/agents/main/workflows/document-studio-finalize.json": "652792303e79db68da3c871465bf2a4290d37b445820cfb0b648eac55215dfd3", + "document-studio/agents/main/workflows/document-studio-list.json": "6e9549761dd55db108d72ea5363963ff712c2a52ef8def6a9de940f49dd60631", + "document-studio/agents/main/workflows/document-studio-plan.json": "1597f5d91ee0fac8d4d69233f5425676576884a9d66449be144dfddfbdcfabe5", + "document-studio/agents/main/workflows/document-studio-profile-save.json": "0d24416bc899a263fa359c083454352ce7c78e2f2720185064a56378062128a3", + "document-studio/agents/main/workflows/document-studio-publish.json": "a16d4e012ed04aea355cb94962faac38009ba5f8d9f48a9080fa6cb6308e0c50", + "document-studio/agents/main/workflows/document-studio-render.json": "696db96a0c6096136b969e494909753da61ed2056b8cf7fade541b60f329abfb", + "document-studio/agents/main/workflows/document-studio-review-read.json": "e13e59515f5b5d32d4123f133cb9e4b88cc5b49438a6f0d7347cf5bc0105be01", + "document-studio/agents/main/workflows/document-studio-template-read.json": "a6c7275e529f8838452c0ed5af27990cfacd2546e6077cb01ee353da99583a7f", "document-studio/agents/main/miniapps/document-studio-review.json": "f0cbd478fba14f030465c2edb9d608d2781ff4c74b39d8a98ca924f46b212f83" } }, @@ -1259,7 +1259,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "e81e33a18cb18f3b7b36a79c9b38ee4fb4e7b7e6176824efe33a328bbde19991" + "code_sha256": "1c83d42457375a41b4bd97e647da64d538daea7f5384aa7eae967a71c1eba88b" } ] }, @@ -1272,7 +1272,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "cfd879c34989575c524ce92c53af6f879d9e1e0da1653e76b979c6808ef9662b" + "code_sha256": "577f614a5dd62794776931c25a011e63e5843f784d3b2109232a8c3bd8e5a719" }, { "path": "/actions/1", @@ -1285,7 +1285,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "46553a9537b798bbc6b8942b46687cda2e4f114851f44a668ae9d68f04e05c44" + "code_sha256": "afab2ad0f53421401b4c25c22a6d279f1c9e04638ddef4ee23af4262c474890c" } ] }, @@ -1298,7 +1298,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "9c142bc571ba70871304d915ef9fe59723c3d7e761e5ad2879ddfe7d3cbc5038" + "code_sha256": "a6a5c81e136a99b691b92202af65bd2ac20488b8419a78dc8d9fc44822ffee5c" } ] }, @@ -1311,7 +1311,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "73bd6acf2e250bcbb3889039f5a8b76f43b04c4c01fc6cca0b3874390a6a6052" + "code_sha256": "38d6bfd9f7a72dbaa597bd8816bc5c11d522b7057745d46beee1d73c37db3363" } ] }, @@ -1324,7 +1324,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "ac18cb9f0c4f23f35c1284a6afae17bd6eaf55bcec5737b7da32a55782bed985" + "code_sha256": "bd8dd86961946436d6abbc1158b3944144234c6f3b24ebd2b5aac71eb6367b34" } ] }, @@ -1337,7 +1337,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "8851378d173f44c79bedde735dd5173a6f38e63d91a382f4202cfd4bce682e84" + "code_sha256": "f749739688faf4b528a55ca7aaaba37d229efcd7930e3fb25beee03a303ba4a8" }, { "path": "/actions/1", @@ -1350,7 +1350,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "dc6a36447e6708d3e180bc775b071e60d189f8e8b1dadee152bd7ccc181d6bb3" + "code_sha256": "db72a5edfc42fae71f430f6a7013ddfd3d6f2c93c3237e472234c1ee549bd71d" } ] }, @@ -1363,7 +1363,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "ec220966d563ccf4b446a4e1a9efb2eb902d355b1d77a7f8602b49cef188499d" + "code_sha256": "52063175be6c0daed7340896ac2498c196f2e6127c99052c9f54d73edd279bc7" } ] }, @@ -1376,7 +1376,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "fe9e6999acea0f197058310f7bebc3cc2e1e673cb3c46b7157a5b6ee8a130580" + "code_sha256": "b76276ca28214596d623db98083d29826c0632cbe6219fd4672cf47b707e619f" } ] }, @@ -1389,7 +1389,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "1ef4fedc0f5c1f2e83a124d9e8183455cb6f41f1661b680d439c49b42ef44957" + "code_sha256": "858f63faa62efd06f479efa06ffa20bac730241778cd123ec3a5ea15a7a3aa51" } ] }, @@ -1402,7 +1402,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "f34f8cc836a018e5ddab24303991c4669c11c5c6a92f2b2379691020b03ad438" + "code_sha256": "04eab566046e1f5e40d0576f5d4a2de68834e1f0d28cc58a94bd9429810e9bdb" } ] }, @@ -1415,7 +1415,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "e2fb49e05f7138b1bac1838571ae11327c47c85316e00944b7de1dd03be68aa6" + "code_sha256": "ec63fa4287631eb3bc6645788ddd688d967e8c3178791300a15b883eabc3ec65" } ] } diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index c6d7f89..9f8d983 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -2,7 +2,7 @@ """Generate the document-studio Module resources (manifest, Workflows, MiniApp). No rendering engine lives in the Module: rendering goes through the MCP tool -`artifact--artifact_render_v1`. The two reference templates (quote and +`artifact_render_v1`. The two reference templates (quote and meeting-minutes) are embedded as text in the Workflows that render; they are the files of document-studio/examples/templates, pinned by contract/PIN.json. Code steps are plain JavaScript (code_execution). The code never contains a @@ -19,7 +19,7 @@ DEST = MODULE / 'agents/main' TEMPLATES_DIR = MODULE / 'examples/templates' VERSION = '0.1.0' -RENDER_TOOL = 'artifact--artifact_render_v1' +RENDER_TOOL = 'artifact_render_v1' STORAGE_TOOLS = ['read_file', 'write_file', 'list_files'] RENDER_TOOLS = STORAGE_TOOLS + [RENDER_TOOL] I18N = json.loads((ROOT / 'contract/i18n.fr.json').read_text(encoding='utf-8')) @@ -69,6 +69,10 @@ def js_embed(value): return 'JSON.parse(' + literal.replace('{', '\\u007b').replace('}', '\\u007d') + ')' +def is_platform_file(rel): + return rel.startswith('fragments/') or rel in ('brand.typ', 'values.json') + + def load_templates(with_files): templates = {} for key, meta in TEMPLATE_META.items(): @@ -79,8 +83,12 @@ def load_templates(with_files): 'title': manifest['title'], 'summary': meta['summary'], 'draft_schema': meta['draft_schema'] or input_schema} if with_files: + # fragments/ (and brand.typ, values.json) are written by the renderer + # itself from its pinned contract: sending them is refused + # (reserved_file_name). The local copies serve template_check only. entry['files'] = {p.relative_to(directory).as_posix(): p.read_text(encoding='utf-8') - for p in sorted(directory.rglob('*')) if p.is_file()} + for p in sorted(directory.rglob('*')) + if p.is_file() and not is_platform_file(p.relative_to(directory).as_posix())} templates[key] = entry return templates @@ -123,6 +131,8 @@ def load_templates(with_files): function b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } async function sha256Hex(bytes) { const d = await crypto.subtle.digest("SHA-256", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, "0")).join(""); } function parseJsonValue(v) { + // llm_call with llm_response_format "text" yields {text, model, provider}. + if (v && typeof v === "object" && !Array.isArray(v) && typeof v.text === "string") v = v.text; if (typeof v !== "string") return v; const cleaned = v.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, ""); try { return JSON.parse(cleaned); } catch (e) { fail("llm_output_invalid", "réponse non JSON"); } @@ -350,7 +360,7 @@ def load_templates(with_files): const tdata = templateData(rec.template_key, data); validateSchema(tpl.input_schema, tdata, "gabarit " + rec.template_key); const doc = {number: number || "BROUILLON", title: rec.title, date: today(), version: String(revision), status, locale: rec.locale}; - const raw = await callTool("artifact--artifact_render_v1", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: "pdf", mode}); + const raw = await callTool("artifact_render_v1", {template: {manifest: tpl.manifest, files: tpl.files}, data: tdata, context: {company: profile.company, brand: profile.brand, doc, i18n: I18N}, output: "pdf", mode}); const res = unwrap(raw); if (isObject(res) && res.error) fail("render_failed", res.error + (res.message ? " : " + res.message : "")); if (!isObject(res) || res.status !== "ok" || !isObject(res.file)) fail("render_failed", "réponse inattendue du moteur de rendu"); @@ -478,8 +488,8 @@ def field(name, title, kind, required, **extra): def llm(action_id, prompt_ref, system, output_key, tokens): return {'id': action_id, 'type': 'llm_call', 'llm_prompt': prompt_ref, 'llm_system_prompt': system, - 'llm_temperature': 0.2, 'llm_max_tokens': tokens, 'llm_response_format': 'json', - 'llm_response_schema': {'type': 'object'}, 'output_key': output_key} + 'llm_temperature': 0.2, 'llm_max_tokens': tokens, 'llm_response_format': 'text', + 'output_key': output_key} SYSTEM = 'Tu es un assistant de rédaction de documents professionnels. Tu réponds uniquement par un objet JSON, sans texte autour.' diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index 2d51972..dc1e9cf 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -44,7 +44,7 @@ def load(path): function pdf(label) { const bytes = Buffer.from("%PDF-1.7 fake " + label); return {bytes, sha: sha(bytes)}; } async function callTool(name, args) { calls.push({name, args: JSON.parse(JSON.stringify(args, (k, v) => (k === "files" ? "[files]" : v)))}); - if (name === "artifact--artifact_render_v1") { + if (name === "artifact_render_v1") { if (opts.render_error) throw new Error(opts.render_error); calls[calls.length - 1].full = args; const f = pdf(args.mode + ":" + args.context.doc.number), p = pdf("png:" + args.mode); @@ -184,11 +184,14 @@ def test_publish_and_finalize_and_cancel_demand_a_manual_confirmation(self): out = run_node('document-studio-profile-save', 'save', {'profile': PROFILE, 'confirmation_manuelle': 'non'}, {}) self.assertTrue(out['error'].startswith('manual_confirmation_required')) - def test_no_llm_step_writes_and_llm_steps_are_json(self): + def test_no_llm_step_writes_and_llm_steps_are_text_parsed_as_json(self): for name, wf in self.workflows.items(): for action in wf['actions']: if action['type'] == 'llm_call': - self.assertEqual(action['llm_response_format'], 'json', name) + # text: the module validator requires a closed llm_response_schema for json, + # and the schema depends on the template; the next step parses and validates. + self.assertEqual(action['llm_response_format'], 'text', name) + self.assertNotIn('llm_response_schema', action, name) for name in ('document-studio-plan',): self.assertFalse(any('write_file' in json.dumps(a) for a in self.workflows[name]['actions'])) @@ -209,6 +212,16 @@ def test_generator_reproduces_the_published_files(self): class TemplatesTest(unittest.TestCase): + def test_embedded_templates_send_no_platform_file(self): + import importlib.util + spec = importlib.util.spec_from_file_location('ds_build', ROOT / 'tooling' / 'document-studio' / 'build.py') + build = importlib.util.module_from_spec(spec) + spec.loader.exec_module(build) + for key, entry in build.load_templates(True).items(): + for rel in entry['files']: + self.assertFalse(rel.startswith('fragments/') or rel in ('brand.typ', 'values.json'), f'{key}/{rel}') + self.assertIn(entry['manifest']['source']['entry'], entry['files'], key) + def test_pin_matches_the_local_files(self): pin = load(TOOLING / 'contract/PIN.json') self.assertRegex(pin['source_commit'], r'^[0-9a-f]{40}$') @@ -245,9 +258,9 @@ def test_render_receives_the_embedded_templates_unchanged(self): quote, fs = create_quote(self, fs) out = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs) ok(self, out) - call = next(c for c in out['calls'] if c['name'] == 'artifact--artifact_render_v1')['full'] + call = next(c for c in out['calls'] if c['name'] == 'artifact_render_v1')['full'] directory = TEMPLATES / 'quote' - self.assertEqual(call['template']['files'], {p.relative_to(directory).as_posix(): p.read_text(encoding='utf-8') for p in sorted(directory.rglob('*')) if p.is_file()}) + self.assertEqual(call['template']['files'], {p.relative_to(directory).as_posix(): p.read_text(encoding='utf-8') for p in sorted(directory.rglob('*')) if p.is_file() and not p.relative_to(directory).as_posix().startswith('fragments/')}) self.assertEqual(call['template']['manifest'], load(directory / 'manifest.json')) self.assertEqual(call['context']['i18n'], load(TOOLING / 'contract/i18n.fr.json')) self.assertEqual((call['output'], call['mode']), ('pdf', 'preview')) @@ -364,7 +377,7 @@ def test_full_lifecycle_with_inline_base64(self): self.assertEqual(record['revision'], 5) self.assertEqual([h['action'] for h in record['history']], ['created', 'rendered', 'approved', 'number_reserved', 'issued']) self.assertEqual(json.loads(fs[f'/document-studio/numbers/quote/{YEAR}/0001.json']['text'])['doc_id'], 'devis-test') - call = [c for c in out['calls'] if c['name'] == 'artifact--artifact_render_v1'][0]['full'] + call = [c for c in out['calls'] if c['name'] == 'artifact_render_v1'][0]['full'] self.assertEqual((call['mode'], call['context']['doc']['number'], call['context']['doc']['status']), ('final', number, 'issued')) write = [c for c in out['calls'] if c['name'] == 'write_file' and c['args']['path'].endswith('.pdf')][0]['args'] self.assertEqual((write['encoding'], write['overwrite']), ('base64', True)) @@ -417,7 +430,7 @@ def approved_fs(): self.assertTrue(lost['error'].startswith('number_conflict'), lost) record = json.loads(lost['fs']['/document-studio/docs/devis-test/record.json']['text']) self.assertEqual((record['status'], record['number']), ('approved', None)) - self.assertFalse([c for c in lost['calls'] if c['name'] == 'artifact--artifact_render_v1']) + self.assertFalse([c for c in lost['calls'] if c['name'] == 'artifact_render_v1']) def test_a_reserved_number_is_kept_when_the_render_fails(self): _, fs = create_quote(self, seeded()) @@ -446,7 +459,7 @@ def test_render_patch_is_validated_and_merged(self): _, fs = create_quote(self, seeded()) bad = run_node('document-studio-render', 'render', {'doc_id': 'devis-test', 'data_patch': {'valid_until': 'demain'}}, fs) self.assertTrue(bad['error'].startswith('data_invalid')) - self.assertFalse([c for c in bad['calls'] if c['name'] == 'artifact--artifact_render_v1']) + self.assertFalse([c for c in bad['calls'] if c['name'] == 'artifact_render_v1']) good = run_node('document-studio-render', 'render', {'doc_id': 'devis-test', 'data_patch': {'valid_until': '2027-01-31'}}, fs) ok(self, good) record = json.loads(good['fs']['/document-studio/docs/devis-test/record.json']['text']) From 75b5728ee408badf0d5ced767d36d5a384866c67 Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Sat, 7 Nov 2026 09:15:04 +0100 Subject: [PATCH 03/13] docs(document-studio): README in English, runtime notes from the One replay (AGENT-1578) Co-Authored-By: Claude Opus 5.5 --- catalog.json | 2 +- document-studio/README.md | 171 ++++++++++++++++++++------------------ 2 files changed, 92 insertions(+), 81 deletions(-) diff --git a/catalog.json b/catalog.json index 6fdc2dd..b00964f 100644 --- a/catalog.json +++ b/catalog.json @@ -647,7 +647,7 @@ "subpath": "document-studio", "manifest": "document-studio/module.yaml", "manifest_sha256": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", - "tree_sha256": "1245028d05ec772852fd7f627732d84fd386ba0f13520a0eef96509db2a8844e", + "tree_sha256": "fbb3e3bc89e5d859d8e3f9bf618ba4c1d100635395707be982400865c27c758c", "description": { "en": "Document studio: draft business documents from a brief, render them to PDF from templates and the company profile, review, approve and issue them with a number, and keep every revision in Storage.", "fr": "Studio de documents : rédiger des documents professionnels depuis un brief, les rendre en PDF avec des gabarits et la fiche entreprise, les relire, les approuver et les émettre avec un numéro, en gardant chaque révision dans Storage." diff --git a/document-studio/README.md b/document-studio/README.md index 0518a7b..ea96242 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -1,95 +1,106 @@ # Document studio -Module réutilisable qui transforme un brief en document professionnel (devis, -compte rendu de réunion) : brouillon, rendu PDF à partir d'un gabarit et de la -fiche entreprise, relecture, approbation, émission avec un numéro. Tout vit -dans Storage ; rien n'est envoyé à l'extérieur. +Reusable Module that turns a brief into a business document (quote, meeting +minutes): draft, PDF render from a template and the company profile, review, +approval and issue with a number. Everything lives in Storage; nothing is sent +outside. -Le Module ne contient aucun moteur de rendu. Le rendu passe par le tool MCP -`artifact_render_v1` (mode `preview` pour les brouillons, `final` pour -l'émission). Les étapes de code sont du JavaScript (`code_execution`) : pas de -WASM en V0. Aucun binaire n'est versionné ici (ni PDF ni PNG). +The Module contains no rendering engine. Rendering goes through the MCP tool +`artifact_render_v1` (mode `preview` for drafts, `final` for the issue). Code +steps are JavaScript (`code_execution`): no WASM in V0. No binary is versioned +here (no PDF, no PNG). The document content (prompts, templates, error +messages) is French; `fr` is the only locale in V0. ## Workflows -| Workflow | Rôle | +| Workflow | Role | |---|---| -| `document-studio-plan` | choisit le gabarit d'après un brief, propose un titre, liste les données manquantes et les questions à poser. N'écrit rien | -| `document-studio-draft` | remplit les données du gabarit (appel modèle, puis validation stricte) et crée le dossier du document au statut `draft`. Pour un devis, les montants et les totaux sont calculés ici, en centimes entiers, à partir des lignes : le modèle ne fournit que des quantités et des prix | -| `document-studio-render` | rend l'état courant (PDF et aperçus PNG) et ajoute une révision. `data_patch` fusionne (superficiellement) des corrections dans les données, qui sont revalidées. Un document émis ou annulé ne se rend plus (`document_locked`) | -| `document-studio-finalize` | `draft` vers `approved`. Exige un rendu de la révision courante et `confirmation_manuelle` | -| `document-studio-publish` | exige `approved` et `confirmation_manuelle`. Réserve le prochain numéro, rend en mode `final`, enregistre le PDF émis, passe à `issued` | -| `document-studio-cancel` | passe à `cancelled` avec un motif. Un numéro émis n'est jamais réutilisé | -| `document-studio-export` | copie le PDF émis (ou le dernier rendu, signalé comme brouillon) vers un chemin Storage hors de `/document-studio/`, avec son empreinte SHA-256. Mail et SFTP sont hors V0 | -| `document-studio-profile-save` | valide et enregistre la fiche entreprise et la charte (`/document-studio/profile.json`), avec confirmation manuelle | -| `document-studio-list` | liste des documents (identifiant, titre, statut, numéro, révision, dernière empreinte) | -| `document-studio-review-read` | dossier complet d'un document et aperçus du dernier rendu, pour la MiniApp | -| `document-studio-template-read` | liste des gabarits, ou manifeste et schémas de données d'un gabarit | - -La MiniApp `document-studio-review` charge un document par son identifiant, -affiche statut, révision, numéro, pages et le tableau des rendus (révision, -mode, empreinte, chemin), et relance un rendu. L'approbation et l'émission -passent par les formulaires des Workflows, avec la confirmation manuelle. - -## Cycle de vie - -`draft` (rendus successifs) → `approved` → `issued`. `cancelled` est possible -depuis tous les autres statuts. Un nouveau rendu d'un document `approved` le -ramène à `draft` : l'approbation est à refaire. La confirmation manuelle est -le champ de formulaire `confirmation_manuelle` (`oui` ou `non`) ; sans `oui`, -le Workflow refuse (`manual_confirmation_required`) avant toute lecture ou -écriture. Le Module n'approuve jamais à la place d'une personne. - -## Stockage - -- `/document-studio/profile.json` : la charte, au schéma `{schema_version: 1, company, brand}` du contrat de gabarit. Un exemple fictif est dans `examples/profile.example.json`. -- `/document-studio/docs//record.json` : le dossier (`document-studio.record/v1`) : statut, numéro, révision (+1 à chaque écriture), données, historique, rendus (chemin, SHA-256, aperçus, provenance), émission. -- `/document-studio/docs//r/` : PDF et aperçus d'un rendu. -- `/document-studio/docs//issued/.pdf` : le PDF émis. -- `/document-studio/numbers///.json` : jeton de numéro. - -`doc_id` : `^[a-z0-9][a-z0-9-]{0,47}$`, choisi par l'appelant ou dérivé du -titre avec un suffixe court. Numéro : `--` (`DEV` pour le -devis, `CR` pour le compte rendu). - -Sans fiche entreprise, `render` et `publish` échouent avec `profile_missing` : -enregistrez la charte par `document-studio-profile-save`. - -## Gabarits - -`examples/templates/quote` et `examples/templates/meeting-minutes` sont des -copies des gabarits de référence du contrat `agentmaurice.template/v1`, avec -les fragments partagés qu'ils importent. `tooling/document-studio/contract/PIN.json` -note le commit du contrat d'origine et l'empreinte de chaque fichier. Un seul -fichier diffère de l'original : `quote/main.typ`, qui ajoute la mention -« Ce document est un devis, ce n'est pas une facture ». Le contrôle du contrat se lance -avec le script `template_check.py` de ce contrat (`check `) ; la CI de ce dépôt est -hors ligne et ne dépend pas de lui. - -Les gabarits sont embarqués en texte dans les Workflows qui rendent. Leurs -accolades y sont écrites en séquences d'échappement, car le moteur de Workflows -lirait une double accolade dans le code comme une action de gabarit. - -Données d'un devis : le brouillon porte des nombres (`quantity`, `unit_price_ht`, -`vat_rate`), jamais des montants formatés ni des totaux. Au rendu, le Workflow -produit les chaînes attendues par le gabarit (`1 250,00 €`) et les totaux HT, TVA par taux et TTC. - -## Régénération et tests +| `document-studio-plan` | picks the template from a brief, proposes a title, lists the missing data and the questions to ask. Writes nothing | +| `document-studio-draft` | fills the template data (model call, then strict validation) and creates the document record with status `draft`. For a quote, amounts and totals are computed here, in integer cents, from the lines: the model only provides quantities and prices | +| `document-studio-render` | renders the current state (PDF and PNG previews) and adds a revision. `data_patch` merges (shallow) corrections into the data, which is revalidated. An issued or cancelled document no longer renders (`document_locked`) | +| `document-studio-finalize` | `draft` to `approved`. Requires a render of the current revision and `confirmation_manuelle` | +| `document-studio-publish` | requires `approved` and `confirmation_manuelle`. Reserves the next number, renders in `final` mode, stores the issued PDF, moves to `issued` | +| `document-studio-cancel` | moves to `cancelled` with a reason. An issued number is never reused | +| `document-studio-export` | copies the issued PDF (or the latest render, flagged as a draft) to a Storage path outside `/document-studio/`, with its SHA-256. Mail and SFTP are out of V0 | +| `document-studio-profile-save` | validates and stores the company profile and brand (`/document-studio/profile.json`), with manual confirmation | +| `document-studio-list` | lists the documents (identifier, title, status, number, revision, latest hash) | +| `document-studio-review-read` | full record of a document and previews of its latest render, for the MiniApp | +| `document-studio-template-read` | lists the templates, or the manifest and data schemas of one template | + +The `document-studio-review` MiniApp loads a document by its identifier, shows +status, revision, number, pages and the table of renders (revision, mode, +hash, path), and triggers a new render. Approval and issue go through the +Workflow forms, with the manual confirmation. + +## Lifecycle + +`draft` (successive renders) → `approved` → `issued`. `cancelled` is reachable +from every other status. A new render of an `approved` document brings it back +to `draft`: the approval must be given again. The manual confirmation is the +form field `confirmation_manuelle` (`oui` or `non`); without `oui`, the +Workflow refuses (`manual_confirmation_required`) before any read or write. +The Module never approves on a person's behalf. + +## Storage + +- `/document-studio/profile.json`: the brand, with the `{schema_version: 1, company, brand}` shape of the template contract. A fictitious example is in `examples/profile.example.json`. +- `/document-studio/docs//record.json`: the record (`document-studio.record/v1`): status, number, revision (+1 at every write), data, history, renders (path, SHA-256, previews, provenance), issue. +- `/document-studio/docs//r/`: PDF and previews of one render. +- `/document-studio/docs//issued/.pdf`: the issued PDF. +- `/document-studio/numbers/