diff --git a/catalog.json b/catalog.json index 64ff3d7..2f84de6 100644 --- a/catalog.json +++ b/catalog.json @@ -643,11 +643,11 @@ { "key": "document-studio", "name": "Document studio", - "version": "0.3.0", + "version": "0.4.0", "subpath": "document-studio", "manifest": "document-studio/module.yaml", - "manifest_sha256": "f31b391b04ecf28700efb19584a020a2e72ddcb5c7ade5c5b6f6f3113f4562db", - "tree_sha256": "66f0b03609f2dfbb16859747646ae16fb778703f8544b36f318b8e94ae497fc0", + "manifest_sha256": "958f6fca731e508d2e6ff3b9a01e322a0ff37b8ba41f3d223515e41452b5b145", + "tree_sha256": "2bd528a9c12afefb88f5b471893418a24c97c3ddf023a8af00e582c174ae637a", "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 0d73110..ff688f4 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -1,7 +1,7 @@ # Document studio Reusable Module that turns a brief into a business document (quote, meeting -minutes): draft, PDF render from a template and the company profile, review, +minutes, chart dashboard): 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. @@ -85,7 +85,7 @@ The Module never approves on a person's behalf. `doc_id`: `^[a-z0-9][a-z0-9-]{0,47}$`, chosen by the caller or derived from the title with a short suffix. Number: `--` (`DEV` for the -quote, `CR` for the minutes). +quote, `CR` for the minutes, `TB` for the dashboard). The company profile is read from the `cib-profile` record of the `profile` Module through `recipe--application_data_v1` (`operation: read`, `namespace: cib-profile`, `record_key: company-profile`, the call of @@ -107,12 +107,13 @@ The same bytes under another author are refused (`version_unchanged`). ## Templates -`examples/templates/quote` and `examples/templates/meeting-minutes` are copies -of the reference templates of the `agentmaurice.template/v1` contract, with the -shared fragments they import. `tooling/document-studio/contract/PIN.json` -records the origin commit of the contract and the hash of every file. One file -differs from the original: `quote/main.typ`, which adds the notice « Ce -document est un devis, ce n'est pas une facture ». The contract check runs with +`examples/templates/quote`, `examples/templates/meeting-minutes` and +`examples/templates/dashboard` are copies of the reference templates of the +`agentmaurice.template/v1` contract, with the shared fragments they import. +`tooling/document-studio/contract/PIN.json` records the origin commit of the +contract and the hash of every file. One file differs from the original: +`quote/main.typ`, which adds the notice « Ce document est un devis, ce n'est +pas une facture ». The contract check runs with that contract's `template_check.py` (`check `); the CI of this repository is offline and does not depend on it. @@ -122,6 +123,28 @@ from its pinned contract and refuses them from the caller (`reserved_file_name`). Their braces are written as escape sequences, because the Workflow engine would read a double brace in the code as a template action. +### Dashboard template (charts) + +The `dashboard` template (number prefix `TB`) draws six charts, one page each, +from `chart/v1` data (`fragments/charts.typ` of the contract, pure vector +Typst, deterministic): `bar` (grouped bars), `line`, `pie`, `gantt` +(phases and tasks over weeks), `org` (organisation chart) and `process` +(process flow with start, step, decision and end). The draft holds one chart +object per property (`bar`, `line`, `pie`, `gantt`, `org`, `process`) plus a +`title` and the `titles` of the six pages; the model only provides the data, +the engine draws it and nothing is computed by the Workflow (the draft schema +is the template input schema). The bounds of `chart/v1` apply (for example 24 +categories, 5 series, 10 pie parts, 25 Gantt tasks, 30 organisation nodes); a +violation fails the render. + +Dependency: this template needs the MCP `artifact` engine **v0.2.5 or later**, +which embeds `charts.typ`. The Workflow never sends `fragments/`: the engine +writes them from its pinned contract, so a One whose artifact is older than +v0.2.5 fails the render of this template (the quote and the minutes are not +affected). The Module manifest has no field for a minimum MCP version +(`requires.mcp` only lists a name and tools), so the constraint is stated +here only. + Quote data: the draft holds numbers (`quantity`, `unit_price_ht`, `vat_rate`), never formatted amounts nor totals. At render time the Workflow produces the strings the template expects (`1 250,00 €`) and the HT, per-rate VAT and TTC diff --git a/document-studio/agents/main/workflows/document-read.json b/document-studio/agents/main/workflows/document-read.json index 2f0a66c..de83439 100644 --- a/document-studio/agents/main/workflows/document-read.json +++ b/document-studio/agents/main/workflows/document-read.json @@ -69,7 +69,7 @@ "recipe--application_data_v1" ] }, - "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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 NAMESPACE = \"cib-documents\";\n\nfunction brokerItem(response, id) {\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== NAMESPACE || item.key !== id) fail(\"broker_record_identity_invalid\");\n if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail(\"broker_revision_invalid\");\n const p = item.permissions;\n if (!isObject(p) || typeof p.can_read !== \"boolean\" || typeof p.can_write !== \"boolean\" || typeof p.can_manage !== \"boolean\") fail(\"broker_permissions_invalid\");\n return item;\n}\nfunction brokerView(item) {\n const p = item.permissions;\n const shares = Array.isArray(item.shares) ? item.shares : [];\n return {record: isObject(item.data) ? item.data : null, revision: item.revision, owner_user_id: typeof item.owner_user_id === \"string\" ? item.owner_user_id : \"\", permissions: p, permissions_summary: \"Lecture : \" + (p.can_read ? \"oui\" : \"non\") + \" · Modification : \" + (p.can_write ? \"oui\" : \"non\") + \" · Partage : \" + (p.can_manage ? \"oui\" : \"non\"), shares, share_count: shares.length};\n}\n\nconst input = {{ json . }};\nconst wantPdf = (() => {\n const v = input.include_pdf;\n if (v === undefined || v === null || v === \"\" || v === false || v === \"non\" || v === \"false\") return false;\n if (v === true || v === \"oui\" || v === \"true\") return true;\n return fail(\"include_pdf_invalid\", \"oui ou non attendu\");\n})();\nconst MAX_PDF_BYTES = 5 * 1024 * 1024;\nif (input.doc_id === undefined || input.doc_id === null || input.doc_id === \"\") {\n if (wantPdf) fail(\"include_pdf_requires_doc_id\", \"indiquez le document dont lire le PDF\");\n const response = await callTool(\"recipe--application_data_v1\", {operation: \"list\", namespace: NAMESPACE, prefix: \"\"});\n const payload = response && response.data ? response.data : response;\n if (!payload || !Array.isArray(payload.items) || !Number.isSafeInteger(payload.total) || payload.total !== payload.items.length) fail(\"broker_list_invalid\");\n const items = payload.items.map((view) => {\n const key = typeof view.record_key === \"string\" ? view.record_key : view.key;\n if (typeof key !== \"string\" || !ID_RE.test(key)) fail(\"broker_list_key_invalid\");\n const d = isObject(view.data) ? view.data : (isObject(view.record) ? view.record : {});\n return {doc_id: key, title: d.title === undefined ? \"\" : d.title, template_key: d.template_key === undefined ? \"\" : d.template_key, number: d.number === undefined ? \"\" : d.number, version: d.version === undefined ? null : d.version, path: d.path === undefined ? \"\" : d.path, sha256: d.sha256 === undefined ? \"\" : d.sha256, revision: view.revision, owner_user_id: typeof view.owner_user_id === \"string\" ? view.owner_user_id : \"\", permissions: isObject(view.permissions) ? view.permissions : {}};\n });\n return {items, total: payload.total, record: null, revision: null, owner_user_id: \"\", permissions: null, permissions_summary: \"\", shares: [], share_count: 0, pdf_base64: null, pdf_sha256: null, pdf_bytes: null};\n}\nconst id = docIdOf(input.doc_id);\nconst item = brokerItem(await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: NAMESPACE, record_key: id}), id);\nif (!isObject(item.data)) fail(\"broker_record_data_invalid\");\nconst out = {...brokerView(item), items: [], total: 1, pdf_base64: null, pdf_sha256: null, pdf_bytes: null};\nif (wantPdf) {\n // Only after the broker read succeeded: the ACL of the record, not the Storage rights of the member, opens the PDF.\n const path = item.data.path;\n const prefix = ROOT + \"/docs/\" + id + \"/issued/\";\n if (typeof path !== \"string\" || !path.startsWith(prefix) || path.length > 300 || path.includes(\"..\") || path.includes(\"//\") || path.slice(prefix.length).includes(\"/\") || !path.endsWith(\".pdf\")) fail(\"invalid_path\", \"le PDF doit être un document émis de \" + ROOT);\n if (typeof item.data.sha256 !== \"string\" || !/^[0-9a-f]{64}$/.test(item.data.sha256)) fail(\"broker_record_data_invalid\", \"empreinte absente\");\n let r;\n try { r = await callTool(\"read_file\", {path, encoding: \"base64\"}); } catch (e) { fail(\"storage_unavailable\", String(e && e.message).slice(0, 200)); }\n if (isObject(r) && isObject(r.data) && r.content === undefined) r = r.data;\n const encoded = typeof r === \"string\" ? r : (isObject(r) && typeof r.content === \"string\" ? r.content : null);\n if (encoded === null) fail(\"storage_read_failed\", path);\n const clean = encoded.replace(/\\s+/g, \"\");\n if (clean.length > Math.ceil(MAX_PDF_BYTES / 3) * 4) fail(\"pdf_too_large\", \"au plus 5 Mio\");\n const bytes = b64ToBytes(clean);\n if (bytes.length > MAX_PDF_BYTES) fail(\"pdf_too_large\", \"au plus 5 Mio\");\n const sha = await sha256Hex(bytes);\n if (sha !== item.data.sha256) fail(\"pdf_integrity_failed\", \"l'empreinte du PDF lu ne correspond pas au record partagé\");\n out.pdf_base64 = clean; out.pdf_sha256 = sha; out.pdf_bytes = bytes.length;\n}\nreturn out;\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 NAMESPACE = \"cib-documents\";\n\nfunction brokerItem(response, id) {\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== NAMESPACE || item.key !== id) fail(\"broker_record_identity_invalid\");\n if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail(\"broker_revision_invalid\");\n const p = item.permissions;\n if (!isObject(p) || typeof p.can_read !== \"boolean\" || typeof p.can_write !== \"boolean\" || typeof p.can_manage !== \"boolean\") fail(\"broker_permissions_invalid\");\n return item;\n}\nfunction brokerView(item) {\n const p = item.permissions;\n const shares = Array.isArray(item.shares) ? item.shares : [];\n return {record: isObject(item.data) ? item.data : null, revision: item.revision, owner_user_id: typeof item.owner_user_id === \"string\" ? item.owner_user_id : \"\", permissions: p, permissions_summary: \"Lecture : \" + (p.can_read ? \"oui\" : \"non\") + \" · Modification : \" + (p.can_write ? \"oui\" : \"non\") + \" · Partage : \" + (p.can_manage ? \"oui\" : \"non\"), shares, share_count: shares.length};\n}\n\nconst input = {{ json . }};\nconst wantPdf = (() => {\n const v = input.include_pdf;\n if (v === undefined || v === null || v === \"\" || v === false || v === \"non\" || v === \"false\") return false;\n if (v === true || v === \"oui\" || v === \"true\") return true;\n return fail(\"include_pdf_invalid\", \"oui ou non attendu\");\n})();\nconst MAX_PDF_BYTES = 5 * 1024 * 1024;\nif (input.doc_id === undefined || input.doc_id === null || input.doc_id === \"\") {\n if (wantPdf) fail(\"include_pdf_requires_doc_id\", \"indiquez le document dont lire le PDF\");\n const response = await callTool(\"recipe--application_data_v1\", {operation: \"list\", namespace: NAMESPACE, prefix: \"\"});\n const payload = response && response.data ? response.data : response;\n if (!payload || !Array.isArray(payload.items) || !Number.isSafeInteger(payload.total) || payload.total !== payload.items.length) fail(\"broker_list_invalid\");\n const items = payload.items.map((view) => {\n const key = typeof view.record_key === \"string\" ? view.record_key : view.key;\n if (typeof key !== \"string\" || !ID_RE.test(key)) fail(\"broker_list_key_invalid\");\n const d = isObject(view.data) ? view.data : (isObject(view.record) ? view.record : {});\n return {doc_id: key, title: d.title === undefined ? \"\" : d.title, template_key: d.template_key === undefined ? \"\" : d.template_key, number: d.number === undefined ? \"\" : d.number, version: d.version === undefined ? null : d.version, path: d.path === undefined ? \"\" : d.path, sha256: d.sha256 === undefined ? \"\" : d.sha256, revision: view.revision, owner_user_id: typeof view.owner_user_id === \"string\" ? view.owner_user_id : \"\", permissions: isObject(view.permissions) ? view.permissions : {}};\n });\n return {items, total: payload.total, record: null, revision: null, owner_user_id: \"\", permissions: null, permissions_summary: \"\", shares: [], share_count: 0, pdf_base64: null, pdf_sha256: null, pdf_bytes: null};\n}\nconst id = docIdOf(input.doc_id);\nconst item = brokerItem(await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: NAMESPACE, record_key: id}), id);\nif (!isObject(item.data)) fail(\"broker_record_data_invalid\");\nconst out = {...brokerView(item), items: [], total: 1, pdf_base64: null, pdf_sha256: null, pdf_bytes: null};\nif (wantPdf) {\n // Only after the broker read succeeded: the ACL of the record, not the Storage rights of the member, opens the PDF.\n const path = item.data.path;\n const prefix = ROOT + \"/docs/\" + id + \"/issued/\";\n if (typeof path !== \"string\" || !path.startsWith(prefix) || path.length > 300 || path.includes(\"..\") || path.includes(\"//\") || path.slice(prefix.length).includes(\"/\") || !path.endsWith(\".pdf\")) fail(\"invalid_path\", \"le PDF doit être un document émis de \" + ROOT);\n if (typeof item.data.sha256 !== \"string\" || !/^[0-9a-f]{64}$/.test(item.data.sha256)) fail(\"broker_record_data_invalid\", \"empreinte absente\");\n let r;\n try { r = await callTool(\"read_file\", {path, encoding: \"base64\"}); } catch (e) { fail(\"storage_unavailable\", String(e && e.message).slice(0, 200)); }\n if (isObject(r) && isObject(r.data) && r.content === undefined) r = r.data;\n const encoded = typeof r === \"string\" ? r : (isObject(r) && typeof r.content === \"string\" ? r.content : null);\n if (encoded === null) fail(\"storage_read_failed\", path);\n const clean = encoded.replace(/\\s+/g, \"\");\n if (clean.length > Math.ceil(MAX_PDF_BYTES / 3) * 4) fail(\"pdf_too_large\", \"au plus 5 Mio\");\n const bytes = b64ToBytes(clean);\n if (bytes.length > MAX_PDF_BYTES) fail(\"pdf_too_large\", \"au plus 5 Mio\");\n const sha = await sha256Hex(bytes);\n if (sha !== item.data.sha256) fail(\"pdf_integrity_failed\", \"l'empreinte du PDF lu ne correspond pas au record partagé\");\n out.pdf_base64 = clean; out.pdf_sha256 = sha; out.pdf_bytes = bytes.length;\n}\nreturn out;\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-share.json b/document-studio/agents/main/workflows/document-share.json index 2b7a8bb..9c98acb 100644 --- a/document-studio/agents/main/workflows/document-share.json +++ b/document-studio/agents/main/workflows/document-share.json @@ -121,7 +121,7 @@ "recipe--application_data_v1" ] }, - "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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 NAMESPACE = \"cib-documents\";\n\nfunction brokerItem(response, id) {\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== NAMESPACE || item.key !== id) fail(\"broker_record_identity_invalid\");\n if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail(\"broker_revision_invalid\");\n const p = item.permissions;\n if (!isObject(p) || typeof p.can_read !== \"boolean\" || typeof p.can_write !== \"boolean\" || typeof p.can_manage !== \"boolean\") fail(\"broker_permissions_invalid\");\n return item;\n}\nfunction brokerView(item) {\n const p = item.permissions;\n const shares = Array.isArray(item.shares) ? item.shares : [];\n return {record: isObject(item.data) ? item.data : null, revision: item.revision, owner_user_id: typeof item.owner_user_id === \"string\" ? item.owner_user_id : \"\", permissions: p, permissions_summary: \"Lecture : \" + (p.can_read ? \"oui\" : \"non\") + \" · Modification : \" + (p.can_write ? \"oui\" : \"non\") + \" · Partage : \" + (p.can_manage ? \"oui\" : \"non\"), shares, share_count: shares.length};\n}\n\nasync function readIssuedRecord(id) {\n let raw;\n try {\n const r = await callTool(\"read_file\", {path: ROOT + \"/docs/\" + id + \"/record.json\"});\n raw = typeof r === \"string\" ? r : (isObject(r) && typeof r.content === \"string\" ? r.content : (isObject(r) && isObject(r.data) && typeof r.data.content === \"string\" ? r.data.content : null));\n } catch (e) {\n const message = String(e && e.message);\n if (/not found|does not exist|no such/i.test(message)) fail(\"document_not_found\", id);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n if (raw === null) fail(\"storage_read_failed\", id);\n let rec;\n try { rec = JSON.parse(raw); } catch (e) { fail(\"record_corrupt\", id); }\n return checkRecord(rec, id);\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nlet expected = input.expected_revision;\nif (expected === undefined || expected === null || expected === \"\") expected = 0;\nif (typeof expected === \"string\" && /^[0-9]+$/.test(expected)) expected = Number(expected);\nif (!Number.isSafeInteger(expected) || expected < 0) fail(\"expected_revision_invalid\");\nconst subject = input.share_subject_user_id === undefined || input.share_subject_user_id === null ? \"\" : input.share_subject_user_id;\nif (typeof subject !== \"string\" || subject.length > 256 || /[\\/\\s]/.test(subject)) fail(\"subject_user_id_invalid\");\nconst permission = input.share_permission === undefined || input.share_permission === null || input.share_permission === \"\" ? \"read\" : input.share_permission;\nif (![\"read\", \"none\"].includes(permission)) fail(\"permission_invalid\", \"lecture ou retrait seulement\");\nif (permission === \"none\" && !subject) fail(\"subject_user_id_required\", \"indiquez le membre dont retirer l'accès\");\nlet revision = expected;\nlet item = null;\nif (permission !== \"none\") {\n const rec = await readIssuedRecord(id);\n if (rec.status !== \"issued\" || !isObject(rec.issued) || !isObject(rec.issued.file) || typeof rec.issued.file.path !== \"string\" || typeof rec.issued.file.sha256 !== \"string\") fail(\"status_invalid\", \"seul un document émis se partage (statut actuel : \" + rec.status + \")\");\n const data = {schema: \"document-studio.shared/v1\", doc_id: rec.doc_id, title: String(rec.title || \"\"), template_key: rec.template_key, number: rec.number, version: rec.revision, path: rec.issued.file.path, sha256: rec.issued.file.sha256, issued_at: rec.issued.at};\n item = brokerItem(await callTool(\"recipe--application_data_v1\", {operation: \"save\", namespace: NAMESPACE, record_key: id, data, expected_revision: expected}), id);\n revision = item.revision;\n}\nif (subject) {\n if (revision < 1) fail(\"expected_revision_invalid\", \"révision du record partagé requise pour retirer un accès\");\n item = brokerItem(await callTool(\"recipe--application_data_v1\", {operation: \"share\", namespace: NAMESPACE, record_key: id, expected_revision: revision, subject_user_id: subject.trim(), permission}), id);\n}\nconst view = brokerView(item);\nreturn {...view, doc_id: id, shared_with: subject ? subject.trim() : \"\", message: subject ? \"Partage mis à jour par le broker natif. Partager un document ne donne pas accès au service.\" : (view.share_count > 0 ? \"Référence du document republiée ; partagée avec \" + view.share_count + \" membre(s), partages inchangés.\" : \"Référence du document publiée, visible de son propriétaire seul tant qu'aucun membre n'est ajouté.\"), external_effect: false};\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 NAMESPACE = \"cib-documents\";\n\nfunction brokerItem(response, id) {\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== NAMESPACE || item.key !== id) fail(\"broker_record_identity_invalid\");\n if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail(\"broker_revision_invalid\");\n const p = item.permissions;\n if (!isObject(p) || typeof p.can_read !== \"boolean\" || typeof p.can_write !== \"boolean\" || typeof p.can_manage !== \"boolean\") fail(\"broker_permissions_invalid\");\n return item;\n}\nfunction brokerView(item) {\n const p = item.permissions;\n const shares = Array.isArray(item.shares) ? item.shares : [];\n return {record: isObject(item.data) ? item.data : null, revision: item.revision, owner_user_id: typeof item.owner_user_id === \"string\" ? item.owner_user_id : \"\", permissions: p, permissions_summary: \"Lecture : \" + (p.can_read ? \"oui\" : \"non\") + \" · Modification : \" + (p.can_write ? \"oui\" : \"non\") + \" · Partage : \" + (p.can_manage ? \"oui\" : \"non\"), shares, share_count: shares.length};\n}\n\nasync function readIssuedRecord(id) {\n let raw;\n try {\n const r = await callTool(\"read_file\", {path: ROOT + \"/docs/\" + id + \"/record.json\"});\n raw = typeof r === \"string\" ? r : (isObject(r) && typeof r.content === \"string\" ? r.content : (isObject(r) && isObject(r.data) && typeof r.data.content === \"string\" ? r.data.content : null));\n } catch (e) {\n const message = String(e && e.message);\n if (/not found|does not exist|no such/i.test(message)) fail(\"document_not_found\", id);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n if (raw === null) fail(\"storage_read_failed\", id);\n let rec;\n try { rec = JSON.parse(raw); } catch (e) { fail(\"record_corrupt\", id); }\n return checkRecord(rec, id);\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nlet expected = input.expected_revision;\nif (expected === undefined || expected === null || expected === \"\") expected = 0;\nif (typeof expected === \"string\" && /^[0-9]+$/.test(expected)) expected = Number(expected);\nif (!Number.isSafeInteger(expected) || expected < 0) fail(\"expected_revision_invalid\");\nconst subject = input.share_subject_user_id === undefined || input.share_subject_user_id === null ? \"\" : input.share_subject_user_id;\nif (typeof subject !== \"string\" || subject.length > 256 || /[\\/\\s]/.test(subject)) fail(\"subject_user_id_invalid\");\nconst permission = input.share_permission === undefined || input.share_permission === null || input.share_permission === \"\" ? \"read\" : input.share_permission;\nif (![\"read\", \"none\"].includes(permission)) fail(\"permission_invalid\", \"lecture ou retrait seulement\");\nif (permission === \"none\" && !subject) fail(\"subject_user_id_required\", \"indiquez le membre dont retirer l'accès\");\nlet revision = expected;\nlet item = null;\nif (permission !== \"none\") {\n const rec = await readIssuedRecord(id);\n if (rec.status !== \"issued\" || !isObject(rec.issued) || !isObject(rec.issued.file) || typeof rec.issued.file.path !== \"string\" || typeof rec.issued.file.sha256 !== \"string\") fail(\"status_invalid\", \"seul un document émis se partage (statut actuel : \" + rec.status + \")\");\n const data = {schema: \"document-studio.shared/v1\", doc_id: rec.doc_id, title: String(rec.title || \"\"), template_key: rec.template_key, number: rec.number, version: rec.revision, path: rec.issued.file.path, sha256: rec.issued.file.sha256, issued_at: rec.issued.at};\n item = brokerItem(await callTool(\"recipe--application_data_v1\", {operation: \"save\", namespace: NAMESPACE, record_key: id, data, expected_revision: expected}), id);\n revision = item.revision;\n}\nif (subject) {\n if (revision < 1) fail(\"expected_revision_invalid\", \"révision du record partagé requise pour retirer un accès\");\n item = brokerItem(await callTool(\"recipe--application_data_v1\", {operation: \"share\", namespace: NAMESPACE, record_key: id, expected_revision: revision, subject_user_id: subject.trim(), permission}), id);\n}\nconst view = brokerView(item);\nreturn {...view, doc_id: id, shared_with: subject ? subject.trim() : \"\", message: subject ? \"Partage mis à jour par le broker natif. Partager un document ne donne pas accès au service.\" : (view.share_count > 0 ? \"Référence du document republiée ; partagée avec \" + view.share_count + \" membre(s), partages inchangés.\" : \"Référence du document publiée, visible de son propriétaire seul tant qu'aucun membre n'est ajouté.\"), external_effect: false};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-cancel.json b/document-studio/agents/main/workflows/document-studio-cancel.json index 5458415..36ec7c0 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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 4ba066e..f34d8cd 100644 --- a/document-studio/agents/main/workflows/document-studio-draft.json +++ b/document-studio/agents/main/workflows/document-studio-draft.json @@ -23,7 +23,8 @@ "description": "Template key", "enum": [ "quote", - "meeting-minutes" + "meeting-minutes", + "dashboard" ] }, "title": { @@ -72,6 +73,10 @@ { "value": "meeting-minutes", "label": "Compte rendu de réunion" + }, + { + "value": "dashboard", + "label": "Tableau de bord" } ] }, @@ -99,7 +104,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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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\");\nrejectUnsafeKeys(input.answers, \"answers\");\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\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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\");\nrejectUnsafeKeys(input.answers, \"answers\");\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" }, { @@ -122,7 +127,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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 || fallbackTitle(key, data)) + \"-\" + shortSuffix();\ndata = normalizeData(key, data, id);\nif (!title) title = documentTitle(key, data);\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 0054757..bc87f76 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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé ne s'exporte pas\");\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé ne s'exporte pas\");\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 fef3c32..21c467b 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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 318284b..1a778d2 100644 --- a/document-studio/agents/main/workflows/document-studio-list.json +++ b/document-studio/agents/main/workflows/document-studio-list.json @@ -26,7 +26,8 @@ "description": "Template key", "enum": [ "quote", - "meeting-minutes" + "meeting-minutes", + "dashboard" ] } } @@ -42,7 +43,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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 > 1000) fail(\"too_many_documents\", \"plus de 1000 documents : archivez\");\nconst items = [];\nfor (const id of ids.sort()) {\n let rec;\n try { rec = await loadRecord(id); } catch (e) { if (String(e && e.message).startsWith(\"document_not_found\")) continue; throw e; }\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}\nconst total = items.length;\nreturn {count: Math.min(total, 200), total, truncated: total > 200, items: items.slice(0, 200)};\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 > 1000) fail(\"too_many_documents\", \"plus de 1000 documents : archivez\");\nconst items = [];\nfor (const id of ids.sort()) {\n let rec;\n try { rec = await loadRecord(id); } catch (e) { if (String(e && e.message).startsWith(\"document_not_found\")) continue; throw e; }\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}\nconst total = items.length;\nreturn {count: Math.min(total, 200), total, truncated: total > 200, items: items.slice(0, 200)};\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-mark-authoritative.json b/document-studio/agents/main/workflows/document-studio-mark-authoritative.json index df3a83d..5324be4 100644 --- a/document-studio/agents/main/workflows/document-studio-mark-authoritative.json +++ b/document-studio/agents/main/workflows/document-studio-mark-authoritative.json @@ -103,7 +103,7 @@ "office_inspect_v1" ] }, - "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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"version\", \"confirmation_manuelle\", \"approved_by\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst version = optionalInteger(input.version, \"version\", 1);\nif (version === undefined) fail(\"version_required\");\nconst approvedBy = text(input.approved_by, \"approved_by\", 200, false);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version qui fait foi\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nif (!manifest) fail(\"manifest_not_found\", \"aucune version enregistrée pour \" + id);\nconst entry = manifest.versions.find((e) => e.version === version);\nif (!entry) fail(\"version_not_found\", \"version \" + version);\n// Replay: the version already is authoritative, nothing is written.\nif (entry.status === \"authoritative\") return versionSummary(id, entry, manifest, msha, true);\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + msha + \") ; rien n'a été écrit\");\nif (entry.status !== \"draft\") fail(\"status_invalid\", \"la version \" + version + \" est \" + entry.status + \" : ajoutez une nouvelle version au lieu de la rétablir\");\nconst current = authoritativeOf(manifest);\nif (current && current.version > version) fail(\"status_invalid\", \"la version \" + current.version + \" fait foi et est plus récente : ajoutez une nouvelle version\");\nawait readVersionFile(entry, true);\nconst at = nowIso();\nconst versions = manifest.versions.map((e) => {\n if (e.version === version) return {...e, status: \"authoritative\", supersedes: current ? current.version : null, authoritative_at: at, ...(approvedBy ? {approved_by: approvedBy} : {})};\n if (current && e.version === current.version) return {...e, status: \"superseded\", superseded_by: version, superseded_at: at};\n return e;\n});\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions, history: manifest.history.concat([{at, action: \"marked_authoritative\", version, supersedes: current ? current.version : null, ...(approvedBy ? {approved_by: approvedBy} : {}), note: \"confirmation manuelle donnée\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, versions[version - 1], next, written, false);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"version\", \"confirmation_manuelle\", \"approved_by\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst version = optionalInteger(input.version, \"version\", 1);\nif (version === undefined) fail(\"version_required\");\nconst approvedBy = text(input.approved_by, \"approved_by\", 200, false);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version qui fait foi\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nif (!manifest) fail(\"manifest_not_found\", \"aucune version enregistrée pour \" + id);\nconst entry = manifest.versions.find((e) => e.version === version);\nif (!entry) fail(\"version_not_found\", \"version \" + version);\n// Replay: the version already is authoritative, nothing is written.\nif (entry.status === \"authoritative\") return versionSummary(id, entry, manifest, msha, true);\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + msha + \") ; rien n'a été écrit\");\nif (entry.status !== \"draft\") fail(\"status_invalid\", \"la version \" + version + \" est \" + entry.status + \" : ajoutez une nouvelle version au lieu de la rétablir\");\nconst current = authoritativeOf(manifest);\nif (current && current.version > version) fail(\"status_invalid\", \"la version \" + current.version + \" fait foi et est plus récente : ajoutez une nouvelle version\");\nawait readVersionFile(entry, true);\nconst at = nowIso();\nconst versions = manifest.versions.map((e) => {\n if (e.version === version) return {...e, status: \"authoritative\", supersedes: current ? current.version : null, authoritative_at: at, ...(approvedBy ? {approved_by: approvedBy} : {})};\n if (current && e.version === current.version) return {...e, status: \"superseded\", superseded_by: version, superseded_at: at};\n return e;\n});\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions, history: manifest.history.concat([{at, action: \"marked_authoritative\", version, supersedes: current ? current.version : null, ...(approvedBy ? {approved_by: approvedBy} : {}), note: \"confirmation manuelle donnée\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, versions[version - 1], next, written, false);\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-new-version.json b/document-studio/agents/main/workflows/document-studio-new-version.json index ad62dcc..28f96f4 100644 --- a/document-studio/agents/main/workflows/document-studio-new-version.json +++ b/document-studio/agents/main/workflows/document-studio-new-version.json @@ -83,7 +83,7 @@ "office_inspect_v1" ] }, - "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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"source_path\", \"author\", \"base_version\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst source = sourcePathOf(input.source_path);\nconst author = text(input.author, \"author\", 200, true);\nconst baseVersion = optionalInteger(input.base_version, \"base_version\", 0);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nif (source.startsWith(versionsDir(id) + \"/\")) fail(\"source_invalid\", \"la source ne peut pas être un fichier du dossier des versions\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nconst latest = lastVersion(manifest);\nconst latestN = latest ? latest.version : 0;\nconst file = await readDocx(source, \"source_not_found\");\n// The request fingerprint covers what the caller decided (document, bytes, author), never the base: a replay of ANY earlier\n// write is recognised whatever the manifest became since, and writes nothing.\nconst request = await fingerprint({action: \"new-version\", doc_id: id, sha256: file.sha, author});\nconst replayed = manifest ? manifest.versions.find((e) => e.request_sha256 === request && (baseVersion === undefined || baseVersion === e.version - 1)) : undefined;\nif (replayed) return versionSummary(id, replayed, manifest, msha, true);\nif (baseVersion !== undefined && baseVersion !== latestN) fail(\"base_version_conflict\", \"la dernière version est \" + latestN + \", la demande part de \" + baseVersion + \" ; rien n'a été écrit\");\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + (msha || \"absente\") + \") ; rien n'a été écrit\");\nif (latest && latest.sha256 === file.sha) fail(\"version_unchanged\", \"le fichier est identique à la version \" + latest.version);\n// The first version never goes through office_compare_v1: the engine reads it here, before any write.\nif (!latest) await inspectDocx(file, source);\nconst n = latestN + 1;\nconst dir = versionsDir(id);\nconst short = file.sha.slice(0, 12);\nlet redline = null, changes = null;\nif (latest) {\n const prev = await readVersionFile(latest);\n const cmp = await compareVersions(prev, file, author, n);\n redline = await storeRedline(dir, n, short, cmp.file);\n changes = cmp.changes;\n}\nconst path = dir + \"/v\" + n + \"-\" + short + \".docx\";\nawait storeBytes(path, file.b64, file.sha);\nconst entry = {version: n, sha256: file.sha, bytes: file.bytes, storage_ref: path, redline_ref: redline ? redline.path : null, redline_sha256: redline ? redline.sha256 : null,\n changes, author, created_at: nowIso(), status: \"draft\", supersedes: null, base_version: latest ? latest.version : null, request_sha256: request};\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions: (manifest ? manifest.versions : []).concat([entry]),\n history: (manifest ? manifest.history : []).concat([{at: entry.created_at, action: \"version_added\", version: n, author, note: latest ? \"comparée à la version \" + latest.version : \"première version\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, entry, next, written, false);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"source_path\", \"author\", \"base_version\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst source = sourcePathOf(input.source_path);\nconst author = text(input.author, \"author\", 200, true);\nconst baseVersion = optionalInteger(input.base_version, \"base_version\", 0);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nif (source.startsWith(versionsDir(id) + \"/\")) fail(\"source_invalid\", \"la source ne peut pas être un fichier du dossier des versions\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nconst latest = lastVersion(manifest);\nconst latestN = latest ? latest.version : 0;\nconst file = await readDocx(source, \"source_not_found\");\n// The request fingerprint covers what the caller decided (document, bytes, author), never the base: a replay of ANY earlier\n// write is recognised whatever the manifest became since, and writes nothing.\nconst request = await fingerprint({action: \"new-version\", doc_id: id, sha256: file.sha, author});\nconst replayed = manifest ? manifest.versions.find((e) => e.request_sha256 === request && (baseVersion === undefined || baseVersion === e.version - 1)) : undefined;\nif (replayed) return versionSummary(id, replayed, manifest, msha, true);\nif (baseVersion !== undefined && baseVersion !== latestN) fail(\"base_version_conflict\", \"la dernière version est \" + latestN + \", la demande part de \" + baseVersion + \" ; rien n'a été écrit\");\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + (msha || \"absente\") + \") ; rien n'a été écrit\");\nif (latest && latest.sha256 === file.sha) fail(\"version_unchanged\", \"le fichier est identique à la version \" + latest.version);\n// The first version never goes through office_compare_v1: the engine reads it here, before any write.\nif (!latest) await inspectDocx(file, source);\nconst n = latestN + 1;\nconst dir = versionsDir(id);\nconst short = file.sha.slice(0, 12);\nlet redline = null, changes = null;\nif (latest) {\n const prev = await readVersionFile(latest);\n const cmp = await compareVersions(prev, file, author, n);\n redline = await storeRedline(dir, n, short, cmp.file);\n changes = cmp.changes;\n}\nconst path = dir + \"/v\" + n + \"-\" + short + \".docx\";\nawait storeBytes(path, file.b64, file.sha);\nconst entry = {version: n, sha256: file.sha, bytes: file.bytes, storage_ref: path, redline_ref: redline ? redline.path : null, redline_sha256: redline ? redline.sha256 : null,\n changes, author, created_at: nowIso(), status: \"draft\", supersedes: null, base_version: latest ? latest.version : null, request_sha256: request};\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions: (manifest ? manifest.versions : []).concat([entry]),\n history: (manifest ? manifest.history : []).concat([{at: entry.created_at, action: \"version_added\", version: n, author, note: latest ? \"comparée à la version \" + latest.version : \"première version\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, entry, next, written, false);\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 23f5f6a..06be04d 100644 --- a/document-studio/agents/main/workflows/document-studio-plan.json +++ b/document-studio/agents/main/workflows/document-studio-plan.json @@ -22,7 +22,8 @@ "description": "Template key", "enum": [ "quote", - "meeting-minutes" + "meeting-minutes", + "dashboard" ] }, "locale": { @@ -58,6 +59,10 @@ { "value": "meeting-minutes", "label": "Compte rendu de réunion" + }, + { + "value": "dashboard", + "label": "Tableau de bord" } ] } @@ -73,7 +78,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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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" }, { @@ -89,7 +94,7 @@ { "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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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\");\nif (out.template_key !== undefined && out.template_key !== null && typeof out.template_key !== \"string\") fail(\"llm_output_invalid\", \"template_key doit être une chaîne\");\nconst key = prep.template_key || out.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst list = (v, name) => {\n if (v === undefined || v === null) return [];\n if (!Array.isArray(v) || !v.every((x) => typeof x === \"string\")) fail(\"llm_output_invalid\", name + \" doit être un tableau de chaînes\");\n return v.filter((x) => x.trim()).map((x) => x.trim().slice(0, 300)).slice(0, 20);\n};\nif (out.title !== undefined && out.title !== null && typeof out.title !== \"string\") fail(\"llm_output_invalid\", \"title doit être une chaîne\");\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, \"missing\"), questions: list(out.questions, \"questions\")};\n", + "code": "const TEMPLATES = JSON.parse(\"\\u007b\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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\");\nif (out.template_key !== undefined && out.template_key !== null && typeof out.template_key !== \"string\") fail(\"llm_output_invalid\", \"template_key doit être une chaîne\");\nconst key = prep.template_key || out.template_key;\nif (typeof key !== \"string\" || !TEMPLATES[key]) fail(\"template_unknown\", String(key));\nconst list = (v, name) => {\n if (v === undefined || v === null) return [];\n if (!Array.isArray(v) || !v.every((x) => typeof x === \"string\")) fail(\"llm_output_invalid\", name + \" doit être un tableau de chaînes\");\n return v.filter((x) => x.trim()).map((x) => x.trim().slice(0, 300)).slice(0, 20);\n};\nif (out.title !== undefined && out.title !== null && typeof out.title !== \"string\") fail(\"llm_output_invalid\", \"title doit être une chaîne\");\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, \"missing\"), questions: list(out.questions, \"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 3ed7e43..ada9815 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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 rejectUnsafeKeys(p, \"profil\");\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 rejectUnsafeKeys(p, \"profil\");\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 2cf538e..ed5c970 100644 --- a/document-studio/agents/main/workflows/document-studio-publish.json +++ b/document-studio/agents/main/workflows/document-studio-publish.json @@ -75,7 +75,7 @@ "recipe--application_data_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\\\", \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 rejectUnsafeKeys(p, \"profil\");\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// The company profile comes from the cib-profile record (native broker, same read call as cib-profile-read). When that record is\n// absent, refused to this caller or unreadable, the Storage copy written by document-studio-profile-save is used, as before.\nlet PROFILE_SOURCE = \"storage\";\nasync function brokerProfileBody() {\n let response;\n try { response = await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: \"cib-profile\", record_key: \"company-profile\"}); } catch (e) { return null; }\n if (isObject(response) && isObject(response.error)) return null;\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== \"cib-profile\" || item.key !== \"company-profile\" || !isObject(item.data)) return null;\n const p = item.permissions;\n if (!isObject(p) || p.can_read !== true) return null;\n return item.data;\n}\nasync function loadProfile() {\n const body = await brokerProfileBody();\n if (body !== null) {\n try { const projected = projectProfile(normalizeProfile(body)); PROFILE_SOURCE = \"cib-profile\"; return projected; } catch (e) { /* unreadable record: fall back to Storage */ }\n }\n PROFILE_SOURCE = \"storage\";\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"json_corrupt\")) fail(\"profile_corrupt\", \"profile.json illisible\");\n if (!m.startsWith(\"storage_not_found\")) throw e;\n stored = null;\n }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte dans cib-profile ou par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\n// A folder per attempt: a render that loses a race never overwrites the file of another attempt.\nfunction attemptTag(f) { const sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase().replace(/[^0-9a-f]/g, \"\").slice(0, 12) : \"\"; return sha || shortSuffix(); }\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 // Read the stored file back whatever the mode: its fingerprint and size must match what the renderer announced.\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"render_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"render_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n if (typeof f.bytes === \"number\" && f.bytes !== stored.length) fail(\"render_integrity_failed\", path + \" : taille différente de celle annoncée\");\n sha = actual;\n return {path, sha256: sha, bytes: stored.length, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n const seen = new Set();\n const list = res.previews;\n if (!Number.isInteger(res.pages) || res.pages < 1) fail(\"render_invalid\", \"pages doit être un entier ≥ 1\");\n if (!Array.isArray(list) || list.length !== res.pages) fail(\"render_invalid\", \"le rendu doit fournir exactement \" + res.pages + \" aperçu(s)\");\n // The renderer's file names are never trusted: one fixed name per page.\n for (const p of list) {\n if (!isObject(p) || !Number.isInteger(p.page) || p.page < 1 || (Number.isInteger(res.pages) && p.page > res.pages)) fail(\"render_invalid\", \"numéro de page d'aperçu invalide\");\n if (seen.has(p.page)) fail(\"render_invalid\", \"page d'aperçu en double : \" + p.page);\n seen.add(p.page);\n const stored = await storeFile(dir + \"/page-\" + p.page + \".png\", p);\n previews.push({page: p.page, path: stored.path, sha256: stored.sha256});\n }\n for (let n = 1; n <= res.pages; n++) if (!seen.has(n)) fail(\"render_invalid\", \"aperçu manquant : page \" + 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 = clock().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); if (last.startsWith(\"storage_unavailable\")) throw e; 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();\n// What was approved is what is issued: the last render carries the fingerprints of its brand and data.\nconst approved = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nif (!approved || typeof approved.profile_sha256 !== \"string\" || typeof approved.data_sha256 !== \"string\") fail(\"render_outdated\", \"ce rendu ne porte pas d'empreintes : rendez et approuvez à nouveau\");\nif (approved.profile_sha256 !== await fingerprint(profile)) fail(\"profile_changed\", \"la charte a changé depuis le rendu approuvé : rendez et approuvez à nouveau\");\nif (approved.data_sha256 !== await fingerprint(normalizeData(rec.template_key, rec.data, id))) fail(\"data_changed\", \"les données ont changé depuis le rendu approuvé : rendez et approuvez à nouveau\");\nif (rec.number) {\n // A number reserved in a previous year is abandoned, never reused: a new one is reserved in the current year.\n const m = /^[A-Z]+-(\\d{4})-\\d+$/.exec(String(rec.number));\n if (!m || Number(m[1]) !== clock().getUTCFullYear()) {\n rec.history.push({at: nowIso(), action: \"number_abandoned\", note: String(rec.number)});\n rec.number = null;\n } else {\n // The token must still name this document: the reservation is not atomic, so it is read back on every retry.\n const seqm = /-(\\d{4,})$/.exec(String(rec.number));\n let token = null;\n try { token = await readJson(ROOT + \"/numbers/\" + rec.template_key + \"/\" + m[1] + \"/\" + seqm[1] + \".json\"); }\n catch (e) { if (!String(e && e.message).startsWith(\"storage_not_found\") && !String(e && e.message).startsWith(\"json_corrupt\")) throw e; }\n if (!isObject(token) || token.doc_id !== rec.doc_id) {\n rec.history.push({at: nowIso(), action: \"number_abandoned\", note: String(rec.number) + \" (jeton d'un autre document)\"});\n rec.number = null;\n }\n }\n}\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 + \"-\" + attemptTag(res.file) + \".pdf\", res.file);\nconst previews = await storePreviews(dir + \"/r\" + revision + \"-\" + attemptTag(res.file), res);\nconst at = nowIso();\nrec.status = \"issued\";\nrec.revision = revision;\nrec.renders.push({revision, mode: \"final\", profile_sha256: approved.profile_sha256, data_sha256: approved.data_sha256, 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), profile_source: PROFILE_SOURCE};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Tableau de bord Activité 2026\\\\\\\",\\\\n \\\\\\\"titles\\\\\\\": \\u007b\\\\n \\\\\\\"bar\\\\\\\": \\\\\\\"Résultat mensuel\\\\\\\",\\\\n \\\\\\\"line\\\\\\\": \\\\\\\"Tendance\\\\\\\",\\\\n \\\\\\\"pie\\\\\\\": \\\\\\\"Répartition du chiffre d'affaires\\\\\\\",\\\\n \\\\\\\"gantt\\\\\\\": \\\\\\\"Plan de projet\\\\\\\",\\\\n \\\\\\\"org\\\\\\\": \\\\\\\"Organisation\\\\\\\",\\\\n \\\\\\\"process\\\\\\\": \\\\\\\"Traitement d'une demande\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"bar\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\": [\\\\n \\\\\\\"janv.\\\\\\\",\\\\n \\\\\\\"févr.\\\\\\\",\\\\n \\\\\\\"mars\\\\\\\",\\\\n \\\\\\\"avr.\\\\\\\",\\\\n \\\\\\\"mai\\\\\\\",\\\\n \\\\\\\"juin\\\\\\\"\\\\n ],\\\\n \\\\\\\"series\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Chiffre d'affaires (k€)\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 1250.5,\\\\n 1380,\\\\n 1520,\\\\n 1475,\\\\n 1680,\\\\n 1904.25\\\\n ]\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Résultat (k€)\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 220,\\\\n -150.5,\\\\n 310,\\\\n -80,\\\\n 405,\\\\n 520\\\\n ]\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"line\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\": [\\\\n \\\\\\\"janv.\\\\\\\",\\\\n \\\\\\\"févr.\\\\\\\",\\\\n \\\\\\\"mars\\\\\\\",\\\\n \\\\\\\"avr.\\\\\\\",\\\\n \\\\\\\"mai\\\\\\\",\\\\n \\\\\\\"juin\\\\\\\"\\\\n ],\\\\n \\\\\\\"series\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Visites\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 12000,\\\\n 13500,\\\\n 15000,\\\\n 14200,\\\\n 16800,\\\\n 19000\\\\n ]\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Commandes\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 980,\\\\n 1040,\\\\n 1100,\\\\n 1080,\\\\n 1210,\\\\n 1330\\\\n ]\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"pie\\\\\\\",\\\\n \\\\\\\"parts\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Conseil\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 3800\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Formation\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 2400\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Licences\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 1700\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Intégration\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 1300\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Support\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 800\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"gantt\\\\\\\",\\\\n \\\\\\\"weeks\\\\\\\": 12,\\\\n \\\\\\\"phases\\\\\\\": [\\\\n \\\\\\\"Cadrage\\\\\\\",\\\\n \\\\\\\"Construction\\\\\\\",\\\\n \\\\\\\"Recette\\\\\\\"\\\\n ],\\\\n \\\\\\\"tasks\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cadrage du besoin\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 0,\\\\n \\\\\\\"duration\\\\\\\": 2,\\\\n \\\\\\\"phase\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Ateliers utilisateurs\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 1,\\\\n \\\\\\\"duration\\\\\\\": 3,\\\\n \\\\\\\"phase\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Socle technique\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 3,\\\\n \\\\\\\"duration\\\\\\\": 4,\\\\n \\\\\\\"phase\\\\\\\": 1\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Interfaces principales\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 5,\\\\n \\\\\\\"duration\\\\\\\": 5,\\\\n \\\\\\\"phase\\\\\\\": 1\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Recette métier\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 9,\\\\n \\\\\\\"duration\\\\\\\": 2,\\\\n \\\\\\\"phase\\\\\\\": 2\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Mise en production\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 11,\\\\n \\\\\\\"duration\\\\\\\": 1,\\\\n \\\\\\\"phase\\\\\\\": 2\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"org\\\\\\\",\\\\n \\\\\\\"nodes\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n1\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Hélène Marchand\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Directrice générale\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n2\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Julien Bœuf\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Directeur technique\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n1\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n3\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Durand\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Directrice commerciale\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n1\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n4\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Inès Garnier\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Développement\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n2\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n5\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Théo Bernard\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Données\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n2\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n6\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Maël Roche\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Grands comptes\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n3\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"process\\\\\\\",\\\\n \\\\\\\"steps\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Demande reçue\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"start\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Qualification\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Dossier complet ?\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"decision\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Chiffrage\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Validation interne\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Envoi du devis\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Signature client\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Clôture\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"end\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du tableau de bord\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"title\\\\\\\",\\\\n \\\\\\\"titles\\\\\\\",\\\\n \\\\\\\"bar\\\\\\\",\\\\n \\\\\\\"line\\\\\\\",\\\\n \\\\\\\"pie\\\\\\\",\\\\n \\\\\\\"gantt\\\\\\\",\\\\n \\\\\\\"org\\\\\\\",\\\\n \\\\\\\"process\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"titles\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"bar\\\\\\\",\\\\n \\\\\\\"line\\\\\\\",\\\\n \\\\\\\"pie\\\\\\\",\\\\n \\\\\\\"gantt\\\\\\\",\\\\n \\\\\\\"org\\\\\\\",\\\\n \\\\\\\"process\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/bar\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/line\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/pie\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/gantt\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/org\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/process\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"label\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"minLength\\\\\\\": 1,\\\\n \\\\\\\"maxLength\\\\\\\": 60,\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^[^\\\\\\\\\\\\\\\\x00-\\\\\\\\\\\\\\\\x1F\\\\\\\\\\\\\\\\x7F]+$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"number\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": -1000000000000,\\\\n \\\\\\\"maximum\\\\\\\": 1000000000000,\\\\n \\\\\\\"anyOf\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"const\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"minimum\\\\\\\": 0.01\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"maximum\\\\\\\": -0.01\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\",\\\\n \\\\\\\"series\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"bar\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"categories\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"series\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 5,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"values\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"values\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/number\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\",\\\\n \\\\\\\"series\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"line\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"categories\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"series\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 5,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"values\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"values\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/number\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"parts\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"pie\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"parts\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 10,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"value\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"value\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0,\\\\n \\\\\\\"maximum\\\\\\\": 1000000000000,\\\\n \\\\\\\"anyOf\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"const\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"minimum\\\\\\\": 0.01\\\\n \\u007d\\\\n ]\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"weeks\\\\\\\",\\\\n \\\\\\\"phases\\\\\\\",\\\\n \\\\\\\"tasks\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"gantt\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"weeks\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"integer\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 1,\\\\n \\\\\\\"maximum\\\\\\\": 104\\\\n \\u007d,\\\\n \\\\\\\"phases\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 5,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"tasks\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 25,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"start\\\\\\\",\\\\n \\\\\\\"duration\\\\\\\",\\\\n \\\\\\\"phase\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"start\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0,\\\\n \\\\\\\"maximum\\\\\\\": 104,\\\\n \\\\\\\"anyOf\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"const\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"minimum\\\\\\\": 0.01\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"duration\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0.01,\\\\n \\\\\\\"maximum\\\\\\\": 104\\\\n \\u007d,\\\\n \\\\\\\"phase\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"integer\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0,\\\\n \\\\\\\"maximum\\\\\\\": 4\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"nodes\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"org\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"nodes\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 30,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"id\\\\\\\",\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"id\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"minLength\\\\\\\": 1,\\\\n \\\\\\\"maxLength\\\\\\\": 32\\\\n \\u007d,\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"title\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"parent\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"maxLength\\\\\\\": 32\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"steps\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"process\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"steps\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 12,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"label\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"label\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"kind\\\\\\\": \\u007b\\\\n \\\\\\\"enum\\\\\\\": [\\\\n \\\\\\\"start\\\\\\\",\\\\n \\\\\\\"step\\\\\\\",\\\\n \\\\\\\"decision\\\\\\\",\\\\n \\\\\\\"end\\\\\\\"\\\\n ]\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `dashboard` : les six graphiques chart/v1, une page chacun.\\\\n// Les donnees passent en JSON par reference (`| json` entre crochets), jamais dans le code.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/charts.typ\\\\\\\": bar-chart, line-chart, pie-chart, gantt-chart, org-chart, process-flow\\\\n\\\\n#set page(paper: brand.page.paper, margin: brand.page.margins)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#show heading.where(level: 1): set text(fill: brand.colors.primary, size: 17pt)\\\\n\\\\n#heading(level: 1)[\\u007b\\u007b .data.title \\u007d\\u007d]\\\\n#v(4mm)\\\\n*\\u007b\\u007b .data.titles.bar \\u007d\\u007d*\\\\n#v(2mm)\\\\n#bar-chart([\\u007b\\u007b .data.bar | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.line \\u007d\\u007d*\\\\n#v(2mm)\\\\n#line-chart([\\u007b\\u007b .data.line | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.pie \\u007d\\u007d*\\\\n#v(2mm)\\\\n#pie-chart([\\u007b\\u007b .data.pie | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.gantt \\u007d\\u007d*\\\\n#v(2mm)\\\\n#gantt-chart([\\u007b\\u007b .data.gantt | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.org \\u007d\\u007d*\\\\n#v(2mm)\\\\n#org-chart([\\u007b\\u007b .data.org | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.process \\u007d\\u007d*\\\\n#v(2mm)\\\\n#process-flow([\\u007b\\u007b .data.process | json \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"dashboard\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Tableau de bord\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\\\\\",\\\\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 ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/charts.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 6\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 rejectUnsafeKeys(p, \"profil\");\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// The company profile comes from the cib-profile record (native broker, same read call as cib-profile-read). When that record is\n// absent, refused to this caller or unreadable, the Storage copy written by document-studio-profile-save is used, as before.\nlet PROFILE_SOURCE = \"storage\";\nasync function brokerProfileBody() {\n let response;\n try { response = await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: \"cib-profile\", record_key: \"company-profile\"}); } catch (e) { return null; }\n if (isObject(response) && isObject(response.error)) return null;\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== \"cib-profile\" || item.key !== \"company-profile\" || !isObject(item.data)) return null;\n const p = item.permissions;\n if (!isObject(p) || p.can_read !== true) return null;\n return item.data;\n}\nasync function loadProfile() {\n const body = await brokerProfileBody();\n if (body !== null) {\n try { const projected = projectProfile(normalizeProfile(body)); PROFILE_SOURCE = \"cib-profile\"; return projected; } catch (e) { /* unreadable record: fall back to Storage */ }\n }\n PROFILE_SOURCE = \"storage\";\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"json_corrupt\")) fail(\"profile_corrupt\", \"profile.json illisible\");\n if (!m.startsWith(\"storage_not_found\")) throw e;\n stored = null;\n }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte dans cib-profile ou par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\n// A folder per attempt: a render that loses a race never overwrites the file of another attempt.\nfunction attemptTag(f) { const sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase().replace(/[^0-9a-f]/g, \"\").slice(0, 12) : \"\"; return sha || shortSuffix(); }\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 // Read the stored file back whatever the mode: its fingerprint and size must match what the renderer announced.\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"render_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"render_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n if (typeof f.bytes === \"number\" && f.bytes !== stored.length) fail(\"render_integrity_failed\", path + \" : taille différente de celle annoncée\");\n sha = actual;\n return {path, sha256: sha, bytes: stored.length, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n const seen = new Set();\n const list = res.previews;\n if (!Number.isInteger(res.pages) || res.pages < 1) fail(\"render_invalid\", \"pages doit être un entier ≥ 1\");\n if (!Array.isArray(list) || list.length !== res.pages) fail(\"render_invalid\", \"le rendu doit fournir exactement \" + res.pages + \" aperçu(s)\");\n // The renderer's file names are never trusted: one fixed name per page.\n for (const p of list) {\n if (!isObject(p) || !Number.isInteger(p.page) || p.page < 1 || (Number.isInteger(res.pages) && p.page > res.pages)) fail(\"render_invalid\", \"numéro de page d'aperçu invalide\");\n if (seen.has(p.page)) fail(\"render_invalid\", \"page d'aperçu en double : \" + p.page);\n seen.add(p.page);\n const stored = await storeFile(dir + \"/page-\" + p.page + \".png\", p);\n previews.push({page: p.page, path: stored.path, sha256: stored.sha256});\n }\n for (let n = 1; n <= res.pages; n++) if (!seen.has(n)) fail(\"render_invalid\", \"aperçu manquant : page \" + 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 = clock().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); if (last.startsWith(\"storage_unavailable\")) throw e; 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();\n// What was approved is what is issued: the last render carries the fingerprints of its brand and data.\nconst approved = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nif (!approved || typeof approved.profile_sha256 !== \"string\" || typeof approved.data_sha256 !== \"string\") fail(\"render_outdated\", \"ce rendu ne porte pas d'empreintes : rendez et approuvez à nouveau\");\nif (approved.profile_sha256 !== await fingerprint(profile)) fail(\"profile_changed\", \"la charte a changé depuis le rendu approuvé : rendez et approuvez à nouveau\");\nif (approved.data_sha256 !== await fingerprint(normalizeData(rec.template_key, rec.data, id))) fail(\"data_changed\", \"les données ont changé depuis le rendu approuvé : rendez et approuvez à nouveau\");\nif (rec.number) {\n // A number reserved in a previous year is abandoned, never reused: a new one is reserved in the current year.\n const m = /^[A-Z]+-(\\d{4})-\\d+$/.exec(String(rec.number));\n if (!m || Number(m[1]) !== clock().getUTCFullYear()) {\n rec.history.push({at: nowIso(), action: \"number_abandoned\", note: String(rec.number)});\n rec.number = null;\n } else {\n // The token must still name this document: the reservation is not atomic, so it is read back on every retry.\n const seqm = /-(\\d{4,})$/.exec(String(rec.number));\n let token = null;\n try { token = await readJson(ROOT + \"/numbers/\" + rec.template_key + \"/\" + m[1] + \"/\" + seqm[1] + \".json\"); }\n catch (e) { if (!String(e && e.message).startsWith(\"storage_not_found\") && !String(e && e.message).startsWith(\"json_corrupt\")) throw e; }\n if (!isObject(token) || token.doc_id !== rec.doc_id) {\n rec.history.push({at: nowIso(), action: \"number_abandoned\", note: String(rec.number) + \" (jeton d'un autre document)\"});\n rec.number = null;\n }\n }\n}\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 + \"-\" + attemptTag(res.file) + \".pdf\", res.file);\nconst previews = await storePreviews(dir + \"/r\" + revision + \"-\" + attemptTag(res.file), res);\nconst at = nowIso();\nrec.status = \"issued\";\nrec.revision = revision;\nrec.renders.push({revision, mode: \"final\", profile_sha256: approved.profile_sha256, data_sha256: approved.data_sha256, 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), profile_source: PROFILE_SOURCE};\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 8db227c..6bf42ed 100644 --- a/document-studio/agents/main/workflows/document-studio-render.json +++ b/document-studio/agents/main/workflows/document-studio-render.json @@ -54,7 +54,7 @@ "recipe--application_data_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\\\", \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 rejectUnsafeKeys(p, \"profil\");\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// The company profile comes from the cib-profile record (native broker, same read call as cib-profile-read). When that record is\n// absent, refused to this caller or unreadable, the Storage copy written by document-studio-profile-save is used, as before.\nlet PROFILE_SOURCE = \"storage\";\nasync function brokerProfileBody() {\n let response;\n try { response = await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: \"cib-profile\", record_key: \"company-profile\"}); } catch (e) { return null; }\n if (isObject(response) && isObject(response.error)) return null;\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== \"cib-profile\" || item.key !== \"company-profile\" || !isObject(item.data)) return null;\n const p = item.permissions;\n if (!isObject(p) || p.can_read !== true) return null;\n return item.data;\n}\nasync function loadProfile() {\n const body = await brokerProfileBody();\n if (body !== null) {\n try { const projected = projectProfile(normalizeProfile(body)); PROFILE_SOURCE = \"cib-profile\"; return projected; } catch (e) { /* unreadable record: fall back to Storage */ }\n }\n PROFILE_SOURCE = \"storage\";\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"json_corrupt\")) fail(\"profile_corrupt\", \"profile.json illisible\");\n if (!m.startsWith(\"storage_not_found\")) throw e;\n stored = null;\n }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte dans cib-profile ou par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\n// A folder per attempt: a render that loses a race never overwrites the file of another attempt.\nfunction attemptTag(f) { const sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase().replace(/[^0-9a-f]/g, \"\").slice(0, 12) : \"\"; return sha || shortSuffix(); }\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 // Read the stored file back whatever the mode: its fingerprint and size must match what the renderer announced.\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"render_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"render_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n if (typeof f.bytes === \"number\" && f.bytes !== stored.length) fail(\"render_integrity_failed\", path + \" : taille différente de celle annoncée\");\n sha = actual;\n return {path, sha256: sha, bytes: stored.length, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n const seen = new Set();\n const list = res.previews;\n if (!Number.isInteger(res.pages) || res.pages < 1) fail(\"render_invalid\", \"pages doit être un entier ≥ 1\");\n if (!Array.isArray(list) || list.length !== res.pages) fail(\"render_invalid\", \"le rendu doit fournir exactement \" + res.pages + \" aperçu(s)\");\n // The renderer's file names are never trusted: one fixed name per page.\n for (const p of list) {\n if (!isObject(p) || !Number.isInteger(p.page) || p.page < 1 || (Number.isInteger(res.pages) && p.page > res.pages)) fail(\"render_invalid\", \"numéro de page d'aperçu invalide\");\n if (seen.has(p.page)) fail(\"render_invalid\", \"page d'aperçu en double : \" + p.page);\n seen.add(p.page);\n const stored = await storeFile(dir + \"/page-\" + p.page + \".png\", p);\n previews.push({page: p.page, path: stored.path, sha256: stored.sha256});\n }\n for (let n = 1; n <= res.pages; n++) if (!seen.has(n)) fail(\"render_invalid\", \"aperçu manquant : page \" + 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 rejectUnsafeKeys(input.data_patch, \"data_patch\");\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 + \"-\" + attemptTag(res.file);\nconst file = await storeFile(dir + \"/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\", profile_sha256: await fingerprint(profile), data_sha256: await fingerprint(data), file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nawait saveRecord(rec);\nreturn {...summarize(rec), profile_source: PROFILE_SOURCE};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Tableau de bord Activité 2026\\\\\\\",\\\\n \\\\\\\"titles\\\\\\\": \\u007b\\\\n \\\\\\\"bar\\\\\\\": \\\\\\\"Résultat mensuel\\\\\\\",\\\\n \\\\\\\"line\\\\\\\": \\\\\\\"Tendance\\\\\\\",\\\\n \\\\\\\"pie\\\\\\\": \\\\\\\"Répartition du chiffre d'affaires\\\\\\\",\\\\n \\\\\\\"gantt\\\\\\\": \\\\\\\"Plan de projet\\\\\\\",\\\\n \\\\\\\"org\\\\\\\": \\\\\\\"Organisation\\\\\\\",\\\\n \\\\\\\"process\\\\\\\": \\\\\\\"Traitement d'une demande\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"bar\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\": [\\\\n \\\\\\\"janv.\\\\\\\",\\\\n \\\\\\\"févr.\\\\\\\",\\\\n \\\\\\\"mars\\\\\\\",\\\\n \\\\\\\"avr.\\\\\\\",\\\\n \\\\\\\"mai\\\\\\\",\\\\n \\\\\\\"juin\\\\\\\"\\\\n ],\\\\n \\\\\\\"series\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Chiffre d'affaires (k€)\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 1250.5,\\\\n 1380,\\\\n 1520,\\\\n 1475,\\\\n 1680,\\\\n 1904.25\\\\n ]\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Résultat (k€)\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 220,\\\\n -150.5,\\\\n 310,\\\\n -80,\\\\n 405,\\\\n 520\\\\n ]\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"line\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\": [\\\\n \\\\\\\"janv.\\\\\\\",\\\\n \\\\\\\"févr.\\\\\\\",\\\\n \\\\\\\"mars\\\\\\\",\\\\n \\\\\\\"avr.\\\\\\\",\\\\n \\\\\\\"mai\\\\\\\",\\\\n \\\\\\\"juin\\\\\\\"\\\\n ],\\\\n \\\\\\\"series\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Visites\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 12000,\\\\n 13500,\\\\n 15000,\\\\n 14200,\\\\n 16800,\\\\n 19000\\\\n ]\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Commandes\\\\\\\",\\\\n \\\\\\\"values\\\\\\\": [\\\\n 980,\\\\n 1040,\\\\n 1100,\\\\n 1080,\\\\n 1210,\\\\n 1330\\\\n ]\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"pie\\\\\\\",\\\\n \\\\\\\"parts\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Conseil\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 3800\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Formation\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 2400\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Licences\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 1700\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Intégration\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 1300\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Support\\\\\\\",\\\\n \\\\\\\"value\\\\\\\": 800\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"gantt\\\\\\\",\\\\n \\\\\\\"weeks\\\\\\\": 12,\\\\n \\\\\\\"phases\\\\\\\": [\\\\n \\\\\\\"Cadrage\\\\\\\",\\\\n \\\\\\\"Construction\\\\\\\",\\\\n \\\\\\\"Recette\\\\\\\"\\\\n ],\\\\n \\\\\\\"tasks\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Cadrage du besoin\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 0,\\\\n \\\\\\\"duration\\\\\\\": 2,\\\\n \\\\\\\"phase\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Ateliers utilisateurs\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 1,\\\\n \\\\\\\"duration\\\\\\\": 3,\\\\n \\\\\\\"phase\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Socle technique\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 3,\\\\n \\\\\\\"duration\\\\\\\": 4,\\\\n \\\\\\\"phase\\\\\\\": 1\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Interfaces principales\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 5,\\\\n \\\\\\\"duration\\\\\\\": 5,\\\\n \\\\\\\"phase\\\\\\\": 1\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Recette métier\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 9,\\\\n \\\\\\\"duration\\\\\\\": 2,\\\\n \\\\\\\"phase\\\\\\\": 2\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Mise en production\\\\\\\",\\\\n \\\\\\\"start\\\\\\\": 11,\\\\n \\\\\\\"duration\\\\\\\": 1,\\\\n \\\\\\\"phase\\\\\\\": 2\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"org\\\\\\\",\\\\n \\\\\\\"nodes\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n1\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Hélène Marchand\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Directrice générale\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n2\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Julien Bœuf\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Directeur technique\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n1\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n3\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Durand\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Directrice commerciale\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n1\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n4\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Inès Garnier\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Développement\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n2\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n5\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Théo Bernard\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Données\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n2\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"id\\\\\\\": \\\\\\\"n6\\\\\\\",\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Maël Roche\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Grands comptes\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\": \\\\\\\"n3\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"process\\\\\\\",\\\\n \\\\\\\"steps\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Demande reçue\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"start\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Qualification\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Dossier complet ?\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"decision\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Chiffrage\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Validation interne\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Envoi du devis\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Signature client\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"step\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"label\\\\\\\": \\\\\\\"Clôture\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"end\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du tableau de bord\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"title\\\\\\\",\\\\n \\\\\\\"titles\\\\\\\",\\\\n \\\\\\\"bar\\\\\\\",\\\\n \\\\\\\"line\\\\\\\",\\\\n \\\\\\\"pie\\\\\\\",\\\\n \\\\\\\"gantt\\\\\\\",\\\\n \\\\\\\"org\\\\\\\",\\\\n \\\\\\\"process\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"titles\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"bar\\\\\\\",\\\\n \\\\\\\"line\\\\\\\",\\\\n \\\\\\\"pie\\\\\\\",\\\\n \\\\\\\"gantt\\\\\\\",\\\\n \\\\\\\"org\\\\\\\",\\\\n \\\\\\\"process\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/bar\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/line\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/pie\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/gantt\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/org\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/process\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"$defs\\\\\\\": \\u007b\\\\n \\\\\\\"label\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"minLength\\\\\\\": 1,\\\\n \\\\\\\"maxLength\\\\\\\": 60,\\\\n \\\\\\\"pattern\\\\\\\": \\\\\\\"^[^\\\\\\\\\\\\\\\\x00-\\\\\\\\\\\\\\\\x1F\\\\\\\\\\\\\\\\x7F]+$\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"number\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": -1000000000000,\\\\n \\\\\\\"maximum\\\\\\\": 1000000000000,\\\\n \\\\\\\"anyOf\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"const\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"minimum\\\\\\\": 0.01\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"maximum\\\\\\\": -0.01\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"bar\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\",\\\\n \\\\\\\"series\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"bar\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"categories\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"series\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 5,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"values\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"values\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/number\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"line\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"categories\\\\\\\",\\\\n \\\\\\\"series\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"line\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"categories\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"series\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 5,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"values\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"values\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 24,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/number\\\\\\\"\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"pie\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"parts\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"pie\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"parts\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 10,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"value\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"value\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0,\\\\n \\\\\\\"maximum\\\\\\\": 1000000000000,\\\\n \\\\\\\"anyOf\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"const\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"minimum\\\\\\\": 0.01\\\\n \\u007d\\\\n ]\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"gantt\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"weeks\\\\\\\",\\\\n \\\\\\\"phases\\\\\\\",\\\\n \\\\\\\"tasks\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"gantt\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"weeks\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"integer\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 1,\\\\n \\\\\\\"maximum\\\\\\\": 104\\\\n \\u007d,\\\\n \\\\\\\"phases\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 5,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"tasks\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 25,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"start\\\\\\\",\\\\n \\\\\\\"duration\\\\\\\",\\\\n \\\\\\\"phase\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"start\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0,\\\\n \\\\\\\"maximum\\\\\\\": 104,\\\\n \\\\\\\"anyOf\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"const\\\\\\\": 0\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"minimum\\\\\\\": 0.01\\\\n \\u007d\\\\n ]\\\\n \\u007d,\\\\n \\\\\\\"duration\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"number\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0.01,\\\\n \\\\\\\"maximum\\\\\\\": 104\\\\n \\u007d,\\\\n \\\\\\\"phase\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"integer\\\\\\\",\\\\n \\\\\\\"minimum\\\\\\\": 0,\\\\n \\\\\\\"maximum\\\\\\\": 4\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"org\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"nodes\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"org\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"nodes\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 30,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"id\\\\\\\",\\\\n \\\\\\\"name\\\\\\\",\\\\n \\\\\\\"parent\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"id\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"minLength\\\\\\\": 1,\\\\n \\\\\\\"maxLength\\\\\\\": 32\\\\n \\u007d,\\\\n \\\\\\\"name\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"title\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"parent\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\",\\\\n \\\\\\\"maxLength\\\\\\\": 32\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"process\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"type\\\\\\\",\\\\n \\\\\\\"steps\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\u007b\\\\n \\\\\\\"const\\\\\\\": \\\\\\\"process\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"steps\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"maxItems\\\\\\\": 12,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\n \\\\\\\"label\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\"\\\\n ],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"label\\\\\\\": \\u007b\\\\n \\\\\\\"$ref\\\\\\\": \\\\\\\"#/$defs/label\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"kind\\\\\\\": \\u007b\\\\n \\\\\\\"enum\\\\\\\": [\\\\n \\\\\\\"start\\\\\\\",\\\\n \\\\\\\"step\\\\\\\",\\\\n \\\\\\\"decision\\\\\\\",\\\\n \\\\\\\"end\\\\\\\"\\\\n ]\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `dashboard` : les six graphiques chart/v1, une page chacun.\\\\n// Les donnees passent en JSON par reference (`| json` entre crochets), jamais dans le code.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/charts.typ\\\\\\\": bar-chart, line-chart, pie-chart, gantt-chart, org-chart, process-flow\\\\n\\\\n#set page(paper: brand.page.paper, margin: brand.page.margins)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n#show heading.where(level: 1): set text(fill: brand.colors.primary, size: 17pt)\\\\n\\\\n#heading(level: 1)[\\u007b\\u007b .data.title \\u007d\\u007d]\\\\n#v(4mm)\\\\n*\\u007b\\u007b .data.titles.bar \\u007d\\u007d*\\\\n#v(2mm)\\\\n#bar-chart([\\u007b\\u007b .data.bar | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.line \\u007d\\u007d*\\\\n#v(2mm)\\\\n#line-chart([\\u007b\\u007b .data.line | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.pie \\u007d\\u007d*\\\\n#v(2mm)\\\\n#pie-chart([\\u007b\\u007b .data.pie | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.gantt \\u007d\\u007d*\\\\n#v(2mm)\\\\n#gantt-chart([\\u007b\\u007b .data.gantt | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.org \\u007d\\u007d*\\\\n#v(2mm)\\\\n#org-chart([\\u007b\\u007b .data.org | json \\u007d\\u007d])\\\\n\\\\n#pagebreak()\\\\n*\\u007b\\u007b .data.titles.process \\u007d\\u007d*\\\\n#v(2mm)\\\\n#process-flow([\\u007b\\u007b .data.process | json \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"dashboard\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Tableau de bord\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\\\\\",\\\\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 ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/charts.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 6\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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 rejectUnsafeKeys(p, \"profil\");\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// The company profile comes from the cib-profile record (native broker, same read call as cib-profile-read). When that record is\n// absent, refused to this caller or unreadable, the Storage copy written by document-studio-profile-save is used, as before.\nlet PROFILE_SOURCE = \"storage\";\nasync function brokerProfileBody() {\n let response;\n try { response = await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: \"cib-profile\", record_key: \"company-profile\"}); } catch (e) { return null; }\n if (isObject(response) && isObject(response.error)) return null;\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!isObject(item) || item.namespace !== \"cib-profile\" || item.key !== \"company-profile\" || !isObject(item.data)) return null;\n const p = item.permissions;\n if (!isObject(p) || p.can_read !== true) return null;\n return item.data;\n}\nasync function loadProfile() {\n const body = await brokerProfileBody();\n if (body !== null) {\n try { const projected = projectProfile(normalizeProfile(body)); PROFILE_SOURCE = \"cib-profile\"; return projected; } catch (e) { /* unreadable record: fall back to Storage */ }\n }\n PROFILE_SOURCE = \"storage\";\n let stored = null;\n try { stored = await readJson(ROOT + \"/profile.json\"); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"json_corrupt\")) fail(\"profile_corrupt\", \"profile.json illisible\");\n if (!m.startsWith(\"storage_not_found\")) throw e;\n stored = null;\n }\n if (!isObject(stored)) fail(\"profile_missing\", \"enregistrez la charte dans cib-profile ou par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\n// A folder per attempt: a render that loses a race never overwrites the file of another attempt.\nfunction attemptTag(f) { const sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase().replace(/[^0-9a-f]/g, \"\").slice(0, 12) : \"\"; return sha || shortSuffix(); }\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 // Read the stored file back whatever the mode: its fingerprint and size must match what the renderer announced.\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"render_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"render_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n if (typeof f.bytes === \"number\" && f.bytes !== stored.length) fail(\"render_integrity_failed\", path + \" : taille différente de celle annoncée\");\n sha = actual;\n return {path, sha256: sha, bytes: stored.length, mime: typeof f.mime_type === \"string\" ? f.mime_type : \"application/octet-stream\"};\n}\nasync function storePreviews(dir, res) {\n const previews = [];\n const seen = new Set();\n const list = res.previews;\n if (!Number.isInteger(res.pages) || res.pages < 1) fail(\"render_invalid\", \"pages doit être un entier ≥ 1\");\n if (!Array.isArray(list) || list.length !== res.pages) fail(\"render_invalid\", \"le rendu doit fournir exactement \" + res.pages + \" aperçu(s)\");\n // The renderer's file names are never trusted: one fixed name per page.\n for (const p of list) {\n if (!isObject(p) || !Number.isInteger(p.page) || p.page < 1 || (Number.isInteger(res.pages) && p.page > res.pages)) fail(\"render_invalid\", \"numéro de page d'aperçu invalide\");\n if (seen.has(p.page)) fail(\"render_invalid\", \"page d'aperçu en double : \" + p.page);\n seen.add(p.page);\n const stored = await storeFile(dir + \"/page-\" + p.page + \".png\", p);\n previews.push({page: p.page, path: stored.path, sha256: stored.sha256});\n }\n for (let n = 1; n <= res.pages; n++) if (!seen.has(n)) fail(\"render_invalid\", \"aperçu manquant : page \" + 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 rejectUnsafeKeys(input.data_patch, \"data_patch\");\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 + \"-\" + attemptTag(res.file);\nconst file = await storeFile(dir + \"/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\", profile_sha256: await fingerprint(profile), data_sha256: await fingerprint(data), file, previews, provenance: res.provenance === undefined ? null : res.provenance});\nawait saveRecord(rec);\nreturn {...summarize(rec), profile_source: PROFILE_SOURCE};\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 29b0cc4..3f91a25 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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\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) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\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\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\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 de54c08..c764b65 100644 --- a/document-studio/agents/main/workflows/document-studio-template-read.json +++ b/document-studio/agents/main/workflows/document-studio-template-read.json @@ -16,7 +16,8 @@ "description": "Template key", "enum": [ "quote", - "meeting-minutes" + "meeting-minutes", + "dashboard" ] } } @@ -25,7 +26,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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" 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.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, 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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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\\\"dashboard\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$defs\\\": \\u007b\\\"bar\\\": \\u007b\\\"description\\\": \\\"Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"bar\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"description\\\": \\\"Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).\\\", \\\"properties\\\": \\u007b\\\"phases\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"tasks\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"duration\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 0.01, \\\"type\\\": \\\"number\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"phase\\\": \\u007b\\\"maximum\\\": 4, \\\"minimum\\\": 0, \\\"type\\\": \\\"integer\\\"\\u007d, \\\"start\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 104, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"start\\\", \\\"duration\\\", \\\"phase\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 25, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"gantt\\\"\\u007d, \\\"weeks\\\": \\u007b\\\"maximum\\\": 104, \\\"minimum\\\": 1, \\\"type\\\": \\\"integer\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"weeks\\\", \\\"phases\\\", \\\"tasks\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"label\\\": \\u007b\\\"description\\\": \\\"Une ligne de texte : ni saut de ligne ni autre caractere de controle.\\\", \\\"maxLength\\\": 60, \\\"minLength\\\": 1, \\\"pattern\\\": \\\"^[^\\\\\\\\x00-\\\\\\\\x1F\\\\\\\\x7F]+$\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"line\\\": \\u007b\\\"description\\\": \\\"Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"categories\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"series\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"values\\\": \\u007b\\\"items\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/number\\\"\\u007d, \\\"maxItems\\\": 24, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"values\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 5, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"line\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"categories\\\", \\\"series\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"number\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d, \\u007b\\\"maximum\\\": -0.01\\u007d], \\\"description\\\": \\\"0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12.\\\", \\\"maximum\\\": 1000000000000, \\\"minimum\\\": -1000000000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"org\\\": \\u007b\\\"description\\\": \\\"Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).\\\", \\\"properties\\\": \\u007b\\\"nodes\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"id\\\": \\u007b\\\"maxLength\\\": 32, \\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"parent\\\": \\u007b\\\"maxLength\\\": 32, \\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"id\\\", \\\"name\\\", \\\"parent\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 30, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"org\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"nodes\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"pie\\\": \\u007b\\\"description\\\": \\\"Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).\\\", \\\"properties\\\": \\u007b\\\"parts\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"value\\\": \\u007b\\\"anyOf\\\": [\\u007b\\\"const\\\": 0\\u007d, \\u007b\\\"minimum\\\": 0.01\\u007d], \\\"maximum\\\": 1000000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"value\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 10, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"pie\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"parts\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"process\\\": \\u007b\\\"description\\\": \\\"Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.\\\", \\\"properties\\\": \\u007b\\\"steps\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"kind\\\": \\u007b\\\"enum\\\": [\\\"start\\\", \\\"step\\\", \\\"decision\\\", \\\"end\\\"]\\u007d, \\\"label\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"label\\\", \\\"kind\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"maxItems\\\": 12, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d, \\\"type\\\": \\u007b\\\"const\\\": \\\"process\\\"\\u007d\\u007d, \\\"required\\\": [\\\"type\\\", \\\"steps\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"description\\\": \\\"Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).\\\", \\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/bar\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/gantt\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/line\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/org\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/pie\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/process\\\"\\u007d, \\\"title\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"titles\\\": \\u007b\\\"properties\\\": \\u007b\\\"bar\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"gantt\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"line\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"org\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"pie\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d, \\\"process\\\": \\u007b\\\"$ref\\\": \\\"#/$defs/label\\\"\\u007d\\u007d, \\\"required\\\": [\\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"type\\\": \\\"object\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"titles\\\", \\\"bar\\\", \\\"line\\\", \\\"pie\\\", \\\"gantt\\\", \\\"org\\\", \\\"process\\\"], \\\"title\\\": \\\"Donnees metier du tableau de bord\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/charts.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"dashboard\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 6, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Tableau de bord\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"TB\\\", \\\"summary\\\": \\\"Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n'est calculé par le modèle.\\\", \\\"title\\\": \\\"Tableau de bord\\\"\\u007d, \\\"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\\\"description\\\": \\\"At most 3 decimals\\\", \\\"exclusiveMinimum\\\": 0, \\\"maximum\\\": 1000000, \\\"type\\\": \\\"number\\\"\\u007d, \\\"unit\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"unit_price_ht\\\": \\u007b\\\"description\\\": \\\"At most 2 decimals\\\", \\\"maximum\\\": 1000000000, \\\"minimum\\\": 0, \\\"type\\\": \\\"number\\\"\\u007d, \\\"vat_rate\\\": \\u007b\\\"description\\\": \\\"One of 0, 2.1, 5.5, 10, 20\\\", \\\"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\");\nObject.setPrototypeOf(TEMPLATES, null);\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)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\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 canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\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\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\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, const, anyOf.\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 if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : 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 \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (schema.const !== undefined && value !== schema.const) errors.push(path + \" : valeur attendue \" + JSON.stringify(schema.const));\n if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + \" : aucune des variantes admises\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\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) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\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 big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\n// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation.\nfunction documentTitle(key, d) { return key === \"quote\" ? \"Devis \" + d.customer.name : key === \"meeting-minutes\" ? d.meeting.title : d.title; }\nfunction fallbackTitle(key, d) {\n if (key === \"quote\") return \"devis \" + (isObject(d.customer) ? d.customer.name : \"\");\n if (key === \"meeting-minutes\") return isObject(d.meeting) ? d.meeting.title : key;\n return typeof d.title === \"string\" && d.title ? d.title : key;\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 rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\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 if (key === \"quote\") checkQuoteNumbers(d);\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/document-studio/examples/templates/dashboard/examples/default.json b/document-studio/examples/templates/dashboard/examples/default.json new file mode 100644 index 0000000..2e2ac54 --- /dev/null +++ b/document-studio/examples/templates/dashboard/examples/default.json @@ -0,0 +1,231 @@ +{ + "title": "Tableau de bord Activité 2026", + "titles": { + "bar": "Résultat mensuel", + "line": "Tendance", + "pie": "Répartition du chiffre d'affaires", + "gantt": "Plan de projet", + "org": "Organisation", + "process": "Traitement d'une demande" + }, + "bar": { + "type": "bar", + "categories": [ + "janv.", + "févr.", + "mars", + "avr.", + "mai", + "juin" + ], + "series": [ + { + "name": "Chiffre d'affaires (k€)", + "values": [ + 1250.5, + 1380, + 1520, + 1475, + 1680, + 1904.25 + ] + }, + { + "name": "Résultat (k€)", + "values": [ + 220, + -150.5, + 310, + -80, + 405, + 520 + ] + } + ] + }, + "line": { + "type": "line", + "categories": [ + "janv.", + "févr.", + "mars", + "avr.", + "mai", + "juin" + ], + "series": [ + { + "name": "Visites", + "values": [ + 12000, + 13500, + 15000, + 14200, + 16800, + 19000 + ] + }, + { + "name": "Commandes", + "values": [ + 980, + 1040, + 1100, + 1080, + 1210, + 1330 + ] + } + ] + }, + "pie": { + "type": "pie", + "parts": [ + { + "name": "Conseil", + "value": 3800 + }, + { + "name": "Formation", + "value": 2400 + }, + { + "name": "Licences", + "value": 1700 + }, + { + "name": "Intégration", + "value": 1300 + }, + { + "name": "Support", + "value": 800 + } + ] + }, + "gantt": { + "type": "gantt", + "weeks": 12, + "phases": [ + "Cadrage", + "Construction", + "Recette" + ], + "tasks": [ + { + "name": "Cadrage du besoin", + "start": 0, + "duration": 2, + "phase": 0 + }, + { + "name": "Ateliers utilisateurs", + "start": 1, + "duration": 3, + "phase": 0 + }, + { + "name": "Socle technique", + "start": 3, + "duration": 4, + "phase": 1 + }, + { + "name": "Interfaces principales", + "start": 5, + "duration": 5, + "phase": 1 + }, + { + "name": "Recette métier", + "start": 9, + "duration": 2, + "phase": 2 + }, + { + "name": "Mise en production", + "start": 11, + "duration": 1, + "phase": 2 + } + ] + }, + "org": { + "type": "org", + "nodes": [ + { + "id": "n1", + "name": "Hélène Marchand", + "title": "Directrice générale", + "parent": "" + }, + { + "id": "n2", + "name": "Julien Bœuf", + "title": "Directeur technique", + "parent": "n1" + }, + { + "id": "n3", + "name": "Camille Durand", + "title": "Directrice commerciale", + "parent": "n1" + }, + { + "id": "n4", + "name": "Inès Garnier", + "title": "Développement", + "parent": "n2" + }, + { + "id": "n5", + "name": "Théo Bernard", + "title": "Données", + "parent": "n2" + }, + { + "id": "n6", + "name": "Maël Roche", + "title": "Grands comptes", + "parent": "n3" + } + ] + }, + "process": { + "type": "process", + "steps": [ + { + "label": "Demande reçue", + "kind": "start" + }, + { + "label": "Qualification", + "kind": "step" + }, + { + "label": "Dossier complet ?", + "kind": "decision" + }, + { + "label": "Chiffrage", + "kind": "step" + }, + { + "label": "Validation interne", + "kind": "step" + }, + { + "label": "Envoi du devis", + "kind": "step" + }, + { + "label": "Signature client", + "kind": "step" + }, + { + "label": "Clôture", + "kind": "end" + } + ] + } +} diff --git a/document-studio/examples/templates/dashboard/fragments/charts.typ b/document-studio/examples/templates/dashboard/fragments/charts.typ new file mode 100644 index 0000000..eacd8d7 --- /dev/null +++ b/document-studio/examples/templates/dashboard/fragments/charts.typ @@ -0,0 +1,532 @@ +// Fragments partages : graphiques deterministes en Typst pur (contrat `chart/v1`, +// README § Graphiques). Aucun paquet, aucun plugin, aucune image : du vectoriel. +// Couleurs : uniquement `brand.colors` (et le blanc, papier et liseres). +// +// Chaque fragment recoit ses donnees sous trois formes equivalentes : +// - un dictionnaire Typst ; +// - une chaine JSON ; +// - un contenu `[...]` portant cette chaine (cas d'un gabarit : la fonction `json` appliquee a la donnee, entre +// crochets ; la valeur passe par reference, jamais dans le code). +// Toute entree mal formee ou hors bornes echoue par une erreur de compilation dont le message commence par `chart/v1:`. +// Un JSON syntaxiquement invalide echoue avec l'erreur de `json()` de Typst : le +// moteur ne transmet que du JSON valide, valide aussi contre `chart.schema.json`. +#import "/brand.typ": brand + +// Bornes du contrat. `chart.schema.json` porte les memes valeurs (test du contrat). +#let limits = ( + max-categories: 24, + max-series: 5, + max-parts: 10, + max-tasks: 25, + max-nodes: 30, + max-steps: 12, + max-phases: 5, + max-weeks: 104, + max-org-leaves: 8, + max-org-depth: 6, + max-org-height: 240, + max-process-height: 180, + max-label: 60, + max-id: 32, + max-abs-value: 1000000000000, + min-abs-value: 0.01, +) + +#let c = brand.colors +// Palette de series : les cinq couleurs de la charte qui contrastent avec le papier. +#let series-colors = (c.primary, c.accent, c.secondary, c.muted, c.text) + +// ---------------------------------------------------------------- validation + +#let fail(msg) = panic("chart/v1: " + msg) +#let ensure(ok, msg) = if not ok { fail(msg) } +#let is-num(v) = type(v) == int or type(v) == float + +#let plain(x) = { + if type(x) == str { x } else if type(x) == content { + if x.has("text") { x.text } else if x.has("children") { x.children.map(plain).join() } else if x.func() == [ ].func() { " " } else { + fail("expected the JSON text of the data (use `| json` inside [ ])") + } + } else { fail("expected a dictionary, a JSON string or its content, got " + str(type(x))) } +} + +#let load(x, kind, who) = { + let d = if type(x) == dictionary { x } else { json(bytes(plain(x))) } + ensure(type(d) == dictionary, who + ": the data must be an object") + ensure(d.at("type", default: none) == kind, who + ": type must be \"" + kind + "\"") + d +} + +#let check-list(v, what, lo, hi) = { + ensure(type(v) == array, what + " must be an array") + ensure(v.len() >= lo and v.len() <= hi, what + " must have between " + str(lo) + " and " + str(hi) + " items, got " + str(v.len())) +} +#let check-label(v, what) = { + ensure(type(v) == str and v.len() > 0, what + " must be a non-empty string") + ensure(v.codepoints().len() <= limits.max-label, what + " is longer than " + str(limits.max-label) + " characters") + // a label is one line of text: no line break, no other control character + ensure(not v.contains(regex("[\\x00-\\x1f\\x7f]")), what + " must not contain a line break or another control character") +} +// A number is 0 or at least `min-abs-value` in absolute value (the displayed precision), +// at most `max-abs-value`: no value can underflow the axis computation. +#let check-num(v, what) = { + ensure(is-num(v), what + " must be a number") + ensure(calc.abs(v) <= limits.max-abs-value, what + " is beyond +-" + str(limits.max-abs-value)) + ensure(v == 0 or calc.abs(v) >= limits.min-abs-value, what + " must be 0 or at least " + str(limits.min-abs-value) + " in absolute value") +} +// An integer is an int, or a float without fractional part (JSON Schema reads 1.0 as an +// integer; Typst decodes it as a float). Returns the value as an int. +#let check-int(v, what, lo, hi) = { + ensure(is-num(v) and (type(v) == int or v == calc.trunc(v)), what + " must be an integer") + ensure(v >= lo and v <= hi, what + " must be between " + str(lo) + " and " + str(hi) + ", got " + str(v)) + int(v) +} +#let get(d, key, who) = { + ensure(key in d, who + ": `" + key + "` is missing") + d.at(key) +} +#let check-series(s, n, who) = { + ensure(type(s) == dictionary, who + ": a series must be an object") + check-label(get(s, "name", who + " series"), who + ": series name") + let vals = get(s, "values", who + " series") + ensure(type(vals) == array and vals.len() == n, who + ": series `" + s.name + "` must have exactly " + str(n) + " values (one per category)") + for v in vals { check-num(v, who + ": a value of series `" + s.name + "`") } +} + +// A word wider than `avail` is cut by zero-width spaces between its characters, so that it can wrap. +// Needs a `context`. +#let cut-words(txt, size, weight, avail) = txt.split(" ").map(word => { + if measure(text(size: size, weight: weight, word)).width > avail { word.clusters().join(sym.zws) } else { word } +}).join(" ") + +// ---------------------------------------------------------------- nombres (fr) + +// 1234567.5 -> « 1 234 567,5 » (espace fine insecable U+202F, virgule decimale, +// vrai signe moins U+2212). Arrondi a `digits` decimales, zeros finaux retires. +#let thin = "\u{202F}" +#let fmt-num(v, digits: 2) = { + let r = calc.round(v, digits: digits) + if r == 0 { "0" } else { + let parts = str(calc.abs(r)).split(".") + let ip = parts.at(0) + let n = ip.len() + let grouped = ip.clusters().enumerate().map(((i, ch)) => if i > 0 and calc.rem(n - i, 3) == 0 { thin + ch } else { ch }).join() + (if r < 0 { "\u{2212}" } else { "" }) + grouped + (if parts.len() > 1 { "," + parts.at(1) } else { "" }) + } +} +#let fmt-pct(v) = fmt-num(v, digits: 1) + thin + "%" + +// ---------------------------------------------------------------- socle + +#let at(x, y, body) = place(top + left, dx: x, dy: y, body) +#let seg(x1, y1, x2, y2, stroke) = at(x1, y1, line(start: (0pt, 0pt), end: (x2 - x1, y2 - y1), stroke: stroke)) +#let tbox(x, y, w, h, body, size: 7pt, fill: c.text, al: center + horizon, weight: "regular") = at(x, y, box(width: w, height: h, align(al, text(size: size, fill: fill, weight: weight, body)))) + +// Pas « joli » (1, 2, 5 x 10^k) pour l'axe. +#let nice-step(v) = { + let p = calc.pow(10.0, calc.floor(calc.log(v, base: 10))) + let m = v / p + let s = if m <= 1 { 1 } else if m <= 2 { 2 } else if m <= 5 { 5 } else { 10 } + s * p +} + +// Axe vertical qui contient toujours zero : (lo, hi, step, decimals). +#let axis-scale(vmin, vmax) = { + let lo = calc.min(vmin, 0) + let hi = calc.max(vmax, 0) + if hi == lo { hi = 1 } + // finite floor: the span is never below the displayed precision, so log(0) cannot happen + let step = calc.max(nice-step(calc.max(hi - lo, limits.min-abs-value) / 5), 0.001) + let decimals = calc.min(6, calc.max(0, -calc.floor(calc.log(step, base: 10)))) + (lo: calc.floor(lo / step) * step, hi: calc.ceil(hi / step) * step, step: step, decimals: decimals) +} + +#let y-axis(ml, mt, ph, w, sc) = { + let n = calc.round((sc.hi - sc.lo) / sc.step) + for i in range(int(n) + 1) { + let v = sc.lo + i * sc.step + let y = mt + ph * ((sc.hi - v) / (sc.hi - sc.lo)) + seg(ml, y, w, y, 0.3pt + c.muted) + tbox(0pt, y - 2mm, ml - 2mm, 4mm, fmt-num(v, digits: sc.decimals), al: right + horizon, fill: c.muted, size: 7pt) + } +} + +#let legend(items, x0, y0, w, step: 56mm) = { + let st = calc.min(step, (w - x0) / items.len()) + let x = x0 + for (i, it) in items.enumerate() { + at(x, y0 + 0.8mm, rect(width: 3mm, height: 3mm, fill: series-colors.at(calc.rem(i, series-colors.len())), stroke: none)) + tbox(x + 4mm, y0, st - 5mm, 4.6mm, it, al: left + horizon, size: 8pt) + x += st + } +} + +// ---------------------------------------------------------------- barres + +// data : (type: "bar", categories: (..), series: ((name:, values: (..)), ..)) +// Series groupees cote a cote, valeurs negatives sous l'axe zero. +#let bar-chart(data, w: 170mm, h: 85mm) = { + let who = "bar-chart" + let d = load(data, "bar", who) + let cats = get(d, "categories", who) + check-list(cats, who + ": categories", 1, limits.max-categories) + for cat in cats { check-label(cat, who + ": a category") } + let ser = get(d, "series", who) + check-list(ser, who + ": series", 1, limits.max-series) + for s in ser { check-series(s, cats.len(), who) } + let ml = 12mm; let mt = 9mm; let mb = 7mm + let pw = w - ml; let ph = h - mt - mb + let all = ser.map(s => s.values).flatten() + let sc = axis-scale(calc.min(..all), calc.max(..all)) + let span = sc.hi - sc.lo + let ypos(v) = mt + ph * ((sc.hi - v) / span) + let slot = pw / cats.len() + let group = slot * 0.72 + let bw = group / ser.len() + let labels = bw >= 9mm + box(width: w, height: h, { + legend(ser.map(s => s.name), ml, 0mm, w) + y-axis(ml, mt, ph, w, sc) + for (si, s) in ser.enumerate() { + for (i, v) in s.values.enumerate() { + let x = ml + slot * i + (slot - group) / 2 + bw * si + let y0 = ypos(0) + let y1 = ypos(v) + let top = calc.min(y0, y1) + at(x, top, rect(width: bw, height: calc.abs(y1 - y0), fill: series-colors.at(si), stroke: none)) + if labels { + let ly = if v >= 0 { top - 3.8mm } else { top + calc.abs(y1 - y0) + 0.2mm } + tbox(x - 2mm, ly, bw + 4mm, 3.6mm, fmt-num(v), size: 6.5pt) + } + } + } + for (i, cat) in cats.enumerate() { + tbox(ml + slot * i, mt + ph + 1mm, slot, 4mm, cat, fill: c.text, size: if slot < 12mm { 6pt } else { 7pt }) + } + seg(ml, ypos(0), w, ypos(0), 0.6pt + c.text) + }) +} + +// ---------------------------------------------------------------- lignes + +// data : (type: "line", categories: (..), series: ((name:, values: (..)), ..)) +#let line-chart(data, w: 170mm, h: 85mm) = { + let who = "line-chart" + let d = load(data, "line", who) + let cats = get(d, "categories", who) + check-list(cats, who + ": categories", 1, limits.max-categories) + for cat in cats { check-label(cat, who + ": a category") } + let ser = get(d, "series", who) + check-list(ser, who + ": series", 1, limits.max-series) + for s in ser { check-series(s, cats.len(), who) } + let ml = 12mm; let mt = 9mm; let mb = 7mm + let pw = w - ml; let ph = h - mt - mb + let all = ser.map(s => s.values).flatten() + let sc = axis-scale(calc.min(..all), calc.max(..all)) + let span = sc.hi - sc.lo + let ypos(v) = mt + ph * ((sc.hi - v) / span) + let slot = pw / cats.len() + box(width: w, height: h, { + legend(ser.map(s => s.name), ml, 0mm, w) + y-axis(ml, mt, ph, w, sc) + for (i, cat) in cats.enumerate() { + tbox(ml + slot * i, mt + ph + 1mm, slot, 4mm, cat, fill: c.text, size: if slot < 12mm { 6pt } else { 7pt }) + } + seg(ml, ypos(0), w, ypos(0), 0.6pt + c.text) + for (k, s) in ser.enumerate() { + let col = series-colors.at(k) + let pts = s.values.enumerate().map(((i, v)) => (ml + slot * (i + 0.5), ypos(v))) + for i in range(pts.len() - 1) { + seg(pts.at(i).at(0), pts.at(i).at(1), pts.at(i + 1).at(0), pts.at(i + 1).at(1), 1.6pt + col) + } + for p in pts { + at(p.at(0) - 1.2mm, p.at(1) - 1.2mm, circle(radius: 1.2mm, fill: col, stroke: 0.5pt + white)) + } + } + }) +} + +// ---------------------------------------------------------------- camembert + +// data : (type: "pie", parts: ((name:, value:), ..)). Les parts sont calculees +// depuis les valeurs (value / somme) ; le pourcentage affiche est donc derive. +#let pie-chart(data, w: 170mm, h: 90mm) = { + let who = "pie-chart" + let d = load(data, "pie", who) + let parts = get(d, "parts", who) + check-list(parts, who + ": parts", 1, limits.max-parts) + for p in parts { + ensure(type(p) == dictionary, who + ": a part must be an object") + check-label(get(p, "name", who + " part"), who + ": part name") + let v = get(p, "value", who + " part") + check-num(v, who + ": value of part `" + p.name + "`") + ensure(v >= 0, who + ": value of part `" + p.name + "` must not be negative") + } + let total = parts.map(p => p.value).sum() + ensure(total > 0, who + ": the sum of the values must be greater than zero") + // Une couleur par part ; au-dela de cinq parts la palette se repete, et la derniere + // part ne prend jamais la couleur de ses deux voisines. + let n = parts.len() + let ncol = series-colors.len() + let color-index(k) = { + if n > 1 and k == n - 1 and n > ncol { + let taken = (calc.rem(0, ncol), calc.rem(n - 2, ncol)) + range(ncol).find(j => j not in taken) + } else { calc.rem(k, ncol) } + } + let r = 36mm; let cx = 42mm; let cy = h / 2 + box(width: w, height: h, { + let a0 = -90deg + for (k, it) in parts.enumerate() { + let share = it.value / total + let da = 360deg * share + if it.value > 0 { + let steps = calc.max(2, calc.ceil(da / 2deg)) + let pts = ((cx, cy),) + for j in range(steps + 1) { + let a = a0 + da * (j / steps) + pts.push((cx + r * calc.cos(a), cy + r * calc.sin(a))) + } + at(0pt, 0pt, polygon(fill: series-colors.at(color-index(k)), stroke: 1pt + white, ..pts)) + let am = a0 + da / 2 + tbox(cx + r * 0.68 * calc.cos(am) - 7mm, cy + r * 0.68 * calc.sin(am) - 2.5mm, 14mm, 5mm, + fmt-pct(share * 100), size: if share < 0.04 { 6pt } else { 8pt }, fill: white, weight: "bold") + } + a0 += da + } + for (k, it) in parts.enumerate() { + let y = 22mm + k * 6.4mm + at(95mm, y + 0.6mm, rect(width: 4mm, height: 4mm, fill: series-colors.at(color-index(k)), stroke: none)) + tbox(102mm, y, w - 102mm, 5.2mm, it.name + " (" + fmt-pct(it.value / total * 100) + ")", al: left + horizon, size: 9pt) + } + }) +} + +// ---------------------------------------------------------------- Gantt + +// data : (type: "gantt", weeks: 26, phases: (..), tasks: ((name:, start:, duration:, phase:), ..)) +// `start` et `duration` en semaines depuis la semaine 0 ; `phase` = indice dans `phases`. +#let gantt-chart(data, w: 170mm) = { + let who = "gantt-chart" + let d = load(data, "gantt", who) + let weeks = check-int(get(d, "weeks", who), who + ": weeks", 1, limits.max-weeks) + let phases = get(d, "phases", who) + check-list(phases, who + ": phases", 1, limits.max-phases) + for p in phases { check-label(p, who + ": a phase") } + let raw-tasks = get(d, "tasks", who) + check-list(raw-tasks, who + ": tasks", 1, limits.max-tasks) + let tasks = () + for t in raw-tasks { + ensure(type(t) == dictionary, who + ": a task must be an object") + check-label(get(t, "name", who + " task"), who + ": task name") + let start = get(t, "start", who + " task") + let dur = get(t, "duration", who + " task") + check-num(start, who + ": start of task `" + t.name + "`") + check-num(dur, who + ": duration of task `" + t.name + "`") + ensure(start >= 0, who + ": start of task `" + t.name + "` must not be negative") + ensure(dur >= limits.min-abs-value, who + ": duration of task `" + t.name + "` must be at least " + str(limits.min-abs-value)) + ensure(start + dur <= weeks, who + ": task `" + t.name + "` ends after week " + str(weeks)) + let phase = check-int(get(t, "phase", who + " task"), who + ": phase of task `" + t.name + "`", 0, phases.len() - 1) + tasks.push((name: t.name, start: start, duration: dur, phase: phase)) + } + let nw = 50mm; let rh = 7mm; let hh = 7mm + let gw = w - nw; let ws = gw / weeks + let hgt = hh + rh * tasks.len() + 9mm + let every = calc.max(1, calc.ceil(9mm / ws)) + box(width: w, height: hgt, { + legend(phases, nw, 0mm, w, step: 30mm) + let y0 = 8mm + at(nw, y0, rect(width: gw, height: hh + rh * tasks.len(), fill: c.background, stroke: none)) + for k in range(weeks + 1) { + seg(nw + ws * k, y0 + hh, nw + ws * k, y0 + hh + rh * tasks.len(), 0.25pt + c.muted) + } + for k in range(weeks) { + if calc.rem(k, every) == 0 { tbox(nw + ws * k - 1mm, y0 + 1mm, ws * every, 5mm, "S" + str(k + 1), size: 6.5pt, fill: c.muted) } + } + for (i, t) in tasks.enumerate() { + let y = y0 + hh + rh * i + seg(0pt, y, w, y, 0.25pt + c.muted) + tbox(0pt, y, nw - 2mm, rh, t.name, al: left + horizon, size: 7.5pt) + // the bar spans the real start and end; a bar shorter than 0.2 mm becomes a 0.2 mm + // marker that starts at the real start and only moves back to stay inside the grid + let bl = ws * t.start + let br = ws * (t.start + t.duration) + let bwid = calc.min(calc.max(0.2mm, br - bl), gw) + let bx = calc.max(0pt, calc.min(bl, gw - bwid)) + at(nw + bx, y + 1.2mm, rect(width: bwid, height: rh - 2.4mm, radius: calc.min(0.8mm, bwid / 2), fill: series-colors.at(t.phase), stroke: none)) + } + seg(0pt, y0 + hh + rh * tasks.len(), w, y0 + hh + rh * tasks.len(), 0.6pt + c.text) + }) +} + +// ---------------------------------------------------------------- organigramme + +// Disposition d'arbre : un emplacement par feuille, parent centre sur ses enfants. +#let tree-layout(nodes, id, depth, x0) = { + let kids = nodes.filter(n => n.parent == id) + if kids.len() == 0 { + (width: 1, cx: x0 + 0.5, items: ((id: id, cx: x0 + 0.5, depth: depth),)) + } else { + let cur = x0 + let items = () + let cxs = () + for k in kids { + let r = tree-layout(nodes, k.id, depth + 1, cur) + cur += r.width + items += r.items + cxs.push(r.cx) + } + let cx = (cxs.first() + cxs.last()) / 2 + (width: cur - x0, cx: cx, items: items + ((id: id, cx: cx, depth: depth),)) + } +} + +// data : (type: "org", nodes: ((id:, name:, title:, parent:), ..)) ; `parent` = "" pour la racine, +// `title` facultatif. +#let org-chart(data, w: 170mm) = { + let who = "org-chart" + let d = load(data, "org", who) + let raw = get(d, "nodes", who) + check-list(raw, who + ": nodes", 1, limits.max-nodes) + let ids = () + for n in raw { + ensure(type(n) == dictionary, who + ": a node must be an object") + let id = get(n, "id", who + " node") + ensure(type(id) == str and id.len() > 0 and id.codepoints().len() <= limits.max-id, who + ": a node id must be a string of 1 to " + str(limits.max-id) + " characters") + ensure(id not in ids, who + ": duplicate node id `" + id + "`") + ids.push(id) + check-label(get(n, "name", who + " node"), who + ": name of node `" + id + "`") + // optional, but a title that is present is a label like any other (not empty) + if "title" in n { check-label(n.title, who + ": title of node `" + id + "`") } + ensure(type(get(n, "parent", who + " node")) == str, who + ": parent of node `" + id + "` must be a string (empty for the root)") + } + let nodes = raw.map(n => (id: n.id, name: n.name, title: n.at("title", default: ""), parent: n.parent)) + let roots = nodes.filter(n => n.parent == "") + ensure(roots.len() == 1, who + ": exactly one node must have an empty parent, got " + str(roots.len())) + for n in nodes { + ensure(n.parent == "" or n.parent in ids, who + ": parent `" + n.parent + "` of node `" + n.id + "` does not exist") + } + let lay = tree-layout(nodes, roots.first().id, 0, 0) + ensure(lay.items.len() == nodes.len(), who + ": every node must descend from the root (cycle or detached node)") + let depth = calc.max(..lay.items.map(i => i.depth)) + ensure(depth <= limits.max-org-depth, who + ": depth " + str(depth) + " is above " + str(limits.max-org-depth)) + ensure(lay.width <= limits.max-org-leaves, who + ": " + str(lay.width) + " leaves is above " + str(limits.max-org-leaves)) + let pos = lay.items.map(i => (i.id, i)).to-dict() + let slot = w / lay.width + let bw = calc.min(slot - 3mm, 36mm); let pad = 1.5mm; let gap = 14mm + let avail = bw - 2 * pad + // The node height follows the measured content, one common height per level; a word wider + // than the box is cut (zero-width spaces between its characters), so no text leaves its node. + context { + let cut(txt, size, weight) = txt.split(" ").map(word => { + if measure(text(size: size, weight: weight, word)).width > avail { word.clusters().join(sym.zws) } else { word } + }).join(" ") + let cell(n, fg) = { + set par(leading: 0.45em, justify: false) + align(center + horizon, { + text(size: 7.5pt, weight: "bold", fill: fg, cut(n.name, 7.5pt, "bold")) + if n.title != "" { + linebreak() + text(size: 6pt, fill: fg, cut(n.title, 6pt, "regular")) + } + }) + } + let fg-of(depth) = if depth <= 1 { white } else { c.text } + let level-h = range(depth + 1).map(dep => { + let hs = nodes.filter(n => pos.at(n.id).depth == dep).map(n => measure(width: avail, block(width: avail, cell(n, fg-of(dep)))).height) + calc.max(13mm, calc.max(..hs) + 2 * pad) + }) + let level-y(dep) = level-h.slice(0, dep).sum(default: 0mm) + dep * gap + let hgt = level-h.sum() + depth * gap + ensure(hgt <= limits.max-org-height * 1mm, who + ": the names and titles need " + str(calc.round(hgt / 1mm)) + " mm of height, above " + str(limits.max-org-height) + " mm: shorten them") + box(width: w, height: hgt, { + for n in nodes.filter(n => n.parent != "") { + let p = pos.at(n.parent); let q = pos.at(n.id) + let px = p.cx * slot; let qx = q.cx * slot + let py = level-y(p.depth) + level-h.at(p.depth); let qy = level-y(q.depth) + let my = (py + qy) / 2 + seg(px, py, px, my, 0.8pt + c.secondary) + seg(px, my, qx, my, 0.8pt + c.secondary) + seg(qx, my, qx, qy, 0.8pt + c.secondary) + } + for n in nodes { + let p = pos.at(n.id) + let x = p.cx * slot - bw / 2; let y = level-y(p.depth) + let fillc = if p.depth == 0 { c.primary } else if p.depth == 1 { c.secondary } else { c.background } + at(x, y, rect(width: bw, height: level-h.at(p.depth), radius: 1.2mm, fill: fillc, stroke: 0.6pt + c.secondary)) + at(x + pad, y + pad, box(width: avail, height: level-h.at(p.depth) - 2 * pad, cell(n, fg-of(p.depth)))) + } + }) + } +} + +// ---------------------------------------------------------------- processus + +// data : (type: "process", steps: ((label:, kind:), ..)) ; kind = start | step | decision | end. +// Retour a la ligne (ce n'est pas un serpentin) : chaque ligne se lit de gauche a droite et un +// connecteur coude revient au debut de la ligne suivante. Le nombre d'etapes par ligne (3 a 5) +// est choisi pour equilibrer les lignes. La hauteur des etapes suit le texte mesure (commune a +// une ligne) ; un mot plus large que sa forme est coupe ; le texte d'une decision tient dans le +// rectangle inscrit dans le losange, qui grandit si besoin. +#let process-flow(data, w: 170mm) = { + let who = "process-flow" + let d = load(data, "process", who) + let steps = get(d, "steps", who) + check-list(steps, who + ": steps", 1, limits.max-steps) + for s in steps { + ensure(type(s) == dictionary, who + ": a step must be an object") + check-label(get(s, "label", who + " step"), who + ": step label") + ensure(get(s, "kind", who + " step") in ("start", "step", "decision", "end"), who + ": step kind must be start, step, decision or end") + } + let rows = calc.ceil(steps.len() / 5) + let per-row = calc.ceil(steps.len() / rows) + let slot = w / per-row; let bw = slot - 9mm; let min-h = 16mm; let gap = 22mm + let pad = 1.5mm + let radius(kind) = if kind == "step" { 1.2mm } else { 6mm } + context { + // text area of a step: the box inside the shape (corners of a rounded shape cut 0.3 r) + let area-w(kind) = if kind == "decision" { 0.46 * bw } else { bw - 2 * pad - 0.6 * radius(kind) } + let size-of(kind) = if kind == "decision" { 6.5pt } else { 7pt } + let cut-label(s) = cut-words(s.label, size-of(s.kind), "bold", area-w(s.kind)) + let body(s) = block(width: area-w(s.kind), align(center + horizon, { + set par(leading: 0.4em, justify: false) + text(size: size-of(s.kind), weight: "bold", fill: white, cut-label(s)) + })) + let need(s) = { + let th = measure(width: area-w(s.kind), body(s)).height + if s.kind == "decision" { calc.max(min-h, 2 * th) } else { calc.max(min-h, th + 2 * pad + 0.6 * radius(s.kind)) } + } + let row-h = range(rows).map(r => calc.max(..steps.enumerate().filter(((i, s)) => calc.floor(i / per-row) == r).map(((i, s)) => need(s)))) + let row-y(r) = row-h.slice(0, r).sum(default: 0mm) + r * gap + let hgt = row-h.sum() + (rows - 1) * gap + ensure(hgt <= limits.max-process-height * 1mm, who + ": the labels need " + str(calc.round(hgt / 1mm)) + " mm of height, above " + str(limits.max-process-height) + " mm: shorten them") + box(width: w, height: hgt, { + for (i, s) in steps.enumerate() { + let r = calc.floor(i / per-row); let k = calc.rem(i, per-row) + let bh = row-h.at(r) + let x = slot * k + (slot - bw) / 2; let y = row-y(r) + let aw = area-w(s.kind) + if s.kind == "decision" { + at(x, y, polygon(fill: c.accent, stroke: none, (bw / 2, 0pt), (bw, bh / 2), (bw / 2, bh), (0pt, bh / 2))) + } else { + let fc = if s.kind == "step" { c.secondary } else { c.primary } + at(x, y, rect(width: bw, height: bh, radius: radius(s.kind), fill: fc, stroke: none)) + } + at(x + (bw - aw) / 2, y, box(width: aw, height: bh, align(horizon, body(s)))) + tbox(x - 1mm, y - 4.5mm, 6mm, 4mm, str(i + 1), size: 7pt, fill: c.muted, al: left + horizon) + if k < per-row - 1 and i < steps.len() - 1 { + seg(x + bw + 0.5mm, y + bh / 2, x + slot - 0.5mm, y + bh / 2, 1.2pt + c.text) + at(x + slot - 2.6mm, y + bh / 2 - 1.2mm, polygon(fill: c.text, stroke: none, (0pt, 0pt), (2.4mm, 1.2mm), (0pt, 2.4mm))) + } + if k == per-row - 1 and i < steps.len() - 1 { + let cx = x + bw / 2; let y1 = y + bh; let y2 = y + bh + gap / 2 + let x2 = slot / 2 + seg(cx, y1, cx, y2, 1.2pt + c.text) + seg(cx, y2, x2, y2, 1.2pt + c.text) + seg(x2, y2, x2, y + bh + gap - 2.4mm, 1.2pt + c.text) + at(x2 - 1.2mm, y + bh + gap - 2.6mm, polygon(fill: c.text, stroke: none, (0pt, 0pt), (2.4mm, 0pt), (1.2mm, 2.4mm))) + } + } + }) + } +} diff --git a/document-studio/examples/templates/dashboard/input.schema.json b/document-studio/examples/templates/dashboard/input.schema.json new file mode 100644 index 0000000..7ca2e13 --- /dev/null +++ b/document-studio/examples/templates/dashboard/input.schema.json @@ -0,0 +1,384 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Donnees metier du tableau de bord", + "description": "Un graphique par propriete, au format chart/v1 (`$defs` recopies de chart.schema.json).", + "type": "object", + "required": [ + "title", + "titles", + "bar", + "line", + "pie", + "gantt", + "org", + "process" + ], + "properties": { + "title": { + "$ref": "#/$defs/label" + }, + "titles": { + "type": "object", + "required": [ + "bar", + "line", + "pie", + "gantt", + "org", + "process" + ], + "properties": { + "bar": { + "$ref": "#/$defs/label" + }, + "line": { + "$ref": "#/$defs/label" + }, + "pie": { + "$ref": "#/$defs/label" + }, + "gantt": { + "$ref": "#/$defs/label" + }, + "org": { + "$ref": "#/$defs/label" + }, + "process": { + "$ref": "#/$defs/label" + } + } + }, + "bar": { + "$ref": "#/$defs/bar" + }, + "line": { + "$ref": "#/$defs/line" + }, + "pie": { + "$ref": "#/$defs/pie" + }, + "gantt": { + "$ref": "#/$defs/gantt" + }, + "org": { + "$ref": "#/$defs/org" + }, + "process": { + "$ref": "#/$defs/process" + } + }, + "$defs": { + "label": { + "type": "string", + "minLength": 1, + "maxLength": 60, + "pattern": "^[^\\x00-\\x1F\\x7F]+$", + "description": "Une ligne de texte : ni saut de ligne ni autre caractere de controle." + }, + "number": { + "type": "number", + "minimum": -1000000000000, + "maximum": 1000000000000, + "anyOf": [ + { + "const": 0 + }, + { + "minimum": 0.01 + }, + { + "maximum": -0.01 + } + ], + "description": "0, ou valeur absolue d'au moins 0.01 (precision affichee) ; au plus 1e12." + }, + "bar": { + "description": "Barres groupees (une serie = une couleur), valeurs negatives sous l'axe zero. Chaque serie a autant de valeurs que de categories (controle du fragment).", + "type": "object", + "required": [ + "type", + "categories", + "series" + ], + "properties": { + "type": { + "const": "bar" + }, + "categories": { + "type": "array", + "minItems": 1, + "maxItems": 24, + "items": { + "$ref": "#/$defs/label" + } + }, + "series": { + "type": "array", + "minItems": 1, + "maxItems": 5, + "items": { + "type": "object", + "required": [ + "name", + "values" + ], + "properties": { + "name": { + "$ref": "#/$defs/label" + }, + "values": { + "type": "array", + "minItems": 1, + "maxItems": 24, + "items": { + "$ref": "#/$defs/number" + } + } + } + } + } + } + }, + "line": { + "description": "Lignes (une serie = une couleur). Chaque serie a autant de valeurs que de categories (controle du fragment).", + "type": "object", + "required": [ + "type", + "categories", + "series" + ], + "properties": { + "type": { + "const": "line" + }, + "categories": { + "type": "array", + "minItems": 1, + "maxItems": 24, + "items": { + "$ref": "#/$defs/label" + } + }, + "series": { + "type": "array", + "minItems": 1, + "maxItems": 5, + "items": { + "type": "object", + "required": [ + "name", + "values" + ], + "properties": { + "name": { + "$ref": "#/$defs/label" + }, + "values": { + "type": "array", + "minItems": 1, + "maxItems": 24, + "items": { + "$ref": "#/$defs/number" + } + } + } + } + } + } + }, + "pie": { + "description": "Camembert : les parts sont calculees depuis les valeurs (valeur / somme). La somme doit etre strictement positive (controle du fragment).", + "type": "object", + "required": [ + "type", + "parts" + ], + "properties": { + "type": { + "const": "pie" + }, + "parts": { + "type": "array", + "minItems": 1, + "maxItems": 10, + "items": { + "type": "object", + "required": [ + "name", + "value" + ], + "properties": { + "name": { + "$ref": "#/$defs/label" + }, + "value": { + "type": "number", + "minimum": 0, + "maximum": 1000000000000, + "anyOf": [ + { + "const": 0 + }, + { + "minimum": 0.01 + } + ] + } + } + } + } + } + }, + "gantt": { + "description": "Gantt en semaines depuis la semaine 0. `phase` est un indice dans `phases`, start + duration <= weeks (controles du fragment).", + "type": "object", + "required": [ + "type", + "weeks", + "phases", + "tasks" + ], + "properties": { + "type": { + "const": "gantt" + }, + "weeks": { + "type": "integer", + "minimum": 1, + "maximum": 104 + }, + "phases": { + "type": "array", + "minItems": 1, + "maxItems": 5, + "items": { + "$ref": "#/$defs/label" + } + }, + "tasks": { + "type": "array", + "minItems": 1, + "maxItems": 25, + "items": { + "type": "object", + "required": [ + "name", + "start", + "duration", + "phase" + ], + "properties": { + "name": { + "$ref": "#/$defs/label" + }, + "start": { + "type": "number", + "minimum": 0, + "maximum": 104, + "anyOf": [ + { + "const": 0 + }, + { + "minimum": 0.01 + } + ] + }, + "duration": { + "type": "number", + "minimum": 0.01, + "maximum": 104 + }, + "phase": { + "type": "integer", + "minimum": 0, + "maximum": 4 + } + } + } + } + } + }, + "org": { + "description": "Organigramme : un seul noeud racine (parent vide), ids uniques, parents existants, profondeur et nombre de feuilles bornes par le fragment (max-org-depth, max-org-leaves).", + "type": "object", + "required": [ + "type", + "nodes" + ], + "properties": { + "type": { + "const": "org" + }, + "nodes": { + "type": "array", + "minItems": 1, + "maxItems": 30, + "items": { + "type": "object", + "required": [ + "id", + "name", + "parent" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 32 + }, + "name": { + "$ref": "#/$defs/label" + }, + "title": { + "$ref": "#/$defs/label" + }, + "parent": { + "type": "string", + "maxLength": 32 + } + } + } + } + } + }, + "process": { + "description": "Processus sur plusieurs lignes, chacune lue de gauche a droite avec un connecteur de retour (pas un serpentin) ; le nombre d'etapes par ligne est calcule.", + "type": "object", + "required": [ + "type", + "steps" + ], + "properties": { + "type": { + "const": "process" + }, + "steps": { + "type": "array", + "minItems": 1, + "maxItems": 12, + "items": { + "type": "object", + "required": [ + "label", + "kind" + ], + "properties": { + "label": { + "$ref": "#/$defs/label" + }, + "kind": { + "enum": [ + "start", + "step", + "decision", + "end" + ] + } + } + } + } + } + } + } +} diff --git a/document-studio/examples/templates/dashboard/main.typ b/document-studio/examples/templates/dashboard/main.typ new file mode 100644 index 0000000..76729d4 --- /dev/null +++ b/document-studio/examples/templates/dashboard/main.typ @@ -0,0 +1,39 @@ +// Gabarit de reference `dashboard` : les six graphiques chart/v1, une page chacun. +// Les donnees passent en JSON par reference (`| json` entre crochets), jamais dans le code. +#import "/brand.typ": brand, locale +#import "/fragments/charts.typ": bar-chart, line-chart, pie-chart, gantt-chart, org-chart, process-flow + +#set page(paper: brand.page.paper, margin: brand.page.margins) +#set text(font: (brand.fonts.body, "Libertinus Serif"), size: 10pt, fill: brand.colors.text, lang: locale) +#show heading.where(level: 1): set text(fill: brand.colors.primary, size: 17pt) + +#heading(level: 1)[{{ .data.title }}] +#v(4mm) +*{{ .data.titles.bar }}* +#v(2mm) +#bar-chart([{{ .data.bar | json }}]) + +#pagebreak() +*{{ .data.titles.line }}* +#v(2mm) +#line-chart([{{ .data.line | json }}]) + +#pagebreak() +*{{ .data.titles.pie }}* +#v(2mm) +#pie-chart([{{ .data.pie | json }}]) + +#pagebreak() +*{{ .data.titles.gantt }}* +#v(2mm) +#gantt-chart([{{ .data.gantt | json }}]) + +#pagebreak() +*{{ .data.titles.org }}* +#v(2mm) +#org-chart([{{ .data.org | json }}]) + +#pagebreak() +*{{ .data.titles.process }}* +#v(2mm) +#process-flow([{{ .data.process | json }}]) diff --git a/document-studio/examples/templates/dashboard/manifest.json b/document-studio/examples/templates/dashboard/manifest.json new file mode 100644 index 0000000..4d90571 --- /dev/null +++ b/document-studio/examples/templates/dashboard/manifest.json @@ -0,0 +1,34 @@ +{ + "schema": "agentmaurice.template/v1", + "key": "dashboard", + "version": "1.0.0", + "title": "Tableau de bord", + "description": "Six graphiques deterministes (barres, lignes, camembert, Gantt, organigramme, processus) a partir de donnees chart/v1.", + "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/charts.typ" + ], + "limits": { + "max_source_bytes": 20000, + "max_pages": 6 + } +} diff --git a/document-studio/module.yaml b/document-studio/module.yaml index dbdfee2..4e82903 100644 --- a/document-studio/module.yaml +++ b/document-studio/module.yaml @@ -3,7 +3,7 @@ "schema_version": 2, "key": "document-studio", "name": "Document studio", - "version": "0.3.0", + "version": "0.4.0", "provides": { "actions": [ { diff --git a/inventory/modules.json b/inventory/modules.json index 65798f2..4a8b653 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1205,7 +1205,7 @@ }, { "key": "document-studio", - "version": "0.3.0", + "version": "0.4.0", "manifest": "document-studio/module.yaml", "workflows": 15, "miniapps": 1, @@ -1238,22 +1238,22 @@ "document-studio/agents/main/miniapps/document-studio-review.json" ], "sha256": { - "document-studio/module.yaml": "f31b391b04ecf28700efb19584a020a2e72ddcb5c7ade5c5b6f6f3113f4562db", - "document-studio/agents/main/workflows/document-read.json": "732f3f29d3ba2a0b8d11b70f3ec26f34c08e3f80f0106156f9357936e1db333a", - "document-studio/agents/main/workflows/document-share.json": "f7755cb4f6049b97e8ca9b762929e5b51fd8b98dc8c2d8ec7dec9588449acf8d", - "document-studio/agents/main/workflows/document-studio-cancel.json": "a23e2f969ff387c63dd28614bb491cda5aaef9837c08f395e75bba3667ccd973", - "document-studio/agents/main/workflows/document-studio-draft.json": "c6b0593f2ad8db5ecab9f17fa47019e94054b8e66c917e0bac6447695141454d", - "document-studio/agents/main/workflows/document-studio-export.json": "231e46fecd19be8aa951b7e4f5862a7cec2b8edf79ee65ba001038150ac37dd4", - "document-studio/agents/main/workflows/document-studio-finalize.json": "c97ae082c17494abb2106cf70ecc68cb4d597da4015ed7eae85f314b640891fe", - "document-studio/agents/main/workflows/document-studio-list.json": "7319e6be4646a32166957ac122eb0bc8e9fc99ad2bd569d1345b373f344c9722", - "document-studio/agents/main/workflows/document-studio-mark-authoritative.json": "f5c484e13b1bc45b15c3106f7c6502e4ba168af9c1c283548171a02f12c25884", - "document-studio/agents/main/workflows/document-studio-new-version.json": "804c6e1f71c235e2d03a262d9da34cff1192a9cc85275b8d5cbafccd69492b41", - "document-studio/agents/main/workflows/document-studio-plan.json": "47a1a75463b75cdfc287a56f80a23f3faef513ae46b6b980a0851579089eb99b", - "document-studio/agents/main/workflows/document-studio-profile-save.json": "956421c2f7839ee05cf3b3419e3ad0cad08417e41b8a49a841da8911383be6fd", - "document-studio/agents/main/workflows/document-studio-publish.json": "eda72900c1872fe05eed3b9025f2341032e2e18c5191b9657d6b18d496e78c64", - "document-studio/agents/main/workflows/document-studio-render.json": "41f495b92d09d07b4d567ad6447ff3690a66c9c74a9315fab09846691357a483", - "document-studio/agents/main/workflows/document-studio-review-read.json": "dc098ee67469f050c8531677424fc412bd7b57d6cab97a6e5af934ae41c57e61", - "document-studio/agents/main/workflows/document-studio-template-read.json": "c5df42ab731d7c56aa483d0a0e19370afdcc24fe0151a61b76ceb3cbbc773fed", + "document-studio/module.yaml": "958f6fca731e508d2e6ff3b9a01e322a0ff37b8ba41f3d223515e41452b5b145", + "document-studio/agents/main/workflows/document-read.json": "b0089b283027ab450ba9d9239b52c694a6c01a9407491576aa1f20c8549f3c3b", + "document-studio/agents/main/workflows/document-share.json": "6a9eae1d6157f6f1dec86019c732f6b4ea66857718306dbfcb49d86ac8ebd60d", + "document-studio/agents/main/workflows/document-studio-cancel.json": "af0bde5acb3c51d1e040c7b77a14b0ba673e2a3644d656980305e6918236415a", + "document-studio/agents/main/workflows/document-studio-draft.json": "9c4793353bd0c21b54edb487316ac02550ac27eb104a64b02bfc413ee3083776", + "document-studio/agents/main/workflows/document-studio-export.json": "2c2d4e3078b1539e8c94627c989c5bbca4f67e8caa9dfdad7cc88623a5c79130", + "document-studio/agents/main/workflows/document-studio-finalize.json": "9869f825b984f028076a31b4cdafe47708679359a5ffc0779f2ccba0bf80384e", + "document-studio/agents/main/workflows/document-studio-list.json": "48aa273340eff2b5b1e17c4a7ed40abe001444dc72b2ef3769825c4f36c88435", + "document-studio/agents/main/workflows/document-studio-mark-authoritative.json": "dc5413f703f6a478f74f16da5fb9a897ce6d76465cf9a55451ba9b668645fca9", + "document-studio/agents/main/workflows/document-studio-new-version.json": "8b4b136511001cc565439c6e9debd434af978af4600b081521332664041145bb", + "document-studio/agents/main/workflows/document-studio-plan.json": "633b923d19e0b28a7415a8087252b4d131ce2cdfd4404a2166c5fdc75736c641", + "document-studio/agents/main/workflows/document-studio-profile-save.json": "291e142bc8665e0ac342aa75c27f2bfdf6e9d132d1027d6b312d188fef45aacf", + "document-studio/agents/main/workflows/document-studio-publish.json": "69cedcbf4e18c4e3f9d267e6eca344740c921cc567e191a83d5c12d07af28bc9", + "document-studio/agents/main/workflows/document-studio-render.json": "8c205b2ac7d4479c102f08dbe17bfdba64ba0f88cbbc907f79f8834c3626cbe9", + "document-studio/agents/main/workflows/document-studio-review-read.json": "32911c2692fa7f5f164cf06ec7f56ed89b5d5d6d89880cb5790998b37ae26093", + "document-studio/agents/main/workflows/document-studio-template-read.json": "7e3069c3b3cf17b5ba561ff5c9215071036bf66aa89d5f2b0d0f3a160f8c69d4", "document-studio/agents/main/miniapps/document-studio-review.json": "126750a2bcf33970f52a3e946381661136ec5cae9a918546cca289a268c1088c" } }, @@ -1267,7 +1267,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "9b7bfbe9723c6ed11b2af8a504f5f5e0dbe27c1fd636f87ee65e552b0f229b37" + "code_sha256": "a1b2bbc2fbf583cad938625d6bdccf13b7b4088749972c3ed03ab460e45cdceb" } ] }, @@ -1280,7 +1280,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "659157ddb8688061a808d19c50ef5dfc096d7cf89d0a08518f313f5dfdd2a79c" + "code_sha256": "29005adbdaad5e387f83f235d79b8345d4a4e84060e6ef628ae9c69f2ee386d4" } ] }, @@ -1293,7 +1293,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "69ce0757ceafdd4371bb9fd30155b0a1b9d217b86b28b0c3017e40f50341a261" + "code_sha256": "aa092f983d44538da590e878e17619714214785438964836218fa46673036b32" } ] }, @@ -1306,7 +1306,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "207b283c868a152a256499c22a8c326ef2964e886470af161555e4d593184ab6" + "code_sha256": "3557552195e6944fa2653b52284e1c8b4b285e800a049e1724c87e374a51fb9a" }, { "path": "/actions/1", @@ -1319,7 +1319,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "8b7eeb51061f9da9222cf5b187679b58ee8f8c89640ef0f04985b6a141f8f513" + "code_sha256": "480d37a1caf87be1ac0c99b6ecce5f7eb25e70ea7958eccfb53d9e484f1b352a" } ] }, @@ -1332,7 +1332,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "165025885224b0ee3c3c74ee87ece42d292eb524d694ac46156db2661e2f2885" + "code_sha256": "505e9eadce7c52a666f3b4a528d9f3dd035103e38d8d79eaca9abd5cfee00027" } ] }, @@ -1345,7 +1345,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "24cfa7e9ccac2ea0cd7437d08268cfc71776a65cbfd30372d48dce2d44237695" + "code_sha256": "21cd8b62aaa32ba5a95feb5c60533011e9e0cfd7cc630899f2e5c1e0bdc0e823" } ] }, @@ -1358,7 +1358,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "2d14a0e71bb6ad4807f9361fd379d4531025e37a027a3794463417739a2675da" + "code_sha256": "bf1449c75ac1c16a9c3feb4736e5dd40501078b8da8633077f81cd17096d5093" } ] }, @@ -1371,7 +1371,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "e3b507ae9d6b3c93110843d486d946b3c60a57d3946d555b4913ad45ce0421d4" + "code_sha256": "a74f33983a126299d7b43170422f0c65fb33b4290c511917034a6ca1bfa474c1" } ] }, @@ -1384,7 +1384,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "f7962e164ada6d946cfcacaecdc0c9faf5a644f40d9dd59d838c8ba8eadafb75" + "code_sha256": "6c349935ac48af7a9ac88c62acbd068ce6f11b868980ae7ac242257e52411b86" } ] }, @@ -1397,7 +1397,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "2ac66d02a50a28ca257a7ca29db2c889f526232cff0966f4ef1540f469f0086f" + "code_sha256": "01ccd02cfb0ec3189219b9f40eecd1973fc578889a8673ab0e357d134b4d47d1" }, { "path": "/actions/1", @@ -1410,7 +1410,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "d1d7a101fc37bb9df5bbd36ae53daaddff842d0805502d5981ab9549b1cefcc0" + "code_sha256": "835b159652ba41535061500f38d854d21ff1bf6248af20ef4eaeaf27e70140ff" } ] }, @@ -1423,7 +1423,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "6ce377baeb157712a931eed1841ed49abd80e35ec555f499e6218ef56852cf42" + "code_sha256": "205f3ebf85af5424b170fa26041dc12ec9ec126db1e33e1fa85899adab49d341" } ] }, @@ -1436,7 +1436,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "28ff2644edbfd9ae06fe59b342b28f594bd93c8ede7bf0121fee143c2dba2dd1" + "code_sha256": "9859172a48c93fb4e1ffa32020def915af1d9a87403ac9f5008606e9723408d9" } ] }, @@ -1449,7 +1449,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "24847650286455761816d9e591374331e7bc1b07f947bb46da2a40ed29e94107" + "code_sha256": "6d077b710db2a3e12d29491938db90a150e31cb56e5fc3970072a2a180ecbe9a" } ] }, @@ -1462,7 +1462,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "df64ef6b951bff53cf9d112beed8fa48a90505609d30769d0ed9438beea8c4be" + "code_sha256": "cbe0c6d253728a2f92a8a385f3b50238c59e18b92491b8fbccd8b06f166df486" } ] }, @@ -1475,7 +1475,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "40f2171f8f5961701e504bac3229aad182836315a01613fcc56de44ca5903521" + "code_sha256": "d8ff78728974ed18d0c2aad225dfb0a2db3934ea27c61a25ebbc7cf1c8af6fb6" } ] } diff --git a/modules.json b/modules.json index 54e549c..a216f4f 100644 --- a/modules.json +++ b/modules.json @@ -31,7 +31,7 @@ }, { "key": "document-studio", - "version": "0.3.0", + "version": "0.4.0", "manifest": "document-studio/module.yaml", "workflows": 15, "miniapps": 1 diff --git a/templates/company-in-a-box/compose.py b/templates/company-in-a-box/compose.py index c5c00ea..97af52b 100755 --- a/templates/company-in-a-box/compose.py +++ b/templates/company-in-a-box/compose.py @@ -26,7 +26,7 @@ OPTIONAL_SERVICES = { "documents": { "module_dir": "document-studio", - "version": "0.3.0", + "version": "0.4.0", "role": "cib_documents", # document-read carries no required_role, like contenu-read: any member of the Application may call it # and the ACL of each shared record decides what it returns. None = no role. diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index 84df772..4dbb5d8 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -2,8 +2,8 @@ """Generate the document-studio Module resources (manifest, Workflows, MiniApp). No rendering engine lives in the Module: rendering goes through the MCP tool -`artifact_render_v1`. The two reference templates (quote and -meeting-minutes) are embedded as text in the Workflows that render; they are +`artifact_render_v1`. The three reference templates (quote, +meeting-minutes and dashboard) 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, @@ -18,7 +18,7 @@ MODULE = ROOT.parents[1] / 'document-studio' DEST = MODULE / 'agents/main' TEMPLATES_DIR = MODULE / 'examples/templates' -VERSION = '0.3.0' +VERSION = '0.4.0' RENDER_TOOL = 'artifact_render_v1' STORAGE_TOOLS = ['read_file', 'write_file', 'list_files'] RENDER_TOOLS = STORAGE_TOOLS + [RENDER_TOOL] @@ -57,10 +57,12 @@ 'payment_terms': {'type': 'string'}}, } TEMPLATE_META = { - 'quote': {'prefix': 'DEV', 'draft_schema': QUOTE_DRAFT_SCHEMA, + 'quote': {'prefix': 'DEV', 'label': 'Devis', '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, + 'meeting-minutes': {'prefix': 'CR', 'label': 'Compte rendu de réunion', 'draft_schema': None, 'summary': 'Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).'}, + 'dashboard': {'prefix': 'TB', 'label': 'Tableau de bord', 'draft_schema': None, + 'summary': 'Tableau de bord : six graphiques (barres, lignes, camembert, Gantt, organigramme, processus) à partir de données chart/v1 ; le moteur les trace, rien n\'est calculé par le modèle.'}, } @@ -165,7 +167,7 @@ def load_templates(with_files): } // Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false, -// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum. +// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum, const, anyOf. function checkSchema(schema, value, path, root, errors) { if (errors.length >= 8) return; if (schema.$ref) { @@ -186,6 +188,8 @@ def load_templates(with_files): if (!ok) { errors.push(path + " : type " + types.join("|") + " attendu"); return; } } if (schema.enum && !schema.enum.includes(value)) errors.push(path + " : valeur hors liste"); + if (schema.const !== undefined && value !== schema.const) errors.push(path + " : valeur attendue " + JSON.stringify(schema.const)); + if (Array.isArray(schema.anyOf) && !schema.anyOf.some((alt) => { const sub = []; checkSchema(alt, value, path, root, sub); return sub.length === 0; })) errors.push(path + " : aucune des variantes admises"); if (typeof value === "string") { if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + " : vide ou trop court"); if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + " : trop long"); @@ -294,6 +298,13 @@ def load_templates(with_files): 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(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || ""}; } +// Title of a document from its (validated) data; fallbackTitle is the same on raw model output, before validation. +function documentTitle(key, d) { return key === "quote" ? "Devis " + d.customer.name : key === "meeting-minutes" ? d.meeting.title : d.title; } +function fallbackTitle(key, d) { + if (key === "quote") return "devis " + (isObject(d.customer) ? d.customer.name : ""); + if (key === "meeting-minutes") return isObject(d.meeting) ? d.meeting.title : key; + return typeof d.title === "string" && d.title ? d.title : key; +} 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. @@ -990,7 +1001,8 @@ def schema(required, **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']) +TEMPLATE_KEY = text('Template key', enum=list(TEMPLATE_META)) +TEMPLATE_OPTIONS = [{'value': key, 'label': meta['label']} for key, meta in TEMPLATE_META.items()] 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 }}'} @@ -1075,9 +1087,9 @@ def llm(action_id, prompt_ref, system, output_key, tokens): 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(); +const id = given ? docIdOf(input.doc_id) : slugify(title || fallbackTitle(key, data)) + "-" + shortSuffix(); data = normalizeData(key, data, id); -if (!title) title = key === "quote" ? "Devis " + data.customer.name : data.meeting.title; +if (!title) title = documentTitle(key, data); 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}; @@ -1273,8 +1285,7 @@ def build(): {'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'}])], + field('brief', 'Brief', 'text', True), field('template_key', 'Gabarit (facultatif)', 'select', False, options=TEMPLATE_OPTIONS)], ['prepare', 'plan-llm', 'normalize'])]) workflow('document-studio-draft', 'Draft a document', @@ -1289,8 +1300,7 @@ def build(): {**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('template_key', 'Gabarit', 'select', True, options=TEMPLATE_OPTIONS), field('title', 'Titre (facultatif)', 'string', False), field('doc_id', 'Identifiant (facultatif)', 'string', False)], ['prepare', 'draft-llm', 'create'])]) diff --git a/tooling/document-studio/contract/PIN.json b/tooling/document-studio/contract/PIN.json index 8d60793..0efd0ac 100644 --- a/tooling/document-studio/contract/PIN.json +++ b/tooling/document-studio/contract/PIN.json @@ -1,7 +1,7 @@ { "contract": "agentmaurice.template/v1", "source_path": "contracts/template/v1", - "source_commit": "b2133665efeb7ed8b3358d0aafed8914587526d6", + "source_commit": "00d4ef2541d77af8da6cf699e29e9c5e0855d220", "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": { @@ -109,6 +109,38 @@ "source_sha256": "a7bf1b08964d4cb0569daad0e2da9b117fe7029f3db21fa1c189898449897180", "modified": false } + }, + "dashboard": { + "examples/default.json": { + "source": "golden/valid/dashboard/examples/default.json", + "sha256": "7950ec5d0c0b0704e674cb0200b05217e10e3b14fe723055eda1668293e292c6", + "source_sha256": "7950ec5d0c0b0704e674cb0200b05217e10e3b14fe723055eda1668293e292c6", + "modified": false + }, + "fragments/charts.typ": { + "source": "fragments/charts.typ", + "sha256": "0676f89646954801d6cdfdba31f23774e1352c66dcf257e750b2944ab41a396d", + "source_sha256": "0676f89646954801d6cdfdba31f23774e1352c66dcf257e750b2944ab41a396d", + "modified": false + }, + "input.schema.json": { + "source": "golden/valid/dashboard/input.schema.json", + "sha256": "f43e7fd87f4297e3bca099e5f00bd8573e52b3ef85869b92d09b04d71c44084e", + "source_sha256": "f43e7fd87f4297e3bca099e5f00bd8573e52b3ef85869b92d09b04d71c44084e", + "modified": false + }, + "main.typ": { + "source": "golden/valid/dashboard/main.typ", + "sha256": "c59f167bfe4ccceb83313c7d0e0179e5bed58994001410192e89892114c28f12", + "source_sha256": "c59f167bfe4ccceb83313c7d0e0179e5bed58994001410192e89892114c28f12", + "modified": false + }, + "manifest.json": { + "source": "golden/valid/dashboard/manifest.json", + "sha256": "2c3bfd69870c0dcfe04c851e232e7629bcef82fb919ea10e0490f10a473072c5", + "source_sha256": "2c3bfd69870c0dcfe04c851e232e7629bcef82fb919ea10e0490f10a473072c5", + "modified": false + } } }, "shared": { diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index a1abd20..201d1ac 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -11,6 +11,7 @@ import zipfile import json import re +import shutil import subprocess import tempfile import unittest @@ -295,7 +296,7 @@ def test_embedded_templates_send_no_platform_file(self): 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']) + self.assertEqual(sorted(pin['templates']), ['dashboard', '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) @@ -311,13 +312,13 @@ 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'): + def test_contract_checker_accepts_the_three_templates(self): + for key in ('quote', 'meeting-minutes', 'dashboard'): 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'): + for key in ('quote', 'meeting-minutes', 'dashboard'): manifest = load(TEMPLATES / key / 'manifest.json') self.assertEqual(manifest['source']['engine'], 'typst') for example in manifest['examples']: @@ -339,6 +340,92 @@ def test_render_receives_the_embedded_templates_unchanged(self): self.assertEqual(call['context']['company']['phone'], '') +DASHBOARD_DRAFT = load(TEMPLATES / 'dashboard/examples/default.json') +CHARTS = ('bar', 'line', 'pie', 'gantt', 'org', 'process') + + +class DashboardTest(unittest.TestCase): + """The third reference template: six chart/v1 charts, drawn by the engine from its pinned contract.""" + + def create(self, fs=None, **extra): + ctx = {'prep': {'template_key': 'dashboard', 'locale': 'fr'}, 'draft': DASHBOARD_DRAFT, 'doc_id': 'tb-test', **extra} + out = run_node('document-studio-draft', 'create', ctx, fs if fs is not None else seeded()) + return ok(self, out), out['fs'] + + def test_the_template_is_embedded_pinned_and_declared(self): + self.assertEqual(sorted(build.load_templates(False)), ['dashboard', 'meeting-minutes', 'quote']) + pin = load(TOOLING / 'contract/PIN.json') + self.assertEqual(sorted(pin['templates']['dashboard']), ['examples/default.json', 'fragments/charts.typ', 'input.schema.json', 'main.typ', 'manifest.json']) + self.assertFalse(any(e['modified'] for e in pin['templates']['dashboard'].values())) + manifest = load(TEMPLATES / 'dashboard/manifest.json') + self.assertEqual((manifest['key'], manifest['fragments']), ('dashboard', ['fragments/charts.typ'])) + for workflow in ('document-studio-plan', 'document-studio-draft'): + self.assertIn('dashboard', load(WORKFLOWS / f'{workflow}.json')['input_schema']['properties']['template_key']['enum']) + self.assertEqual(build.TEMPLATE_META['dashboard']['prefix'], 'TB') + + def test_the_example_data_validates_the_input_schema(self): + summary, _ = self.create() + self.assertEqual((summary['template_key'], summary['title'], summary['status']), ('dashboard', 'Tableau de bord Activité 2026', 'draft')) + self.assertEqual(summary['computed'], DASHBOARD_DRAFT) + for chart in CHARTS: + self.assertEqual(summary['data'][chart]['type'], chart) + bad = json.loads(json.dumps(DASHBOARD_DRAFT)) + del bad['pie'] + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'dashboard', 'locale': 'fr'}, 'draft': bad, 'doc_id': 'tb-test'}, {}) + self.assertTrue(out['error'].startswith('data_invalid'), out) + bad = json.loads(json.dumps(DASHBOARD_DRAFT)) + bad['bar']['type'] = 'pie' + self.assertTrue(run_node('document-studio-draft', 'create', {'prep': {'template_key': 'dashboard', 'locale': 'fr'}, 'draft': bad, 'doc_id': 'tb-test'}, {})['error'].startswith('data_invalid')) + bad = json.loads(json.dumps(DASHBOARD_DRAFT)) + bad['pie']['parts'][0]['value'] = 0.001 # chart/v1 number: 0 or at least 0.01 + self.assertTrue(run_node('document-studio-draft', 'create', {'prep': {'template_key': 'dashboard', 'locale': 'fr'}, 'draft': bad, 'doc_id': 'tb-test'}, {})['error'].startswith('data_invalid')) + + def test_the_title_comes_from_the_data_and_the_id_is_derived_from_it(self): + out = run_node('document-studio-draft', 'create', {'prep': {'template_key': 'dashboard', 'locale': 'fr'}, 'draft': DASHBOARD_DRAFT}, {}) + summary = ok(self, out) + self.assertEqual(summary['title'], 'Tableau de bord Activité 2026') + self.assertRegex(summary['doc_id'], r'^tableau-de-bord-activite-2026-[a-z0-9]+$') + + def test_render_sends_the_template_without_fragments_and_publish_numbers_it(self): + _, fs = self.create() + out = run_node('document-studio-render', 'render', {'doc_id': 'tb-test'}, fs) + rendered = ok(self, out) + call = next(c for c in out['calls'] if c['name'] == 'artifact_render_v1')['full'] + directory = TEMPLATES / 'dashboard' + self.assertEqual(sorted(call['template']['files']), ['examples/default.json', 'input.schema.json', 'main.typ', 'manifest.json']) + self.assertEqual(call['template']['files']['main.typ'], (directory / 'main.typ').read_text(encoding='utf-8')) + self.assertEqual(call['template']['manifest'], load(directory / 'manifest.json')) + self.assertEqual(call['data'], DASHBOARD_DRAFT) + self.assertEqual((call['output'], call['mode']), ('pdf', 'preview')) + self.assertEqual((rendered['status'], rendered['renders']), ('draft', 1)) + approved = run_node('document-studio-finalize', 'finalize', {'doc_id': 'tb-test', 'confirmation_manuelle': 'oui'}, out['fs']) + self.assertEqual(ok(self, approved)['status'], 'approved') + published = ok(self, run_node('document-studio-publish', 'publish', {'doc_id': 'tb-test', 'confirmation_manuelle': True}, approved['fs'])) + self.assertEqual((published['status'], published['number']), ('issued', f'TB-{YEAR}-0001')) + + def test_the_other_actions_handle_the_third_template(self): + _, fs = self.create() + listing = ok(self, run_node('document-studio-list', 'list', {'template_key': 'dashboard'}, fs)) + self.assertEqual([d['doc_id'] for d in listing['items']], ['tb-test']) + one = ok(self, run_node('document-studio-template-read', 'read', {'template_key': 'dashboard'})) + self.assertEqual((one['template']['prefix'], one['template']['title']), ('TB', 'Tableau de bord')) + rendered = run_node('document-studio-render', 'render', {'doc_id': 'tb-test'}, fs) + exported = ok(self, run_node('document-studio-export', 'export', {'doc_id': 'tb-test', 'destination_path': '/envois/tb.pdf'}, rendered['fs'])) + self.assertIn('/envois/tb.pdf', json.dumps(exported)) + plan = run_node('document-studio-plan', 'prepare', {'brief': 'Un tableau de bord', 'template_key': 'dashboard'}) + self.assertEqual(ok(self, plan)['template_key'], 'dashboard') + + def test_the_reference_renderer_compiles_the_template_when_the_contract_is_next_to_it(self): + tool = CONTRACT_CHECK.parent / 'render_reference/main.go' + if not tool.exists() or not shutil.which('go'): + self.skipTest('the contract checkout or the go toolchain is not available') + with tempfile.TemporaryDirectory() as out: + proc = subprocess.run(['go', 'run', str(tool), '-template', str(TEMPLATES / 'dashboard'), '-out', out], cwd=tool.parents[2], capture_output=True, text=True) + if proc.returncode != 0 and 'typst' in (proc.stdout + proc.stderr).lower() and 'not found' in (proc.stdout + proc.stderr).lower(): + self.skipTest('no Typst compiler available to the reference renderer') + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + + class MiniAppTest(unittest.TestCase): def test_the_document_id_is_typed_in_a_workflow_form_and_buttons_target_events(self): # The MiniApp vocabulary has no input component: fields come from the form of the targeted Workflow. @@ -582,7 +669,7 @@ def test_null_handling_in_drafts(self): 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'}) + self.assertEqual({t['template_key'] for t in listing['templates']}, {'quote', 'meeting-minutes', 'dashboard'}) 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'])