From 0fddc527ffe4e3976d2cc6d92e9f4e020fc21b3e Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Mon, 9 Nov 2026 05:59:03 +0100 Subject: [PATCH 1/5] AGENT-1831: document-studio 0.2.0, shared document references through the ACL broker, optional CIB service - document-share / document-read: publish the reference of an issued document (doc_id, title, type, number, version, Storage path, sha256) as a recipe--application_data_v1 record (namespace cib-documents) and grant or remove read per member, like contenu-share / contenu-read. PDF stays in Storage. - template compose.py: --with-service documents adds the optional Documents Agent and writes a surface draft with required_role on every Workflow. - tests for the Workflows (mock broker) and the composer; inventory and catalog regenerated. Co-Authored-By: Claude Opus 5.5 --- catalog.json | 15 +- document-studio/README.md | 24 ++- .../agents/main/workflows/document-read.json | 62 ++++++++ .../agents/main/workflows/document-share.json | 142 ++++++++++++++++++ document-studio/module.yaml | 14 +- inventory/modules.json | 48 +++++- modules.json | 4 +- templates/company-in-a-box/compose.py | 65 +++++++- .../company-in-a-box/tests/documents.json | 59 ++++++++ .../company-in-a-box/tests/test_compose.py | 52 +++++++ tooling/document-studio/build.py | 131 +++++++++++++++- tooling/document-studio/tests/test_module.py | 119 ++++++++++++++- 12 files changed, 714 insertions(+), 21 deletions(-) create mode 100644 document-studio/agents/main/workflows/document-read.json create mode 100644 document-studio/agents/main/workflows/document-share.json create mode 100644 templates/company-in-a-box/tests/documents.json diff --git a/catalog.json b/catalog.json index 4595178..9fd85c2 100644 --- a/catalog.json +++ b/catalog.json @@ -643,11 +643,11 @@ { "key": "document-studio", "name": "Document studio", - "version": "0.1.0", + "version": "0.2.0", "subpath": "document-studio", "manifest": "document-studio/module.yaml", - "manifest_sha256": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", - "tree_sha256": "5cc05c17fa5dea65b2b71bd76521530f4aa046fcb50a915c6b3aff3eb4bcb268", + "manifest_sha256": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", + "tree_sha256": "31136edf483f1df0d257845a8836799e42d9933ae725dad97d88c41247fa6c50", "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." @@ -692,12 +692,17 @@ { "key": "document-studio-profile-save", "name": "Save the company profile" + }, + { + "key": "document-share", + "name": "Share an issued document" } ], "queries": [ "document-studio-list", "document-studio-review-read", - "document-studio-template-read" + "document-studio-template-read", + "document-read" ], "requires": { "runtimes": [ @@ -712,7 +717,7 @@ "model": "free" }, "maturity": "preview", - "workflows": 11, + "workflows": 13, "miniapps": 1 }, { diff --git a/document-studio/README.md b/document-studio/README.md index 1e24b28..934180c 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -26,6 +26,8 @@ messages) is French; `fr` is the only locale in V0. | `document-studio-list` | lists the documents (identifier, title, status, number, revision, latest hash) | | `document-studio-review-read` | full record of a document and previews of its latest render, for the MiniApp | | `document-studio-template-read` | lists the templates, or the manifest and data schemas of one template | +| `document-share` | publishes the reference of an **issued** document as a record of the native application data broker (`recipe--application_data_v1`, namespace `cib-documents`, key `doc_id`), then grants or removes `read` for one member. Requires `confirmation_manuelle`. The PDF stays in Storage | +| `document-read` | reads one shared reference through the broker (with the caller's permissions), or lists the references the caller may read when `doc_id` is empty | The `document-studio-review` MiniApp has no input component of its own (the MiniApp vocabulary has none): the document identifier (`doc_id`) is typed in @@ -35,6 +37,26 @@ table of renders (revision, mode, hash, path), refreshes it, and triggers a new render. Approval and issue go through the Workflow forms, with the manual confirmation. +## Sharing with the company + +Sharing follows the `cib-contenu` pattern: the broker holds one record per document and enforces a per-member ACL; a +record is private to its owner until `document-share` grants `read` (`write` is refused on purpose: a member must not +be able to rewrite the reference). `expected_revision` is `0` for the first publication, then the revision returned by +the previous call (compare-and-set). The shared record (`document-studio.shared/v1`) holds `doc_id`, `title`, +`template_key`, `number`, `version` (the revision of the Storage record at issue), `path` (Storage path of the issued +PDF), `sha256` and `issued_at`. Removing access (`none`) does not need the Storage record, so it still works after a +cancellation; a cancelled document stays referenced until its owner removes the members. Reading the PDF itself is a +Storage right, separate from the ACL of the reference. + +## Optional service in the Company-in-a-Box template + +`templates/company-in-a-box/compose.py --with-service documents` adds this Module as an optional fourth Agent +(`documents`, spec-init'ed in the consumer like the three roles; off by default). Besides the resources and the test +plan it writes `surface-drafts/cib-documents.surface-draft.json`, with `required_role` on every Workflow: `cib_documents` +for the owner of the service, `cib_admin` for `document-studio-profile-save`. Role grants and the ACL of each record are +cumulative; the Module never grants a role or a share. The Administration select of `cib-admin-manage` does not list +`cib_documents` yet. + ## Lifecycle `draft` (successive renders) → `approved` → `issued`. `cancelled` is reachable @@ -111,7 +133,7 @@ renderer, on synthetic data. They do not prove the behavior on a One. ## Known limits (V0) -- The brand is read from Storage only. The `profile` Module keeps the profile in an application record whose broker is not wired in the One yet: calling the `cib-profile-read` Workflow would make every render fail until then. +- The brand is still read from Storage (`/document-studio/profile.json`), not from the `cib-profile` record of the `profile` Module, although the broker now exists: switching the source is a separate change of `render` and `publish`. - The logo is a reference (`storage://…`); this Module does not resolve it to a file before rendering. - Number reservation is not atomic: it lists, writes without overwrite, reads back and checks the owner, at most 5 attempts (`number_conflict`). A number reserved then lost (failed render) stays reserved: it is taken again on the next attempt, never reused by another document. Atomic sequences are a platform follow-up. - No sending (mail, SFTP), no DOCX, one locale (`fr`). diff --git a/document-studio/agents/main/workflows/document-read.json b/document-studio/agents/main/workflows/document-read.json new file mode 100644 index 0000000..63ab21d --- /dev/null +++ b/document-studio/agents/main/workflows/document-read.json @@ -0,0 +1,62 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-read", + "kind": "workflow", + "title": "Read shared documents", + "version": "1", + "description": "Reads, through the native application data broker, the reference of one shared document (with the permissions of the caller), or lists the references the caller may read when doc_id is empty. Only the rights of the caller apply.", + "input_schema": { + "type": "object", + "required": [], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + } + } + }, + "forms": [ + { + "id": "document-read", + "title": "Relire un document partagé", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document (vide pour la liste)", + "type": "string", + "required": false + } + ], + "actions_on_submit": [ + "read" + ] + } + ], + "actions": [ + { + "id": "read", + "type": "code_execution", + "context": { + "allowed_tools": [ + "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 . }};\nif (input.doc_id === undefined || input.doc_id === null || input.doc_id === \"\") {\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};\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\");\nreturn {...brokerView(item), items: [], total: 1};\n", + "output_key": "result" + } + ], + "output": { + "record": "{{ result.record }}", + "revision": "{{ result.revision }}", + "owner_user_id": "{{ result.owner_user_id }}", + "permissions": "{{ result.permissions }}", + "permissions_summary": "{{ result.permissions_summary }}", + "shares": "{{ result.shares }}", + "share_count": "{{ result.share_count }}", + "items": "{{ result.items }}", + "total": "{{ result.total }}" + } +} diff --git a/document-studio/agents/main/workflows/document-share.json b/document-studio/agents/main/workflows/document-share.json new file mode 100644 index 0000000..99142f7 --- /dev/null +++ b/document-studio/agents/main/workflows/document-share.json @@ -0,0 +1,142 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "workflow_id": "document-share", + "kind": "workflow", + "title": "Share an issued document", + "version": "1", + "description": "Publishes the reference of an issued document (identifier, title, type, number, version, Storage path and SHA-256 of the PDF) as a record of the native application data broker, then grants or removes read access for one member. The PDF stays in Storage. A record is private to its owner until shared; sharing never gives access to the service. expected_revision is 0 for the first publication, else the revision returned by the previous call.", + "input_schema": { + "type": "object", + "required": [ + "doc_id", + "confirmation_manuelle" + ], + "additionalProperties": false, + "properties": { + "doc_id": { + "type": "string", + "description": "Document identifier: lowercase letters, digits and hyphens", + "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + }, + "confirmation_manuelle": { + "type": [ + "boolean", + "string" + ], + "description": "Manual confirmation: oui (or true) to proceed" + }, + "expected_revision": { + "type": [ + "integer", + "string" + ], + "description": "0 (or empty) to create the reference, else the current revision of the shared record" + }, + "share_subject_user_id": { + "type": "string", + "description": "Member to grant or remove; empty to only publish the reference" + }, + "share_permission": { + "type": "string", + "description": "Right of the member", + "enum": [ + "read", + "none" + ] + } + } + }, + "forms": [ + { + "id": "document-share", + "title": "Partager un document émis", + "fields": [ + { + "name": "doc_id", + "title": "Identifiant du document", + "type": "string", + "required": true + }, + { + "name": "expected_revision", + "title": "Révision attendue (0 pour une première publication)", + "type": "string", + "required": true, + "default": "0" + }, + { + "name": "share_subject_user_id", + "title": "Membre", + "type": "string", + "required": false + }, + { + "name": "share_permission", + "title": "Droit", + "type": "select", + "required": true, + "options": [ + { + "value": "read", + "label": "Lecture" + }, + { + "value": "none", + "label": "Retirer" + } + ], + "default": "read" + }, + { + "name": "confirmation_manuelle", + "title": "Confirmation manuelle", + "type": "select", + "required": true, + "options": [ + { + "value": "non", + "label": "Non" + }, + { + "value": "oui", + "label": "Oui" + } + ], + "default": "non" + } + ], + "actions_on_submit": [ + "share" + ] + } + ], + "actions": [ + { + "id": "share", + "type": "code_execution", + "context": { + "allowed_tools": [ + "read_file", + "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.\" : \"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" + } + ], + "output": { + "doc_id": "{{ result.doc_id }}", + "record": "{{ result.record }}", + "revision": "{{ result.revision }}", + "owner_user_id": "{{ result.owner_user_id }}", + "permissions": "{{ result.permissions }}", + "permissions_summary": "{{ result.permissions_summary }}", + "shares": "{{ result.shares }}", + "share_count": "{{ result.share_count }}", + "shared_with": "{{ result.shared_with }}", + "message": "{{ result.message }}", + "scope": "internal_only", + "external_effect": false + } +} diff --git a/document-studio/module.yaml b/document-studio/module.yaml index 37cdb42..e29fb96 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.1.0", + "version": "0.2.0", "provides": { "actions": [ { @@ -53,6 +53,12 @@ "name": "Save the company profile", "workflow_id": "document-studio-profile-save", "workflow_version": "1" + }, + { + "key": "document-share", + "name": "Share an issued document", + "workflow_id": "document-share", + "workflow_version": "1" } ], "queries": [ @@ -73,6 +79,12 @@ "name": "Read the templates", "workflow_id": "document-studio-template-read", "workflow_version": "1" + }, + { + "key": "document-read", + "name": "Read shared documents", + "workflow_id": "document-read", + "workflow_version": "1" } ], "apps": [ diff --git a/inventory/modules.json b/inventory/modules.json index ac924ce..edc515b 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1205,9 +1205,9 @@ }, { "key": "document-studio", - "version": "0.1.0", + "version": "0.2.0", "manifest": "document-studio/module.yaml", - "workflows": 11, + "workflows": 13, "miniapps": 1, "source": { "repository": "github.com/agentmaurice/modules", @@ -1218,6 +1218,8 @@ ], "resources": { "workflows": [ + "document-studio/agents/main/workflows/document-read.json", + "document-studio/agents/main/workflows/document-share.json", "document-studio/agents/main/workflows/document-studio-cancel.json", "document-studio/agents/main/workflows/document-studio-draft.json", "document-studio/agents/main/workflows/document-studio-export.json", @@ -1234,7 +1236,9 @@ "document-studio/agents/main/miniapps/document-studio-review.json" ], "sha256": { - "document-studio/module.yaml": "89c05d34793969a8fccb1b767f9b6aa87bda29d6fb9edaf4f80e1f827e2a0299", + "document-studio/module.yaml": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", + "document-studio/agents/main/workflows/document-read.json": "4c1e20b58a546f415f480145882523ae607fabfbf784eac5de02d1ad3515a2ef", + "document-studio/agents/main/workflows/document-share.json": "a37a4d7bbe729c74b769f26c85a3c4766d691ca76821cdc846abe816b15ebdb2", "document-studio/agents/main/workflows/document-studio-cancel.json": "899e24cb5688d92497891ea09a3181f64093df9d2802d818da78f1298f807965", "document-studio/agents/main/workflows/document-studio-draft.json": "72be0b86b67c6fc4392bff1795c38c59763334582fedf1ccdd95b296e9492b4e", "document-studio/agents/main/workflows/document-studio-export.json": "52aa5bcc2ee64715be59fab234804fcebd3cc1cfec4e32dd5f9ea5d69c9371db", @@ -1250,6 +1254,32 @@ } }, "workflow_actions": { + "document-studio/agents/main/workflows/document-read.json": { + "workflow_id": "document-read", + "actions": [ + { + "path": "/actions/0", + "id": "read", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "ea1e3c187debf0615c24169bd8b9eb8e054c11b4184e696d17606c6fe7c78981" + } + ] + }, + "document-studio/agents/main/workflows/document-share.json": { + "workflow_id": "document-share", + "actions": [ + { + "path": "/actions/0", + "id": "share", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "1b5d8e9c893c9bc45e81c5107585cb3d8f42fdc75b50ccaf963e5cf1481564d9" + } + ] + }, "document-studio/agents/main/workflows/document-studio-cancel.json": { "workflow_id": "document-studio-cancel", "actions": [ @@ -1469,6 +1499,12 @@ "name": "Save the company profile", "workflow_id": "document-studio-profile-save", "workflow_version": "1" + }, + { + "key": "document-share", + "name": "Share an issued document", + "workflow_id": "document-share", + "workflow_version": "1" } ], "queries": [ @@ -1489,6 +1525,12 @@ "name": "Read the templates", "workflow_id": "document-studio-template-read", "workflow_version": "1" + }, + { + "key": "document-read", + "name": "Read shared documents", + "workflow_id": "document-read", + "workflow_version": "1" } ], "apps": [ diff --git a/modules.json b/modules.json index 0a9c9af..f9c720c 100644 --- a/modules.json +++ b/modules.json @@ -31,9 +31,9 @@ }, { "key": "document-studio", - "version": "0.1.0", + "version": "0.2.0", "manifest": "document-studio/module.yaml", - "workflows": 11, + "workflows": 13, "miniapps": 1 }, { diff --git a/templates/company-in-a-box/compose.py b/templates/company-in-a-box/compose.py index eeb2d1e..7a78e0f 100755 --- a/templates/company-in-a-box/compose.py +++ b/templates/company-in-a-box/compose.py @@ -17,6 +17,22 @@ MODULE_DIRS = {"veille": "watch", "contenu": "content", "accompagnement": "support"} MODULE_VERSION = "0.2.4" +# Optional services are off unless asked with --with-service. Each one is an +# extra Agent (alias = service name) that must already be spec-init'ed in the +# consumer. `role` is the business role of the service owner ("responsable") and +# is carried explicitly, per Workflow, in the surface draft written next to the +# copied files; `gates` overrides it for the Workflows an administrator owns. +# Role grants and per-record ACL stay cumulative, as for the three roles. +OPTIONAL_SERVICES = { + "documents": { + "module_dir": "document-studio", + "version": "0.2.0", + "role": "cib_documents", + "gates": {"document-studio-profile-save": "cib_admin"}, + }, +} +SURFACE_DRAFT_DIR = "surface-drafts" + # A consumer composed at 0.2.3 may already contain the old console. Only # these exact source bytes are a supported in-place upgrade; any other # destination divergence remains an operator conflict. @@ -85,7 +101,7 @@ def load_json(path: Path) -> dict: return value -def validate_module(module_root: Path, role: str, errors: list[str]) -> None: +def validate_module(module_root: Path, role: str, errors: list[str], version: str = MODULE_VERSION) -> None: manifest_path = module_root / "module.yaml" try: manifest = load_json(manifest_path) @@ -102,7 +118,7 @@ def validate_module(module_root: Path, role: str, errors: list[str]) -> None: errors.append(f"forbidden legacy path {module_root / forbidden_path}") if not isinstance(manifest.get("key"), str) or not manifest["key"]: errors.append(f"module key missing: {manifest_path}") - if manifest.get("version") != MODULE_VERSION: + if manifest.get("version") != version: errors.append(f"unexpected bundle version in {manifest_path}: {manifest.get('version')!r}") workflows = module_root / "agents" / "main" / "workflows" miniapps = module_root / "agents" / "main" / "miniapps" @@ -134,6 +150,21 @@ def validate_agent_spec(path: Path, role: str, errors: list[str]) -> None: errors.append(f"consumer spec agent_id is empty: {path}") +def surface_draft(source_root: Path, service: str, agent_spec: Path) -> str: + """Surface entries of an optional service, with `required_role` on every Workflow (never left to a naming convention).""" + config = OPTIONAL_SERVICES[service] + manifest = load_json(source_root / config["module_dir"] / "module.yaml") + agent_id = load_json(agent_spec)["agent_id"] + provides = manifest["provides"] + workflows = [ + {"agent_id": agent_id, "workflow_id": ref["workflow_id"], "version": ref["workflow_version"], + "required_role": config["gates"].get(ref["workflow_id"], config["role"])} + for ref in provides["actions"] + provides["queries"] + ] + miniapps = [{"agent_id": agent_id, "miniapp_id": a["miniapp_id"], "version": a["miniapp_version"]} for a in provides["apps"]] + return json.dumps({"public_surface": {"workflows": workflows, "miniapps": miniapps}}, indent=2) + "\n" + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( @@ -148,6 +179,13 @@ def main() -> int: default=Path(__file__).resolve().parents[2], help="Racine du dépôt contenant les Modules et templates/", ) + parser.add_argument( + "--with-service", + action="append", + default=[], + choices=sorted(OPTIONAL_SERVICES), + help="Ajouter un service optionnel (Agent déjà spec-init sous le même alias) ; aucun par défaut", + ) parser.add_argument( "--write", action="store_true", @@ -159,15 +197,20 @@ def main() -> int: errors: list[str] = [] planned: list[tuple[Path, Path]] = [] - for role in ROLES: - module_root = source_root / MODULE_DIRS[role] + drafts: list[tuple[Path, str]] = [] + targets = [(role, MODULE_DIRS[role], MODULE_VERSION) for role in ROLES] + for service in dict.fromkeys(args.with_service): + config = OPTIONAL_SERVICES[service] + targets.append((service, config["module_dir"], config["version"])) + for role, module_dir, version in targets: + module_root = source_root / module_dir manifest = module_root / "module.yaml" workflows = module_root / "agents" / "main" / "workflows" miniapps = module_root / "agents" / "main" / "miniapps" test_plan = source_root / "templates/company-in-a-box/tests" / f"{role}.json" agent_spec = consumer / "agents" / role / "agent-spec.json" - validate_module(module_root, role, errors) + validate_module(module_root, role, errors, version) if agent_spec.exists(): validate_agent_spec(agent_spec, role, errors) for required in (manifest, workflows, miniapps, test_plan, agent_spec): @@ -185,6 +228,12 @@ def main() -> int: except ValueError as exc: errors.append(str(exc)) planned.append((test_plan, consumer / "agents" / role / "tests" / "test-plan.json")) + if role in OPTIONAL_SERVICES and not errors: + draft_path = consumer / SURFACE_DRAFT_DIR / f"cib-{role}.surface-draft.json" + draft = surface_draft(source_root, role, agent_spec) + if draft_path.exists() and draft_path.read_text(encoding="utf-8") != draft: + errors.append(f"destination conflict (refusing overwrite): {draft_path}") + drafts.append((draft_path, draft)) upgradeable: set[tuple[Path, Path]] = set() for source, destination in planned: @@ -223,6 +272,12 @@ def main() -> int: print(f"ERROR copy verification failed: {destination}", file=sys.stderr) return 3 + for draft_path, draft in drafts: + print(f"surface draft -> {draft_path} (required_role on every Workflow; merge it into the Application surface and publish it yourself)") + if args.write: + draft_path.parent.mkdir(parents=True, exist_ok=True) + draft_path.write_text(draft, encoding="utf-8") + return 0 diff --git a/templates/company-in-a-box/tests/documents.json b/templates/company-in-a-box/tests/documents.json new file mode 100644 index 0000000..d5450fe --- /dev/null +++ b/templates/company-in-a-box/tests/documents.json @@ -0,0 +1,59 @@ +{ + "$schema": "agentmaurice.test_plan/v2", + "schema_version": 2, + "test_plan_id": "documents-regression", + "cases": [ + { + "id": "document-share-without-confirmation", + "description": "Refus avant tout appel : sans confirmation manuelle, document-share n'écrit ni ne partage rien.", + "workflow": { + "workflow_id": "document-share", + "input": { + "doc_id": "devis-demo", + "expected_revision": 0, + "share_subject_user_id": "member-b", + "share_permission": "read", + "confirmation_manuelle": "non" + } + }, + "assertions": [ + { + "type": "status", + "expected": "failed" + } + ] + }, + { + "id": "document-read-invalid-id", + "description": "Refus d'un identifiant de document hors format avant l'appel au broker.", + "workflow": { + "workflow_id": "document-read", + "input": { + "doc_id": "../hors-scope" + } + }, + "assertions": [ + { + "type": "status", + "expected": "failed" + } + ] + }, + { + "id": "document-read-without-proof", + "description": "Exécution technique sans preuve humaine : le broker ACL doit refuser cet accès. Les cas positifs sont vérifiés avec les comptes existants depuis la surface CIB.", + "workflow": { + "workflow_id": "document-read", + "input": { + "doc_id": "devis-demo" + } + }, + "assertions": [ + { + "type": "status", + "expected": "failed" + } + ] + } + ] +} diff --git a/templates/company-in-a-box/tests/test_compose.py b/templates/company-in-a-box/tests/test_compose.py index e95a5d2..86b04b7 100644 --- a/templates/company-in-a-box/tests/test_compose.py +++ b/templates/company-in-a-box/tests/test_compose.py @@ -120,6 +120,58 @@ def test_v024_composes_three_dedicated_sharing_consoles(self): source, consumer = self.make_source_and_consumer(tmp) self.assertEqual(self.run_main(source, consumer), 0) + def add_documents(self, source, consumer, with_agent=True): + shutil.copytree(ROOT / "document-studio", source / "document-studio") + if with_agent: + spec_dir = consumer / "agents" / "documents" + spec_dir.mkdir(parents=True) + (spec_dir / "agent-spec.json").write_text(json.dumps({ + "$schema": "agentmaurice.agent_spec/v2", "schema_version": 2, + "agent_alias": "documents", "agent_id": "agent-documents", + }), encoding="utf-8") + + def test_document_studio_is_an_optional_service_off_by_default(self): + with tempfile.TemporaryDirectory(prefix="cib-template-compose-") as directory: + source, consumer = self.make_source_and_consumer(Path(directory)) + self.add_documents(source, consumer) + self.assertEqual(self.run_main(source, consumer, "--write"), 0) + self.assertFalse((consumer / "agents/documents/workflows").exists()) + self.assertFalse((consumer / "surface-drafts").exists()) + + def test_optional_service_needs_its_agent_and_the_pinned_version(self): + with tempfile.TemporaryDirectory(prefix="cib-template-compose-") as directory: + source, consumer = self.make_source_and_consumer(Path(directory)) + self.add_documents(source, consumer, with_agent=False) + self.assertEqual(self.run_main(source, consumer, "--with-service", "documents", "--write"), 2) + self.assertFalse((consumer / "agents/documents").exists()) + + def test_documents_service_copies_the_module_and_gates_every_workflow_by_role(self): + with tempfile.TemporaryDirectory(prefix="cib-template-compose-") as directory: + source, consumer = self.make_source_and_consumer(Path(directory)) + self.add_documents(source, consumer) + self.assertEqual(self.run_main(source, consumer, "--with-service", "documents"), 0) + self.assertFalse((consumer / "surface-drafts").exists(), "dry-run writes nothing") + self.assertEqual(self.run_main(source, consumer, "--with-service", "documents", "--write"), 0) + for name in ("document-share", "document-read", "document-studio-publish"): + self.assertTrue((consumer / "agents/documents/workflows" / f"{name}.json").is_file(), name) + self.assertTrue((consumer / "agents/documents/tests/test-plan.json").is_file()) + draft = json.loads((consumer / "surface-drafts/cib-documents.surface-draft.json").read_text(encoding="utf-8")) + roles = {w["workflow_id"]: w["required_role"] for w in draft["public_surface"]["workflows"]} + self.assertEqual(len(roles), 13) + self.assertEqual(roles["document-studio-profile-save"], "cib_admin") + self.assertEqual({r for k, r in roles.items() if k != "document-studio-profile-save"}, {"cib_documents"}) + self.assertEqual({w["agent_id"] for w in draft["public_surface"]["workflows"]}, {"agent-documents"}) + self.assertEqual([a["miniapp_id"] for a in draft["public_surface"]["miniapps"]], ["document-studio-review"]) + self.assertEqual(self.run_main(source, consumer, "--with-service", "documents", "--write"), 0, "rerun is idempotent") + (consumer / "surface-drafts/cib-documents.surface-draft.json").write_text("{}", encoding="utf-8") + self.assertEqual(self.run_main(source, consumer, "--with-service", "documents", "--write"), 2, "divergent draft is refused") + + def test_documents_test_plan_targets_existing_workflows(self): + plan = json.loads((ROOT / "templates/company-in-a-box/tests/documents.json").read_text(encoding="utf-8")) + self.assertEqual((plan["$schema"], plan["schema_version"]), ("agentmaurice.test_plan/v2", 2)) + names = {p.stem for p in (ROOT / "document-studio/agents/main/workflows").glob("*.json")} + self.assertLessEqual({c["workflow"]["workflow_id"] for c in plan["cases"]}, names) + if __name__ == "__main__": unittest.main() diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index 1030d83..0b92931 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -18,10 +18,13 @@ MODULE = ROOT.parents[1] / 'document-studio' DEST = MODULE / 'agents/main' TEMPLATES_DIR = MODULE / 'examples/templates' -VERSION = '0.1.0' +VERSION = '0.2.0' RENDER_TOOL = 'artifact_render_v1' STORAGE_TOOLS = ['read_file', 'write_file', 'list_files'] RENDER_TOOLS = STORAGE_TOOLS + [RENDER_TOOL] +BROKER = 'recipe--application_data_v1' +SHARE_TOOLS = ['read_file', BROKER] +NAMESPACE = 'cib-documents' I18N = json.loads((ROOT / 'contract/i18n.fr.json').read_text(encoding='utf-8')) # Draft data of a quote: numbers, never formatted amounts and never totals. @@ -546,6 +549,94 @@ def load_templates(with_files): ''' +BROKER_LIB = r""" +const NAMESPACE = "cib-documents"; + +function brokerItem(response, id) { + const payload = response && response.data ? response.data : response; + const item = payload && payload.record; + if (!isObject(item) || item.namespace !== NAMESPACE || item.key !== id) fail("broker_record_identity_invalid"); + if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail("broker_revision_invalid"); + const p = item.permissions; + if (!isObject(p) || typeof p.can_read !== "boolean" || typeof p.can_write !== "boolean" || typeof p.can_manage !== "boolean") fail("broker_permissions_invalid"); + return item; +} +function brokerView(item) { + const p = item.permissions; + const shares = Array.isArray(item.shares) ? item.shares : []; + 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}; +} +""" + +SHARE_IO = r""" +async function readIssuedRecord(id) { + let raw; + try { + const r = await callTool("read_file", {path: ROOT + "/docs/" + id + "/record.json"}); + 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)); + } catch (e) { + const message = String(e && e.message); + if (/not found|does not exist|no such/i.test(message)) fail("document_not_found", id); + fail("storage_unavailable", message.slice(0, 200)); + } + if (raw === null) fail("storage_read_failed", id); + let rec; + try { rec = JSON.parse(raw); } catch (e) { fail("record_corrupt", id); } + return checkRecord(rec, id); +} +""" + +SHARE_CODE = r""" +const input = {{ json . }}; +requireConfirmation(input); +const id = docIdOf(input.doc_id); +let expected = input.expected_revision; +if (expected === undefined || expected === null || expected === "") expected = 0; +if (typeof expected === "string" && /^[0-9]+$/.test(expected)) expected = Number(expected); +if (!Number.isSafeInteger(expected) || expected < 0) fail("expected_revision_invalid"); +const subject = input.share_subject_user_id === undefined || input.share_subject_user_id === null ? "" : input.share_subject_user_id; +if (typeof subject !== "string" || subject.length > 256 || /[\/\s]/.test(subject)) fail("subject_user_id_invalid"); +const permission = input.share_permission === undefined || input.share_permission === null || input.share_permission === "" ? "read" : input.share_permission; +if (!["read", "none"].includes(permission)) fail("permission_invalid", "lecture ou retrait seulement"); +if (permission === "none" && !subject) fail("subject_user_id_required", "indiquez le membre dont retirer l'accès"); +let revision = expected; +let item = null; +if (permission !== "none") { + const rec = await readIssuedRecord(id); + 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 + ")"); + 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}; + item = brokerItem(await callTool("recipe--application_data_v1", {operation: "save", namespace: NAMESPACE, record_key: id, data, expected_revision: expected}), id); + revision = item.revision; +} +if (subject) { + if (revision < 1) fail("expected_revision_invalid", "révision du record partagé requise pour retirer un accès"); + 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); +} +const view = brokerView(item); +return {...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." : "Référence du document publiée, visible de son propriétaire seul tant qu'aucun membre n'est ajouté.", external_effect: false}; +""" + +READ_CODE = r""" +const input = {{ json . }}; +if (input.doc_id === undefined || input.doc_id === null || input.doc_id === "") { + const response = await callTool("recipe--application_data_v1", {operation: "list", namespace: NAMESPACE, prefix: ""}); + const payload = response && response.data ? response.data : response; + if (!payload || !Array.isArray(payload.items) || !Number.isSafeInteger(payload.total) || payload.total !== payload.items.length) fail("broker_list_invalid"); + const items = payload.items.map((view) => { + const key = typeof view.record_key === "string" ? view.record_key : view.key; + if (typeof key !== "string" || !ID_RE.test(key)) fail("broker_list_key_invalid"); + const d = isObject(view.data) ? view.data : (isObject(view.record) ? view.record : {}); + 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 : {}}; + }); + return {items, total: payload.total, record: null, revision: null, owner_user_id: "", permissions: null, permissions_summary: "", shares: [], share_count: 0}; +} +const id = docIdOf(input.doc_id); +const item = brokerItem(await callTool("recipe--application_data_v1", {operation: "read", namespace: NAMESPACE, record_key: id}), id); +if (!isObject(item.data)) fail("broker_record_data_invalid"); +return {...brokerView(item), items: [], total: 1}; +""" + + def code(*parts): body = ''.join(parts) assert '{{' not in body.replace('{{ json . }}', ''), 'a double-brace sequence in the JavaScript' @@ -961,6 +1052,39 @@ def build(): [node('read', code(lib(templates='meta'), TEMPLATE_READ_CODE), 'result')], {'templates': '{{ result.templates }}', 'template': '{{ result.template }}'}) + workflow('document-share', 'Share an issued document', + 'Publishes the reference of an issued document (identifier, title, type, number, version, Storage path and SHA-256 of ' + 'the PDF) as a record of the native application data broker, then grants or removes read access for one member. ' + 'The PDF stays in Storage. A record is private to its owner until shared; sharing never gives access to the service. ' + 'expected_revision is 0 for the first publication, else the revision returned by the previous call.', + schema(['doc_id', 'confirmation_manuelle'], doc_id=DOC_ID, confirmation_manuelle=CONFIRM, + expected_revision={'type': ['integer', 'string'], 'description': '0 (or empty) to create the reference, else the current revision of the shared record'}, + share_subject_user_id=text('Member to grant or remove; empty to only publish the reference'), + share_permission=text('Right of the member', enum=['read', 'none'])), + [node('share', code(IMPORT, lib(), BROKER_LIB, SHARE_IO, SHARE_CODE), 'result', tools=SHARE_TOOLS)], + {'doc_id': '{{ result.doc_id }}', 'record': '{{ result.record }}', 'revision': '{{ result.revision }}', + 'owner_user_id': '{{ result.owner_user_id }}', 'permissions': '{{ result.permissions }}', + 'permissions_summary': '{{ result.permissions_summary }}', 'shares': '{{ result.shares }}', + 'share_count': '{{ result.share_count }}', 'shared_with': '{{ result.shared_with }}', + 'message': '{{ result.message }}', 'scope': 'internal_only', 'external_effect': False}, + forms=[form('document-share', 'Partager un document émis', [ + field('doc_id', 'Identifiant du document', 'string', True), + field('expected_revision', 'Révision attendue (0 pour une première publication)', 'string', True, default='0'), + field('share_subject_user_id', 'Membre', 'string', False), + field('share_permission', 'Droit', 'select', True, options=[{'value': 'read', 'label': 'Lecture'}, {'value': 'none', 'label': 'Retirer'}], default='read'), + CONFIRM_FIELD], ['share'])]) + + workflow('document-read', 'Read shared documents', + 'Reads, through the native application data broker, the reference of one shared document (with the permissions of the ' + 'caller), or lists the references the caller may read when doc_id is empty. Only the rights of the caller apply.', + schema([], doc_id=DOC_ID), + [node('read', code(IMPORT, lib(), BROKER_LIB, READ_CODE), 'result', tools=[BROKER])], + {'record': '{{ result.record }}', 'revision': '{{ result.revision }}', 'owner_user_id': '{{ result.owner_user_id }}', + 'permissions': '{{ result.permissions }}', 'permissions_summary': '{{ result.permissions_summary }}', + 'shares': '{{ result.shares }}', 'share_count': '{{ result.share_count }}', 'items': '{{ result.items }}', + 'total': '{{ result.total }}'}, + forms=[form('document-read', 'Relire un document partagé', [field('doc_id', 'Identifiant du document (vide pour la liste)', 'string', False)], ['read'])]) + miniapp() manifest() @@ -1015,9 +1139,10 @@ def ref(key, name): 'actions': [ref('document-studio-plan', 'Plan a document'), ref('document-studio-draft', 'Draft a document'), ref('document-studio-render', 'Render a document preview'), ref('document-studio-finalize', 'Approve a document'), ref('document-studio-publish', 'Issue a document'), ref('document-studio-cancel', 'Cancel a document'), - ref('document-studio-export', 'Export a document'), ref('document-studio-profile-save', 'Save the company profile')], + ref('document-studio-export', 'Export a document'), ref('document-studio-profile-save', 'Save the company profile'), + ref('document-share', 'Share an issued document')], 'queries': [ref('document-studio-list', 'List documents'), ref('document-studio-review-read', 'Read a document for review'), - ref('document-studio-template-read', 'Read the templates')], + ref('document-studio-template-read', 'Read the templates'), ref('document-read', 'Read shared documents')], 'apps': [{'key': 'document-studio-review', 'name': 'Document studio', 'miniapp_id': 'document-studio-review', 'miniapp_version': '1'}]}, 'requires': {}, diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index f46c188..52b68f5 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -64,6 +64,36 @@ def load(path): if (opts.bad_page) previews.push({...prev, page: opts.bad_page}); return {status: "ok", mode: args.mode, output: "pdf", file, pages: opts.pages || 1, previews: opts.no_previews ? undefined : previews, provenance: {engine: "mock"}}; } + if (name === "recipe--application_data_v1") { + const brokerRecords = store.__broker || (store.__broker = {}); + const perms = (r) => ({can_read: true, can_write: true, can_manage: true}); + const view = (k, r) => ({namespace: args.namespace, key: k, revision: r.revision, owner_user_id: "owner-1", permissions: perms(r), shares: r.shares, data: r.data}); + if (args.namespace !== "cib-documents") throw new Error("namespace_forbidden"); + if (opts.broker_error) throw new Error(opts.broker_error); + const cur = brokerRecords[args.record_key]; + if (args.operation === "save") { + if ((cur ? cur.revision : 0) !== args.expected_revision) throw new Error("revision_conflict"); + brokerRecords[args.record_key] = {revision: (cur ? cur.revision : 0) + 1, data: args.data, shares: cur ? cur.shares : []}; + return {data: {record: view(args.record_key, brokerRecords[args.record_key])}}; + } + if (args.operation === "share") { + if (!cur) throw new Error("record_not_found"); + if (cur.revision !== args.expected_revision) throw new Error("revision_conflict"); + cur.shares = cur.shares.filter((x) => x.subject_user_id !== args.subject_user_id); + if (args.permission !== "none") cur.shares.push({subject_user_id: args.subject_user_id, permission: args.permission}); + cur.revision += 1; + return {data: {record: view(args.record_key, cur)}}; + } + if (args.operation === "read") { + if (!cur) throw new Error("record_not_found"); + return {data: {record: view(args.record_key, cur)}}; + } + if (args.operation === "list") { + const items = Object.keys(brokerRecords).sort().map((k) => ({record_key: k, ...view(k, brokerRecords[k])})); + return {data: {items, total: items.length}}; + } + throw new Error("operation_unsupported"); + } if (name === "read_file") { if (opts.read_error && args.path.includes(opts.read_error_path || "") && args.encoding === undefined) throw new Error(opts.read_error); const e = store[args.path]; @@ -161,7 +191,7 @@ def test_manifest_lists_every_resource(self): manifest = load(MODULE / 'module.yaml') refs = {r['workflow_id'] for kind in ('actions', 'queries') for r in manifest['provides'][kind]} self.assertEqual(refs, set(self.workflows)) - self.assertEqual(len(refs), 11) + self.assertEqual(len(refs), 13) apps = {r['miniapp_id'] for r in manifest['provides']['apps']} self.assertEqual(apps, {p.stem for p in (MODULE / 'agents/main/miniapps').glob('*.json')}) self.assertEqual((manifest['key'], manifest['schema_version']), ('document-studio', 2)) @@ -873,5 +903,92 @@ def test_list_and_review_read(self): self.assertEqual(review['renders'][0]['mode'], 'preview') +class SharingTest(unittest.TestCase): + def issued(self): + _, fs = create_quote(self, seeded()) + fs = run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs)['fs'] + fs = run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['fs'] + return run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, fs)['fs'] + + def share(self, fs, **extra): + ctx = {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'expected_revision': 0, **extra} + return run_node('document-share', 'share', ctx, fs) + + def test_workflows_use_only_the_broker_and_read_the_record(self): + for name, tools in (('document-share', ['read_file', 'recipe--application_data_v1']), ('document-read', ['recipe--application_data_v1'])): + wf = load(WORKFLOWS / f'{name}.json') + self.assertEqual(wf['actions'][0]['context']['allowed_tools'], tools) + self.assertNotIn('write_file', wf['actions'][0]['code']) + self.assertIn('namespace', load(WORKFLOWS / 'document-share.json')['actions'][0]['code']) + self.assertEqual(load(WORKFLOWS / 'document-share.json')['output']['external_effect'], False) + + def test_share_needs_a_manual_confirmation_before_any_call(self): + out = self.share({}, confirmation_manuelle='non') + self.assertTrue(out['error'].startswith('manual_confirmation_required')) + self.assertEqual(out['calls'], []) + + def test_only_an_issued_document_is_shared(self): + _, fs = create_quote(self, seeded()) + out = self.share(fs, share_subject_user_id='member-b') + self.assertTrue(out['error'].startswith('status_invalid'), out) + self.assertEqual([c['name'] for c in out['calls']], ['read_file']) + + def test_share_publishes_the_reference_then_grants_read(self): + fs = self.issued() + record = json.loads(fs['/document-studio/docs/devis-test/record.json']['text']) + out = self.share(fs, share_subject_user_id='member-b', share_permission='read') + result = ok(self, out) + brokered = [c['args'] for c in out['calls'] if c['name'] == 'recipe--application_data_v1'] + self.assertEqual([c['operation'] for c in brokered], ['save', 'share']) + self.assertEqual((brokered[0]['expected_revision'], brokered[1]['expected_revision']), (0, 1)) + self.assertEqual((brokered[1]['subject_user_id'], brokered[1]['permission']), ('member-b', 'read')) + data = brokered[0]['data'] + self.assertEqual(data, {'schema': 'document-studio.shared/v1', 'doc_id': 'devis-test', 'title': record['title'], + 'template_key': 'quote', 'number': record['number'], 'version': record['revision'], + 'path': record['issued']['file']['path'], 'sha256': record['issued']['file']['sha256'], + 'issued_at': record['issued']['at']}) + self.assertNotIn('content', json.dumps(brokered[0]['data'])) + self.assertEqual((result['revision'], result['share_count'], result['shared_with']), (2, 1, 'member-b')) + self.assertIs(result['external_effect'], False) + self.assertEqual([c['name'] for c in out['calls']].count('write_file'), 0) + + def test_publishing_without_a_member_keeps_the_record_private(self): + out = self.share(self.issued()) + result = ok(self, out) + self.assertEqual([c['args']['operation'] for c in out['calls'] if c['name'] != 'read_file'], ['save']) + self.assertEqual((result['revision'], result['share_count']), (1, 0)) + + def test_removal_does_not_need_the_storage_record_and_wrong_revisions_fail(self): + fs = self.issued() + shared = self.share(fs, share_subject_user_id='member-b') + self.assertIn('error', self.share(shared['fs'], share_subject_user_id='member-b'), 'create again at revision 0 must conflict') + gone = run_node('document-share', 'share', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'expected_revision': '2', + 'share_subject_user_id': 'member-b', 'share_permission': 'none'}, shared['fs']) + self.assertEqual(ok(self, gone)['share_count'], 0) + self.assertEqual([c['name'] for c in gone['calls']], ['recipe--application_data_v1']) + self.assertTrue(run_node('document-share', 'share', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'share_permission': 'none'}, {})['error'].startswith('subject_user_id_required')) + + def test_inputs_are_validated(self): + fs = self.issued() + for extra, code in (({'share_permission': 'write', 'share_subject_user_id': 'm'}, 'permission_invalid'), + ({'share_subject_user_id': 'a b'}, 'subject_user_id_invalid'), + ({'share_subject_user_id': 'a/b'}, 'subject_user_id_invalid'), + ({'expected_revision': -1}, 'expected_revision_invalid'), + ({'doc_id': '../x'}, 'doc_id_invalid')): + out = self.share(fs, **extra) + self.assertTrue(out['error'].startswith(code), (extra, out)) + + def test_read_returns_the_reference_with_permissions_and_lists(self): + fs = self.share(self.issued(), share_subject_user_id='member-b')['fs'] + one = ok(self, run_node('document-read', 'read', {'doc_id': 'devis-test'}, fs)) + self.assertEqual((one['record']['doc_id'], one['revision'], one['total']), ('devis-test', 2, 1)) + self.assertTrue(one['permissions']['can_read']) + listing = ok(self, run_node('document-read', 'read', {}, fs)) + self.assertEqual((listing['total'], [i['doc_id'] for i in listing['items']]), (1, ['devis-test'])) + self.assertEqual(listing['items'][0]['sha256'], one['record']['sha256']) + self.assertIn('error', run_node('document-read', 'read', {'doc_id': 'absent'}, fs)) + self.assertIn('error', run_node('document-read', 'read', {'doc_id': 'devis-test'}, fs, broker_error='access_denied')) + + if __name__ == '__main__': unittest.main() From ac097a0eb4ce850bc7bc2e96922a7f5b69e8494c Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Mon, 9 Nov 2026 06:08:18 +0100 Subject: [PATCH 2/5] AGENT-1831: document-studio reads the company profile from the cib-profile record, Storage as fallback render and publish read recipe--application_data_v1 (read, cib-profile, company-profile), report profile_source (cib-profile|storage) and fall back to /document-studio/profile.json when the record is absent, refused or unreadable. Brand fingerprints (profile_changed) unchanged. loadProfile moves out of the shared Storage helpers so only render and publish declare the broker. Co-Authored-By: Claude Opus 5.5 --- catalog.json | 2 +- document-studio/README.md | 11 ++-- .../workflows/document-studio-cancel.json | 2 +- .../main/workflows/document-studio-draft.json | 2 +- .../workflows/document-studio-export.json | 2 +- .../workflows/document-studio-finalize.json | 2 +- .../main/workflows/document-studio-list.json | 2 +- .../document-studio-profile-save.json | 2 +- .../workflows/document-studio-publish.json | 8 ++- .../workflows/document-studio-render.json | 8 ++- .../document-studio-review-read.json | 2 +- inventory/modules.json | 36 +++++------ tooling/document-studio/build.py | 60 +++++++++++------ tooling/document-studio/tests/test_module.py | 64 +++++++++++++++++++ 14 files changed, 149 insertions(+), 54 deletions(-) diff --git a/catalog.json b/catalog.json index 9fd85c2..1c7ce95 100644 --- a/catalog.json +++ b/catalog.json @@ -647,7 +647,7 @@ "subpath": "document-studio", "manifest": "document-studio/module.yaml", "manifest_sha256": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "tree_sha256": "31136edf483f1df0d257845a8836799e42d9933ae725dad97d88c41247fa6c50", + "tree_sha256": "98de52e864ad811f7a16ffc694e46f07dcdc46579f06029344d6a599de78ad9c", "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 934180c..423c02b 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -68,7 +68,7 @@ The Module never approves on a person's behalf. ## Storage -- `/document-studio/profile.json`: the brand, with the `{schema_version: 1, company, brand}` shape of the template contract. A fictitious example is in `examples/profile.example.json`. +- `/document-studio/profile.json`: the fallback brand (used when `cib-profile` is unavailable), with the `{schema_version: 1, company, brand}` shape of the template contract. A fictitious example is in `examples/profile.example.json`. - `/document-studio/docs//record.json`: the record (`document-studio.record/v1`): status, number, revision (+1 at every write), data, history, renders (path, SHA-256, previews, provenance), issue. - `/document-studio/docs//r-/`: PDF and previews of one render attempt (12 first characters of the PDF SHA-256, so a losing attempt never overwrites another attempt's file). - `/document-studio/docs//issued/-.pdf`: the issued PDF. @@ -78,8 +78,11 @@ The Module never approves on a person's behalf. title with a short suffix. Number: `--` (`DEV` for the quote, `CR` for the minutes). -Without a company profile, `render` and `publish` fail with `profile_missing`: -store the brand with `document-studio-profile-save`. +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 +`cib-profile-read`); `render` and `publish` report the source in `profile_source`. Fallback: `/document-studio/profile.json` +in Storage. Without either, they fail with `profile_missing`. The fingerprints of the brand checked at issue +(`profile_changed`) are computed on the projected profile, whatever its source. ## Templates @@ -133,7 +136,7 @@ renderer, on synthetic data. They do not prove the behavior on a One. ## Known limits (V0) -- The brand is still read from Storage (`/document-studio/profile.json`), not from the `cib-profile` record of the `profile` Module, although the broker now exists: switching the source is a separate change of `render` and `publish`. +- The brand is read from the `cib-profile` record (key `company-profile`) through the broker, by `render` and `publish`. If that record is absent, refused to the caller or unreadable, the Storage copy `/document-studio/profile.json` is used and the output says so (`profile_source`: `cib-profile` or `storage`). A broker refusal is therefore not distinguished from an absent record. `document-studio-profile-save` still writes only the Storage copy: save the profile in `cib-profile` (profile Module) to make it the source. - The logo is a reference (`storage://…`); this Module does not resolve it to a file before rendering. - Number reservation is not atomic: it lists, writes without overwrite, reads back and checks the owner, at most 5 attempts (`number_conflict`). A number reserved then lost (failed render) stays reserved: it is taken again on the next attempt, never reused by another document. Atomic sequences are a platform follow-up. - No sending (mail, SFTP), no DOCX, one locale (`fr`). diff --git a/document-studio/agents/main/workflows/document-studio-cancel.json b/document-studio/agents/main/workflows/document-studio-cancel.json index f7a1572..5458415 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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst reason = text(input.reason, \"reason\", 500, true);\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"status_invalid\", \"document déjà annulé\");\nrec.status = \"cancelled\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"cancelled\", note: reason});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\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", "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 dd39512..4ba066e 100644 --- a/document-studio/agents/main/workflows/document-studio-draft.json +++ b/document-studio/agents/main/workflows/document-studio-draft.json @@ -122,7 +122,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst prep = input.prep;\nconst key = prep.template_key;\nlet data = parseJsonValue(input.draft);\nif (!isObject(data)) fail(\"llm_output_invalid\", \"objet attendu\");\nif (Array.isArray(data.missing) && data.missing.length) fail(\"data_missing\", data.missing.filter((x) => typeof x === \"string\").join(\" ; \"));\nlet title = typeof input.title === \"string\" && input.title.trim() ? input.title.trim().slice(0, 120) : \"\";\nconst given = input.doc_id !== undefined && input.doc_id !== null && input.doc_id !== \"\";\nconst id = given ? docIdOf(input.doc_id) : slugify(title || (key === \"quote\" ? \"devis \" + (isObject(data.customer) ? data.customer.name : \"\") : (isObject(data.meeting) ? data.meeting.title : key))) + \"-\" + shortSuffix();\ndata = normalizeData(key, data, id);\nif (!title) title = key === \"quote\" ? \"Devis \" + data.customer.name : data.meeting.title;\ntitle = title.slice(0, 120);\nconst at = nowIso();\nconst rec = {schema: \"document-studio.record/v1\", doc_id: id, template_key: key, template_version: TEMPLATES[key].manifest.version, title, locale: prep.locale, status: \"draft\", number: null, revision: 1, data, history: [{at, action: \"created\", note: \"brouillon créé depuis un brief\"}], renders: [], issued: null};\ntry { await writeJson(recordPath(id), rec, false); } catch (e) { fail(\"document_create_failed\", id + \" : \" + String(e && e.message)); }\nreturn {...summarize(rec), data, computed: templateData(key, data)};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"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", "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 f48d585..0054757 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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst dest = input.destination_path;\nif (typeof dest !== \"string\" || !dest.startsWith(\"/\") || dest.length > 300 || dest.includes(\"..\") || dest.includes(\"//\") || /\\s$/.test(dest) || dest.endsWith(\"/\")) fail(\"destination_invalid\", \"chemin Storage absolu attendu\");\nif (dest === ROOT || dest.startsWith(ROOT + \"/\")) fail(\"destination_invalid\", \"la destination doit être hors de \" + ROOT);\nconst rec = await loadRecord(id);\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.\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", "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 2fba2fa..fef3c32 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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nif (rec.status !== \"draft\") fail(\"status_invalid\", \"seul un brouillon s'approuve (statut actuel : \" + rec.status + \")\");\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nif (!last || last.revision !== rec.revision) fail(\"render_required\", \"rendez la révision courante avant de l'approuver\");\nrec.status = \"approved\";\nrec.revision += 1;\nrec.history.push({at: nowIso(), action: \"approved\", note: \"rendu r\" + last.revision + \" approuvé\"});\nawait saveRecord(rec);\nreturn summarize(rec);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\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", "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 309bc64..318284b 100644 --- a/document-studio/agents/main/workflows/document-studio-list.json +++ b/document-studio/agents/main/workflows/document-studio-list.json @@ -42,7 +42,7 @@ "list_files" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nif (input.status !== undefined && input.status !== null && input.status !== \"\" && !STATUSES.includes(input.status)) fail(\"status_invalid\", String(input.status));\nconst paths = await listPaths(ROOT + \"/docs\");\nconst ids = [];\nfor (const p of paths) { const m = /document-studio\\/docs\\/([a-z0-9][a-z0-9-]{0,47})(?:\\/|$)/.exec(p); if (m && !ids.includes(m[1])) ids.push(m[1]); }\nif (ids.length > 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.\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", "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 a5fe585..3ed7e43 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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nconst body = normalizeProfile(input.profile);\nawait callTool(\"write_file\", {path: ROOT + \"/profile.json\", content: JSON.stringify(body, null, 2) + \"\\n\", overwrite: true});\nreturn {path: ROOT + \"/profile.json\", legal_name: body.company.legal_name, colors: body.brand.colors, message: \"Charte enregistrée dans Storage.\"};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\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", "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 5752ca5..2cf538e 100644 --- a/document-studio/agents/main/workflows/document-studio-publish.json +++ b/document-studio/agents/main/workflows/document-studio-publish.json @@ -71,10 +71,11 @@ "read_file", "write_file", "list_files", - "artifact_render_v1" + "artifact_render_v1", + "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}\nasync function loadProfile() {\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 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);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"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", "output_key": "result" } ], @@ -87,6 +88,7 @@ "revision": "{{ result.revision }}", "renders": "{{ result.renders }}", "last_render": "{{ result.last_render }}", - "issued": "{{ result.issued }}" + "issued": "{{ result.issued }}", + "profile_source": "{{ result.profile_source }}" } } diff --git a/document-studio/agents/main/workflows/document-studio-render.json b/document-studio/agents/main/workflows/document-studio-render.json index c260339..8db227c 100644 --- a/document-studio/agents/main/workflows/document-studio-render.json +++ b/document-studio/agents/main/workflows/document-studio-render.json @@ -50,10 +50,11 @@ "read_file", "write_file", "list_files", - "artifact_render_v1" + "artifact_render_v1", + "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}\nasync function loadProfile() {\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 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);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst TEMPLATES = JSON.parse(\"\\u007b\\\"meeting-minutes\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"files\\\": \\u007b\\\"examples/default.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\",\\\\n \\\\\\\"time\\\\\\\": \\\\\\\"14:00\\\\\\\",\\\\n \\\\\\\"place\\\\\\\": \\\\\\\"Salle Horizon / visio\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\", \\\\\\\"present\\\\\\\": true \\u007d,\\\\n \\u007b \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\", \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\", \\\\\\\"present\\\\\\\": false \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\" \\u007d,\\\\n \\u007b \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\", \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\", \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\" \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"examples/minimal.json\\\": \\\"\\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Point d'avancement du projet Exemple\\\\\\\",\\\\n \\\\\\\"date\\\\\\\": \\\\\\\"2026-11-05\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Cheffe de projet\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Développeur\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": true\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"Sam Leroy\\\\\\\",\\\\n \\\\\\\"role\\\\\\\": \\\\\\\"Client référent\\\\\\\",\\\\n \\\\\\\"present\\\\\\\": false\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"agenda\\\\\\\": [\\\\n \\\\\\\"Revue de l'avancement\\\\\\\",\\\\n \\\\\\\"Budget restant et risques\\\\\\\",\\\\n \\\\\\\"Planning de la prochaine itération\\\\\\\"\\\\n ],\\\\n \\\\\\\"decisions\\\\\\\": [\\\\n \\\\\\\"Le lot A est validé en l'état.\\\\\\\",\\\\n \\\\\\\"La recette est repoussée au 2026-11-20 (marge de sécurité).\\\\\\\"\\\\n ],\\\\n \\\\\\\"actions\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Envoyer le planning révisé\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Camille Martin\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-08\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Corriger les 3 anomalies de recette\\\\\\\",\\\\n \\\\\\\"owner\\\\\\\": \\\\\\\"Alex Durand\\\\\\\",\\\\n \\\\\\\"due_date\\\\\\\": \\\\\\\"2026-11-15\\\\\\\"\\\\n \\u007d\\\\n ]\\\\n\\u007d\\\\n\\\", \\\"input.schema.json\\\": \\\"\\u007b\\\\n \\\\\\\"$schema\\\\\\\": \\\\\\\"https://json-schema.org/draft/2020-12/schema\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Donnees metier du compte rendu de reunion\\\\\\\",\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"meeting\\\\\\\", \\\\\\\"participants\\\\\\\", \\\\\\\"agenda\\\\\\\", \\\\\\\"decisions\\\\\\\", \\\\\\\"actions\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"meeting\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"title\\\\\\\", \\\\\\\"date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"title\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d,\\\\n \\\\\\\"time\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"place\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"participants\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"minItems\\\\\\\": 1,\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"name\\\\\\\", \\\\\\\"role\\\\\\\", \\\\\\\"present\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"name\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"role\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d,\\\\n \\\\\\\"present\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"boolean\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d,\\\\n \\\\\\\"agenda\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"decisions\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\", \\\\\\\"items\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\" \\u007d \\u007d,\\\\n \\\\\\\"actions\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"array\\\\\\\",\\\\n \\\\\\\"items\\\\\\\": \\u007b\\\\n \\\\\\\"type\\\\\\\": \\\\\\\"object\\\\\\\",\\\\n \\\\\\\"required\\\\\\\": [\\\\\\\"description\\\\\\\", \\\\\\\"owner\\\\\\\", \\\\\\\"due_date\\\\\\\"],\\\\n \\\\\\\"properties\\\\\\\": \\u007b\\\\n \\\\\\\"description\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"owner\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"minLength\\\\\\\": 1 \\u007d,\\\\n \\\\\\\"due_date\\\\\\\": \\u007b \\\\\\\"type\\\\\\\": \\\\\\\"string\\\\\\\", \\\\\\\"format\\\\\\\": \\\\\\\"date\\\\\\\" \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n \\u007d\\\\n\\u007d\\\\n\\\", \\\"main.typ\\\": \\\"// Gabarit de reference `meeting-minutes` (compte rendu de reunion).\\\\n// Contrat : contracts/template/v1/.\\\\n#import \\\\\\\"/brand.typ\\\\\\\": brand, locale\\\\n#import \\\\\\\"/fragments/header.typ\\\\\\\": doc-header\\\\n#import \\\\\\\"/fragments/footer.typ\\\\\\\": doc-footer\\\\n#import \\\\\\\"/fragments/legal-mentions.typ\\\\\\\": legal-mentions\\\\n#import \\\\\\\"/fragments/lines-table.typ\\\\\\\": lines-table\\\\n\\\\n#set page(\\\\n paper: brand.page.paper,\\\\n margin: brand.page.margins,\\\\n footer: doc-footer([\\u007b\\u007b .company.legal_name \\u007d\\u007d - \\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d]),\\\\n)\\\\n#set text(font: (brand.fonts.body, \\\\\\\"Libertinus Serif\\\\\\\"), size: 10pt, fill: brand.colors.text, lang: locale)\\\\n\\\\n#doc-header([\\u007b\\u007b .company.trade_name \\u007d\\u007d], [\\u007b\\u007b .i18n.strings.minutes_title \\u007d\\u007d], [\\u007b\\u007b .doc.number \\u007d\\u007d], [\\u007b\\u007b .doc.date \\u007d\\u007d])\\\\n\\\\n*\\u007b\\u007b .i18n.strings.minutes_meeting \\u007d\\u007d* : \\u007b\\u007b .data.meeting.title \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_date \\u007d\\u007d* : \\u007b\\u007b .data.meeting.date \\u007d\\u007d \\u007b\\u007b .data.meeting.time | default \\\\\\\"\\\\\\\" \\u007d\\u007d \\\\\\\\\\\\n*\\u007b\\u007b .i18n.strings.minutes_place \\u007d\\u007d* : \\u007b\\u007b .data.meeting.place | default \\\\\\\"-\\\\\\\" \\u007d\\u007d\\\\n\\\\n#v(4mm)\\\\n== \\u007b\\u007b .i18n.strings.minutes_participants \\u007d\\u007d\\\\n\\u007b\\u007b range .data.participants \\u007d\\u007d\\\\n- *\\u007b\\u007b .name \\u007d\\u007d*, \\u007b\\u007b .role \\u007d\\u007d\\u007b\\u007b if not .present \\u007d\\u007d (\\u007b\\u007b $.i18n.strings.minutes_absent \\u007d\\u007d)\\u007b\\u007b end \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_agenda \\u007d\\u007d\\\\n\\u007b\\u007b range .data.agenda \\u007d\\u007d\\\\n+ \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_decisions \\u007d\\u007d\\\\n\\u007b\\u007b range .data.decisions \\u007d\\u007d\\\\n- \\u007b\\u007b . \\u007d\\u007d\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n\\\\n== \\u007b\\u007b .i18n.strings.minutes_actions \\u007d\\u007d\\\\n#lines-table(\\\\n (\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_action \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_owner \\u007d\\u007d],\\\\n [\\u007b\\u007b .i18n.strings.minutes_col_due \\u007d\\u007d],\\\\n ),\\\\n (\\\\n\\u007b\\u007b- range .data.actions \\u007d\\u007d\\\\n ([\\u007b\\u007b .description \\u007d\\u007d], [\\u007b\\u007b .owner \\u007d\\u007d], [\\u007b\\u007b .due_date \\u007d\\u007d]),\\\\n\\u007b\\u007b- end \\u007d\\u007d\\\\n ),\\\\n right-from: 3,\\\\n)\\\\n\\\\n#legal-mentions([\\u007b\\u007b .i18n.strings.common_legal_notice \\u007d\\u007d], [\\u007b\\u007b .company.legal_mentions \\u007d\\u007d])\\\\n\\\", \\\"manifest.json\\\": \\\"\\u007b\\\\n \\\\\\\"schema\\\\\\\": \\\\\\\"agentmaurice.template/v1\\\\\\\",\\\\n \\\\\\\"key\\\\\\\": \\\\\\\"meeting-minutes\\\\\\\",\\\\n \\\\\\\"version\\\\\\\": \\\\\\\"1.0.0\\\\\\\",\\\\n \\\\\\\"title\\\\\\\": \\\\\\\"Compte rendu de réunion\\\\\\\",\\\\n \\\\\\\"description\\\\\\\": \\\\\\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\\\\\",\\\\n \\\\\\\"kind\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"profile\\\\\\\": \\\\\\\"document\\\\\\\",\\\\n \\\\\\\"source\\\\\\\": \\u007b\\\\n \\\\\\\"engine\\\\\\\": \\\\\\\"typst\\\\\\\",\\\\n \\\\\\\"entry\\\\\\\": \\\\\\\"main.typ\\\\\\\"\\\\n \\u007d,\\\\n \\\\\\\"outputs\\\\\\\": [\\\\n \\\\\\\"pdf\\\\\\\"\\\\n ],\\\\n \\\\\\\"locales\\\\\\\": [\\\\n \\\\\\\"fr\\\\\\\"\\\\n ],\\\\n \\\\\\\"default_locale\\\\\\\": \\\\\\\"fr\\\\\\\",\\\\n \\\\\\\"input_schema\\\\\\\": \\\\\\\"input.schema.json\\\\\\\",\\\\n \\\\\\\"examples\\\\\\\": [\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"default\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/default.json\\\\\\\"\\\\n \\u007d,\\\\n \\u007b\\\\n \\\\\\\"name\\\\\\\": \\\\\\\"minimal\\\\\\\",\\\\n \\\\\\\"data\\\\\\\": \\\\\\\"examples/minimal.json\\\\\\\"\\\\n \\u007d\\\\n ],\\\\n \\\\\\\"fragments\\\\\\\": [\\\\n \\\\\\\"fragments/header.typ\\\\\\\",\\\\n \\\\\\\"fragments/footer.typ\\\\\\\",\\\\n \\\\\\\"fragments/legal-mentions.typ\\\\\\\",\\\\n \\\\\\\"fragments/lines-table.typ\\\\\\\"\\\\n ],\\\\n \\\\\\\"limits\\\\\\\": \\u007b\\\\n \\\\\\\"max_source_bytes\\\\\\\": 20000,\\\\n \\\\\\\"max_pages\\\\\\\": 3\\\\n \\u007d\\\\n\\u007d\\\\n\\\"\\u007d, \\\"input_schema\\\": \\u007b\\\"$schema\\\": \\\"https://json-schema.org/draft/2020-12/schema\\\", \\\"properties\\\": \\u007b\\\"actions\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"due_date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"owner\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"description\\\", \\\"owner\\\", \\\"due_date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"agenda\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"decisions\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"meeting\\\": \\u007b\\\"properties\\\": \\u007b\\\"date\\\": \\u007b\\\"format\\\": \\\"date\\\", \\\"type\\\": \\\"string\\\"\\u007d, \\\"place\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"time\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"title\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"title\\\", \\\"date\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"participants\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"present\\\": \\u007b\\\"type\\\": \\\"boolean\\\"\\u007d, \\\"role\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\", \\\"role\\\", \\\"present\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"minItems\\\": 1, \\\"type\\\": \\\"array\\\"\\u007d\\u007d, \\\"required\\\": [\\\"meeting\\\", \\\"participants\\\", \\\"agenda\\\", \\\"decisions\\\", \\\"actions\\\"], \\\"title\\\": \\\"Donnees metier du compte rendu de reunion\\\", \\\"type\\\": \\\"object\\\"\\u007d, \\\"manifest\\\": \\u007b\\\"default_locale\\\": \\\"fr\\\", \\\"description\\\": \\\"Compte rendu avec participants, ordre du jour, décisions et actions (responsable, échéance).\\\", \\\"examples\\\": [\\u007b\\\"data\\\": \\\"examples/default.json\\\", \\\"name\\\": \\\"default\\\"\\u007d, \\u007b\\\"data\\\": \\\"examples/minimal.json\\\", \\\"name\\\": \\\"minimal\\\"\\u007d], \\\"fragments\\\": [\\\"fragments/header.typ\\\", \\\"fragments/footer.typ\\\", \\\"fragments/legal-mentions.typ\\\", \\\"fragments/lines-table.typ\\\"], \\\"input_schema\\\": \\\"input.schema.json\\\", \\\"key\\\": \\\"meeting-minutes\\\", \\\"kind\\\": \\\"document\\\", \\\"limits\\\": \\u007b\\\"max_pages\\\": 3, \\\"max_source_bytes\\\": 20000\\u007d, \\\"locales\\\": [\\\"fr\\\"], \\\"outputs\\\": [\\\"pdf\\\"], \\\"profile\\\": \\\"document\\\", \\\"schema\\\": \\\"agentmaurice.template/v1\\\", \\\"source\\\": \\u007b\\\"engine\\\": \\\"typst\\\", \\\"entry\\\": \\\"main.typ\\\"\\u007d, \\\"title\\\": \\\"Compte rendu de réunion\\\", \\\"version\\\": \\\"1.0.0\\\"\\u007d, \\\"prefix\\\": \\\"CR\\\", \\\"summary\\\": \\\"Compte rendu de réunion : réunion, participants, ordre du jour, décisions, actions (responsable, échéance).\\\", \\\"title\\\": \\\"Compte rendu de réunion\\\"\\u007d, \\\"quote\\\": \\u007b\\\"draft_schema\\\": \\u007b\\\"properties\\\": \\u007b\\\"customer\\\": \\u007b\\\"properties\\\": \\u007b\\\"address_lines\\\": \\u007b\\\"items\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"type\\\": \\\"array\\\"\\u007d, \\\"contact\\\": \\u007b\\\"type\\\": \\\"string\\\"\\u007d, \\\"name\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d\\u007d, \\\"required\\\": [\\\"name\\\"], \\\"type\\\": \\\"object\\\"\\u007d, \\\"lines\\\": \\u007b\\\"items\\\": \\u007b\\\"properties\\\": \\u007b\\\"description\\\": \\u007b\\\"minLength\\\": 1, \\\"type\\\": \\\"string\\\"\\u007d, \\\"quantity\\\": \\u007b\\\"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", "output_key": "result" } ], @@ -66,6 +67,7 @@ "revision": "{{ result.revision }}", "renders": "{{ result.renders }}", "last_render": "{{ result.last_render }}", - "issued": "{{ result.issued }}" + "issued": "{{ result.issued }}", + "profile_source": "{{ result.profile_source }}" } } 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 3455527..29b0cc4 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}\nasync function loadProfile() {\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 par document-studio-profile-save\");\n return projectProfile(normalizeProfile(stored));\n}\n\nconst input = {{ json . }};\nconst id = docIdOf(input.doc_id);\nconst rec = await loadRecord(id);\nconst last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\nconst s = summarize(rec);\nreturn {doc_id: id, title: rec.title, template_key: rec.template_key, status: rec.status, number: rec.number === null ? \"\" : rec.number, revision: rec.revision, pages: last ? last.previews.length : 0, previews: last ? last.previews : [], renders: rec.renders.map((r) => ({revision: r.revision, mode: r.mode, sha256: r.file.sha256, path: r.file.path})), history: rec.history, issued: rec.issued, record: rec};\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\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", "output_key": "result" } ], diff --git a/inventory/modules.json b/inventory/modules.json index edc515b..a18ba87 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1239,16 +1239,16 @@ "document-studio/module.yaml": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", "document-studio/agents/main/workflows/document-read.json": "4c1e20b58a546f415f480145882523ae607fabfbf784eac5de02d1ad3515a2ef", "document-studio/agents/main/workflows/document-share.json": "a37a4d7bbe729c74b769f26c85a3c4766d691ca76821cdc846abe816b15ebdb2", - "document-studio/agents/main/workflows/document-studio-cancel.json": "899e24cb5688d92497891ea09a3181f64093df9d2802d818da78f1298f807965", - "document-studio/agents/main/workflows/document-studio-draft.json": "72be0b86b67c6fc4392bff1795c38c59763334582fedf1ccdd95b296e9492b4e", - "document-studio/agents/main/workflows/document-studio-export.json": "52aa5bcc2ee64715be59fab234804fcebd3cc1cfec4e32dd5f9ea5d69c9371db", - "document-studio/agents/main/workflows/document-studio-finalize.json": "07f6f1bce4cb549c1973b06b3523abefc77c253967711415d51bd499360ed020", - "document-studio/agents/main/workflows/document-studio-list.json": "38daf2284f500b2e71d0bbd73dbfbd8d3c3ca1259f600384a6ce95c565ba5a33", + "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-plan.json": "47a1a75463b75cdfc287a56f80a23f3faef513ae46b6b980a0851579089eb99b", - "document-studio/agents/main/workflows/document-studio-profile-save.json": "686d4ccf1265c6b3990a0fdec57b7ddc3e3252bcc66025f25d640f12c7f9454e", - "document-studio/agents/main/workflows/document-studio-publish.json": "350a0c4318d39c76b907891181c8abb66c6d21ce372f03548c013e7e3653a8b1", - "document-studio/agents/main/workflows/document-studio-render.json": "ac51133ecc9eb27b71e68c7316acde0dc75d8c88e3c68d676f87d12943a5d4c4", - "document-studio/agents/main/workflows/document-studio-review-read.json": "a7c0b4a35ac7e2f68193a71d2aa40711366abac924b079d85d76ca7bcbbfa6ac", + "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/agents/main/miniapps/document-studio-review.json": "126750a2bcf33970f52a3e946381661136ec5cae9a918546cca289a268c1088c" } @@ -1289,7 +1289,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "f1917d69e3f6037738be1d01b1596f493e100e8531724aa9c3f812277e34441c" + "code_sha256": "69ce0757ceafdd4371bb9fd30155b0a1b9d217b86b28b0c3017e40f50341a261" } ] }, @@ -1315,7 +1315,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "84cd3cdb86438410be7feb0f37a661dbbee58c1009a1de60fad4aa46cea6253e" + "code_sha256": "8b7eeb51061f9da9222cf5b187679b58ee8f8c89640ef0f04985b6a141f8f513" } ] }, @@ -1328,7 +1328,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "7afe7e008045c2dbd7a94dd38795eef6b03f53e9fe22b24714523dbacf542792" + "code_sha256": "165025885224b0ee3c3c74ee87ece42d292eb524d694ac46156db2661e2f2885" } ] }, @@ -1341,7 +1341,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "0b7fb78a4eaf763a38684b03c62e39340c51c5244295f1eb00c43d5f934e9117" + "code_sha256": "24cfa7e9ccac2ea0cd7437d08268cfc71776a65cbfd30372d48dce2d44237695" } ] }, @@ -1354,7 +1354,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "9ea76c328efb36d97b4cda1c4cff6f290a56ec5950564155f3b549fdb955a2c4" + "code_sha256": "2d14a0e71bb6ad4807f9361fd379d4531025e37a027a3794463417739a2675da" } ] }, @@ -1393,7 +1393,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "d7534ddd9f68d4a12d292c697b8696f6b40d21d4140d89f8a010c589ae9f90c8" + "code_sha256": "6ce377baeb157712a931eed1841ed49abd80e35ec555f499e6218ef56852cf42" } ] }, @@ -1406,7 +1406,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "7acdf05706263ae55bb475399eeccd796b6965f15b32c3c54239d24741467edd" + "code_sha256": "28ff2644edbfd9ae06fe59b342b28f594bd93c8ede7bf0121fee143c2dba2dd1" } ] }, @@ -1419,7 +1419,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "00664e1d1bc38d410cfe9da07f7a4149ad8b8d22db1b92d744c017bc9521f6b7" + "code_sha256": "24847650286455761816d9e591374331e7bc1b07f947bb46da2a40ed29e94107" } ] }, @@ -1432,7 +1432,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "c9790097344a4efb7d26f1908662ed92d374fbffa30d1b877864adb75f717175" + "code_sha256": "df64ef6b951bff53cf9d112beed8fa48a90505609d30769d0ed9438beea8c4be" } ] }, diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index 0b92931..3de6b14 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -377,17 +377,6 @@ def load_templates(with_files): await writeJson(recordPath(rec.doc_id), rec, true); remember(rec); } -async function loadProfile() { - let stored = null; - try { stored = await readJson(ROOT + "/profile.json"); } catch (e) { - const m = String(e && e.message); - if (m.startsWith("json_corrupt")) fail("profile_corrupt", "profile.json illisible"); - if (!m.startsWith("storage_not_found")) throw e; - stored = null; - } - if (!isObject(stored)) fail("profile_missing", "enregistrez la charte par document-studio-profile-save"); - return projectProfile(normalizeProfile(stored)); -} ''' PROFILE = r''' @@ -467,6 +456,39 @@ def load_templates(with_files): } ''' +PROFILE_LOAD = r''' +// The company profile comes from the cib-profile record (native broker, same read call as cib-profile-read). When that record is +// absent, refused to this caller or unreadable, the Storage copy written by document-studio-profile-save is used, as before. +let PROFILE_SOURCE = "storage"; +async function brokerProfileBody() { + let response; + try { response = await callTool("recipe--application_data_v1", {operation: "read", namespace: "cib-profile", record_key: "company-profile"}); } catch (e) { return null; } + if (isObject(response) && isObject(response.error)) return null; + const payload = response && response.data ? response.data : response; + const item = payload && payload.record; + if (!isObject(item) || item.namespace !== "cib-profile" || item.key !== "company-profile" || !isObject(item.data)) return null; + const p = item.permissions; + if (!isObject(p) || p.can_read !== true) return null; + return item.data; +} +async function loadProfile() { + const body = await brokerProfileBody(); + if (body !== null) { + try { const projected = projectProfile(normalizeProfile(body)); PROFILE_SOURCE = "cib-profile"; return projected; } catch (e) { /* unreadable record: fall back to Storage */ } + } + PROFILE_SOURCE = "storage"; + let stored = null; + try { stored = await readJson(ROOT + "/profile.json"); } catch (e) { + const m = String(e && e.message); + if (m.startsWith("json_corrupt")) fail("profile_corrupt", "profile.json illisible"); + if (!m.startsWith("storage_not_found")) throw e; + stored = null; + } + if (!isObject(stored)) fail("profile_missing", "enregistrez la charte dans cib-profile ou par document-studio-profile-save"); + return projectProfile(normalizeProfile(stored)); +} +''' + RENDER = r''' // A folder per attempt: a render that loses a race never overwrites the file of another attempt. function attemptTag(f) { const sha = typeof f.sha256 === "string" ? f.sha256.toLowerCase().replace(/[^0-9a-f]/g, "").slice(0, 12) : ""; return sha || shortSuffix(); } @@ -651,7 +673,7 @@ def node(action_id, source, output_key, tools=None): return data -def lib(*, templates=None, io=False, profile=False, render=False, numbering=False): +def lib(*, templates=None, io=False, profile=False, render=False, numbering=False, load_profile=False): parts = [IMPORT if io else ''] if templates is not None: parts.append('const TEMPLATES = ' + js_embed(load_templates(templates == 'full')) + ';\nObject.setPrototypeOf(TEMPLATES, null);\n') @@ -662,6 +684,8 @@ def lib(*, templates=None, io=False, profile=False, render=False, numbering=Fals parts.append(PROFILE) if io: parts.append(IO) + if load_profile: + parts.append(PROFILE_LOAD) if render: parts.append(RENDER) if numbering: @@ -801,7 +825,7 @@ def llm(action_id, prompt_ref, system, output_key, tokens): rec.revision = revision; rec.renders.push({revision, mode: "preview", profile_sha256: await fingerprint(profile), data_sha256: await fingerprint(data), file, previews, provenance: res.provenance === undefined ? null : res.provenance}); await saveRecord(rec); -return summarize(rec); +return {...summarize(rec), profile_source: PROFILE_SOURCE}; ''' FINALIZE_CODE = r''' @@ -868,7 +892,7 @@ def llm(action_id, prompt_ref, system, output_key, tokens): rec.issued = {number: rec.number, file: {path: file.path, sha256: file.sha256}, at}; rec.history.push({at, action: "issued", note: rec.number}); await saveRecord(rec); -return summarize(rec); +return {...summarize(rec), profile_source: PROFILE_SOURCE}; ''' CANCEL_CODE = r''' @@ -988,8 +1012,8 @@ def build(): 'Renders the current data with the company profile through the artifact tool (mode preview), stores the PDF ' 'and its page previews in Storage and appends a revision. An issued or cancelled document is locked.', schema(['doc_id'], doc_id=DOC_ID, data_patch={'type': 'object', 'description': 'Shallow merge into the draft data, then revalidated'}), - [node('render', code(lib(templates='full', io=True, profile=True, render=True), RENDER_CODE), 'result', tools=RENDER_TOOLS)], - out_summary, + [node('render', code(lib(templates='full', io=True, profile=True, render=True, load_profile=True), RENDER_CODE), 'result', tools=RENDER_TOOLS + [BROKER])], + {**out_summary, 'profile_source': '{{ result.profile_source }}'}, forms=[form('render', 'Nouveau rendu', [field('doc_id', 'Identifiant du document', 'string', True)], ['render'])]) workflow('document-studio-finalize', 'Approve a document', @@ -1003,8 +1027,8 @@ def build(): 'Reserves the next number of the template for the year, renders the final PDF (mode final) and stores it as the ' 'issued file. Requires an approved document and a manual confirmation. The reservation is not atomic.', schema(['doc_id', 'confirmation_manuelle'], doc_id=DOC_ID, confirmation_manuelle=CONFIRM), - [node('publish', code(lib(templates='full', io=True, profile=True, render=True, numbering=True), PUBLISH_CODE), 'result', tools=RENDER_TOOLS)], - out_summary, + [node('publish', code(lib(templates='full', io=True, profile=True, render=True, numbering=True, load_profile=True), PUBLISH_CODE), 'result', tools=RENDER_TOOLS + [BROKER])], + {**out_summary, 'profile_source': '{{ result.profile_source }}'}, forms=[form('issue', 'Émettre un document', [field('doc_id', 'Identifiant du document', 'string', True), CONFIRM_FIELD], ['publish'])]) workflow('document-studio-cancel', 'Cancel a document', diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index 52b68f5..d83ef15 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -68,6 +68,14 @@ def load(path): const brokerRecords = store.__broker || (store.__broker = {}); const perms = (r) => ({can_read: true, can_write: true, can_manage: true}); const view = (k, r) => ({namespace: args.namespace, key: k, revision: r.revision, owner_user_id: "owner-1", permissions: perms(r), shares: r.shares, data: r.data}); + if (args.namespace === "cib-profile") { + calls[calls.length - 1].profile_read = true; + if (args.operation !== "read" || args.record_key !== "company-profile") throw new Error("unexpected profile call"); + if (opts.cib_profile_error) throw Object.assign(new Error(opts.cib_profile_error), {code: opts.cib_profile_error}); + if (opts.cib_profile_error_value) return {error: {code: opts.cib_profile_error_value}}; + if (opts.cib_profile === undefined) throw Object.assign(new Error("application data record not found"), {code: "NOT_FOUND"}); + return {data: {record: {namespace: "cib-profile", key: "company-profile", revision: 3, owner_user_id: "owner-1", permissions: {can_read: opts.cib_profile_unreadable ? false : true, can_write: false, can_manage: false}, shares: [], data: opts.cib_profile}}}; + } if (args.namespace !== "cib-documents") throw new Error("namespace_forbidden"); if (opts.broker_error) throw new Error(opts.broker_error); const cur = brokerRecords[args.record_key]; @@ -990,5 +998,61 @@ def test_read_returns_the_reference_with_permissions_and_lists(self): self.assertIn('error', run_node('document-read', 'read', {'doc_id': 'devis-test'}, fs, broker_error='access_denied')) +class ProfileSourceTest(unittest.TestCase): + BROKER_PROFILE = json.loads(json.dumps(PROFILE)) | {} + + def prepared(self): + _, fs = create_quote(self, seeded()) + return fs + + def render(self, fs, **opts): + return run_node('document-studio-render', 'render', {'doc_id': 'devis-test'}, fs, **opts) + + def profile_call(self, out): + return [c for c in out['calls'] if c.get('profile_read')] + + def test_the_cib_profile_record_is_read_with_the_exact_broker_call(self): + brand_from_broker = json.loads(json.dumps(PROFILE)) + brand_from_broker['company']['legal_name'] = 'Societe du record' + out = self.render(self.prepared() | {'/document-studio/profile.json': text_file('{oops')}, cib_profile=brand_from_broker) + result = ok(self, out) + self.assertEqual(result['profile_source'], 'cib-profile') + self.assertEqual(self.profile_call(out)[0]['args'], {'operation': 'read', 'namespace': 'cib-profile', 'record_key': 'company-profile'}) + render_call = [c for c in out['calls'] if c['name'] == 'artifact_render_v1'][0]['full'] + self.assertEqual(render_call['context']['company']['legal_name'], 'Societe du record') + self.assertNotIn('profile.json', json.dumps([c['args'] for c in out['calls'] if c['name'] == 'read_file'])) + + def test_an_absent_record_falls_back_to_storage(self): + result = ok(self, self.render(self.prepared())) + self.assertEqual(result['profile_source'], 'storage') + + def test_a_refused_unreadable_or_invalid_record_falls_back_to_storage(self): + for opts in ({'cib_profile_error': 'PERMISSION_DENIED'}, {'cib_profile_error_value': 'FORBIDDEN'}, + {'cib_profile': PROFILE, 'cib_profile_unreadable': True}, {'cib_profile': {'schema_version': 1}}): + out = self.render(self.prepared(), **opts) + self.assertEqual(ok(self, out)['profile_source'], 'storage', opts) + self.assertEqual(len(self.profile_call(out)), 1) + + def test_without_any_profile_the_render_still_fails(self): + fs = {k: v for k, v in self.prepared().items() if 'devis-test' in k} + self.assertTrue(self.render(fs)['error'].startswith('profile_missing')) + + def test_publish_keeps_the_fingerprint_check_across_sources(self): + fs = self.prepared() + rendered = self.render(fs, cib_profile=PROFILE) + self.assertEqual(ok(self, rendered)['profile_source'], 'cib-profile') + approved = run_node('document-studio-finalize', 'finalize', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, rendered['fs']) + same = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, approved['fs'], cib_profile=PROFILE) + self.assertEqual(ok(self, same)['profile_source'], 'cib-profile') + # same content through the Storage fallback: same fingerprint, the issue goes through + via_storage = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, approved['fs']) + self.assertEqual(ok(self, via_storage)['profile_source'], 'storage') + changed = json.loads(json.dumps(PROFILE)) + changed['brand']['colors']['primary'] = '#112233' + refused = run_node('document-studio-publish', 'publish', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui'}, approved['fs'], cib_profile=changed) + self.assertTrue(refused['error'].startswith('profile_changed'), refused.get('error')) + self.assertEqual(load(WORKFLOWS / 'document-studio-publish.json')['actions'][0]['context']['allowed_tools'][-1], 'recipe--application_data_v1') + + if __name__ == '__main__': unittest.main() From c20126c578e9d4090946261aeb86e966f35fe757 Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Mon, 9 Nov 2026 06:29:36 +0100 Subject: [PATCH 3/5] AGENT-1831: document-read without required_role, truthful share message, empty doc_id allowed - compose.py surface draft: document-read carries no required_role (record ACL protects it, like contenu-read). - document-share republished without a member reports the real shares returned by the broker. - document-read input schema accepts an empty doc_id (list); README updated. Co-Authored-By: Claude Opus 5.5 --- catalog.json | 2 +- document-studio/README.md | 4 ++-- .../agents/main/workflows/document-read.json | 4 ++-- .../agents/main/workflows/document-share.json | 2 +- inventory/modules.json | 6 +++--- templates/company-in-a-box/compose.py | 20 +++++++++++-------- .../company-in-a-box/tests/test_compose.py | 6 ++++-- tooling/document-studio/build.py | 4 ++-- tooling/document-studio/tests/test_module.py | 15 ++++++++++++++ 9 files changed, 42 insertions(+), 21 deletions(-) diff --git a/catalog.json b/catalog.json index 1c7ce95..2eae75b 100644 --- a/catalog.json +++ b/catalog.json @@ -647,7 +647,7 @@ "subpath": "document-studio", "manifest": "document-studio/module.yaml", "manifest_sha256": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "tree_sha256": "98de52e864ad811f7a16ffc694e46f07dcdc46579f06029344d6a599de78ad9c", + "tree_sha256": "e21fb5684d2de6fd01717a342dc35fbcb8776094431372ae7d0372bc26cb3ebc", "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 423c02b..23313a6 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -27,7 +27,7 @@ messages) is French; `fr` is the only locale in V0. | `document-studio-review-read` | full record of a document and previews of its latest render, for the MiniApp | | `document-studio-template-read` | lists the templates, or the manifest and data schemas of one template | | `document-share` | publishes the reference of an **issued** document as a record of the native application data broker (`recipe--application_data_v1`, namespace `cib-documents`, key `doc_id`), then grants or removes `read` for one member. Requires `confirmation_manuelle`. The PDF stays in Storage | -| `document-read` | reads one shared reference through the broker (with the caller's permissions), or lists the references the caller may read when `doc_id` is empty | +| `document-read` | reads one shared reference through the broker (with the caller's permissions), or lists the references the caller may read when `doc_id` is empty or absent (`"doc_id": ""` is valid, so the form can be submitted blank) | The `document-studio-review` MiniApp has no input component of its own (the MiniApp vocabulary has none): the document identifier (`doc_id`) is typed in @@ -54,7 +54,7 @@ Storage right, separate from the ACL of the reference. (`documents`, spec-init'ed in the consumer like the three roles; off by default). Besides the resources and the test plan it writes `surface-drafts/cib-documents.surface-draft.json`, with `required_role` on every Workflow: `cib_documents` for the owner of the service, `cib_admin` for `document-studio-profile-save`. Role grants and the ACL of each record are -cumulative; the Module never grants a role or a share. The Administration select of `cib-admin-manage` does not list +cumulative; the Module never grants a role or a share. `document-read` has no `required_role` in the surface draft, like `contenu-read`: any member of the Application may call it and the ACL of each record decides what is returned. `document-share` republished without a member reports the real shares returned by the broker. The Administration select of `cib-admin-manage` does not list `cib_documents` yet. ## Lifecycle diff --git a/document-studio/agents/main/workflows/document-read.json b/document-studio/agents/main/workflows/document-read.json index 63ab21d..0837fd9 100644 --- a/document-studio/agents/main/workflows/document-read.json +++ b/document-studio/agents/main/workflows/document-read.json @@ -13,8 +13,8 @@ "properties": { "doc_id": { "type": "string", - "description": "Document identifier: lowercase letters, digits and hyphens", - "pattern": "^[a-z0-9][a-z0-9-]{0,47}$" + "description": "Document identifier; empty (or absent) lists the references the caller may read", + "pattern": "^([a-z0-9][a-z0-9-]{0,47})?$" } } }, diff --git a/document-studio/agents/main/workflows/document-share.json b/document-studio/agents/main/workflows/document-share.json index 99142f7..2b7a8bb 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.\" : \"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.\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", "output_key": "result" } ], diff --git a/inventory/modules.json b/inventory/modules.json index a18ba87..a68b55f 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1237,8 +1237,8 @@ ], "sha256": { "document-studio/module.yaml": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "document-studio/agents/main/workflows/document-read.json": "4c1e20b58a546f415f480145882523ae607fabfbf784eac5de02d1ad3515a2ef", - "document-studio/agents/main/workflows/document-share.json": "a37a4d7bbe729c74b769f26c85a3c4766d691ca76821cdc846abe816b15ebdb2", + "document-studio/agents/main/workflows/document-read.json": "d71940349fd9f9013989a0de9c78b07c93d6cb3b758f579c2f6f33bf24c79048", + "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", @@ -1276,7 +1276,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "1b5d8e9c893c9bc45e81c5107585cb3d8f42fdc75b50ccaf963e5cf1481564d9" + "code_sha256": "659157ddb8688061a808d19c50ef5dfc096d7cf89d0a08518f313f5dfdd2a79c" } ] }, diff --git a/templates/company-in-a-box/compose.py b/templates/company-in-a-box/compose.py index 7a78e0f..435b869 100755 --- a/templates/company-in-a-box/compose.py +++ b/templates/company-in-a-box/compose.py @@ -28,7 +28,9 @@ "module_dir": "document-studio", "version": "0.2.0", "role": "cib_documents", - "gates": {"document-studio-profile-save": "cib_admin"}, + # 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. + "gates": {"document-studio-profile-save": "cib_admin", "document-read": None}, }, } SURFACE_DRAFT_DIR = "surface-drafts" @@ -151,16 +153,18 @@ def validate_agent_spec(path: Path, role: str, errors: list[str]) -> None: def surface_draft(source_root: Path, service: str, agent_spec: Path) -> str: - """Surface entries of an optional service, with `required_role` on every Workflow (never left to a naming convention).""" + """Surface entries of an optional service, with `required_role` on every Workflow but the ACL-protected read (never left to a naming convention).""" config = OPTIONAL_SERVICES[service] manifest = load_json(source_root / config["module_dir"] / "module.yaml") agent_id = load_json(agent_spec)["agent_id"] provides = manifest["provides"] - workflows = [ - {"agent_id": agent_id, "workflow_id": ref["workflow_id"], "version": ref["workflow_version"], - "required_role": config["gates"].get(ref["workflow_id"], config["role"])} - for ref in provides["actions"] + provides["queries"] - ] + workflows = [] + for ref in provides["actions"] + provides["queries"]: + entry = {"agent_id": agent_id, "workflow_id": ref["workflow_id"], "version": ref["workflow_version"]} + role = config["gates"].get(ref["workflow_id"], config["role"]) + if role is not None: + entry["required_role"] = role + workflows.append(entry) miniapps = [{"agent_id": agent_id, "miniapp_id": a["miniapp_id"], "version": a["miniapp_version"]} for a in provides["apps"]] return json.dumps({"public_surface": {"workflows": workflows, "miniapps": miniapps}}, indent=2) + "\n" @@ -273,7 +277,7 @@ def main() -> int: return 3 for draft_path, draft in drafts: - print(f"surface draft -> {draft_path} (required_role on every Workflow; merge it into the Application surface and publish it yourself)") + print(f"surface draft -> {draft_path} (required_role on every Workflow except document-read, protected by the record ACL; merge it into the Application surface and publish it yourself)") if args.write: draft_path.parent.mkdir(parents=True, exist_ok=True) draft_path.write_text(draft, encoding="utf-8") diff --git a/templates/company-in-a-box/tests/test_compose.py b/templates/company-in-a-box/tests/test_compose.py index 86b04b7..d9e0122 100644 --- a/templates/company-in-a-box/tests/test_compose.py +++ b/templates/company-in-a-box/tests/test_compose.py @@ -156,10 +156,12 @@ def test_documents_service_copies_the_module_and_gates_every_workflow_by_role(se self.assertTrue((consumer / "agents/documents/workflows" / f"{name}.json").is_file(), name) self.assertTrue((consumer / "agents/documents/tests/test-plan.json").is_file()) draft = json.loads((consumer / "surface-drafts/cib-documents.surface-draft.json").read_text(encoding="utf-8")) - roles = {w["workflow_id"]: w["required_role"] for w in draft["public_surface"]["workflows"]} + roles = {w["workflow_id"]: w.get("required_role") for w in draft["public_surface"]["workflows"]} self.assertEqual(len(roles), 13) self.assertEqual(roles["document-studio-profile-save"], "cib_admin") - self.assertEqual({r for k, r in roles.items() if k != "document-studio-profile-save"}, {"cib_documents"}) + self.assertIsNone(roles["document-read"], "ACL of the record protects the read, as for contenu-read") + self.assertNotIn("required_role", next(w for w in draft["public_surface"]["workflows"] if w["workflow_id"] == "document-read")) + self.assertEqual({r for k, r in roles.items() if k not in ("document-studio-profile-save", "document-read")}, {"cib_documents"}) self.assertEqual({w["agent_id"] for w in draft["public_surface"]["workflows"]}, {"agent-documents"}) self.assertEqual([a["miniapp_id"] for a in draft["public_surface"]["miniapps"]], ["document-studio-review"]) self.assertEqual(self.run_main(source, consumer, "--with-service", "documents", "--write"), 0, "rerun is idempotent") diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index 3de6b14..c1f5183 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -635,7 +635,7 @@ def load_templates(with_files): 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); } const view = brokerView(item); -return {...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." : "Référence du document publiée, visible de son propriétaire seul tant qu'aucun membre n'est ajouté.", external_effect: false}; +return {...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}; """ READ_CODE = r""" @@ -1101,7 +1101,7 @@ def build(): workflow('document-read', 'Read shared documents', 'Reads, through the native application data broker, the reference of one shared document (with the permissions of the ' 'caller), or lists the references the caller may read when doc_id is empty. Only the rights of the caller apply.', - schema([], doc_id=DOC_ID), + schema([], doc_id=text('Document identifier; empty (or absent) lists the references the caller may read', pattern='^([a-z0-9][a-z0-9-]{0,47})?$')), [node('read', code(IMPORT, lib(), BROKER_LIB, READ_CODE), 'result', tools=[BROKER])], {'record': '{{ result.record }}', 'revision': '{{ result.revision }}', 'owner_user_id': '{{ result.owner_user_id }}', 'permissions': '{{ result.permissions }}', 'permissions_summary': '{{ result.permissions_summary }}', diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index d83ef15..0b89aeb 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -997,6 +997,21 @@ def test_read_returns_the_reference_with_permissions_and_lists(self): self.assertIn('error', run_node('document-read', 'read', {'doc_id': 'absent'}, fs)) self.assertIn('error', run_node('document-read', 'read', {'doc_id': 'devis-test'}, fs, broker_error='access_denied')) + def test_republishing_reports_the_real_shares_and_read_accepts_an_empty_id(self): + fs = self.share(self.issued(), share_subject_user_id='member-b')['fs'] + again = ok(self, self.share(fs, expected_revision=2)) + self.assertEqual(again['share_count'], 1) + self.assertNotIn('seul', again['message']) + self.assertIn('1 membre', again['message']) + private = ok(self, self.share(self.issued())) + self.assertIn('propriétaire seul', private['message']) + schema = load(WORKFLOWS / 'document-read.json')['input_schema'] + self.assertTrue(re.fullmatch(schema['properties']['doc_id']['pattern'], '')) + self.assertTrue(re.fullmatch(schema['properties']['doc_id']['pattern'], 'devis-test')) + self.assertIsNone(re.fullmatch(schema['properties']['doc_id']['pattern'], '../x')) + self.assertEqual(schema['required'], []) + self.assertEqual(ok(self, run_node('document-read', 'read', {'doc_id': ''}, fs))['total'], 1) + class ProfileSourceTest(unittest.TestCase): BROKER_PROFILE = json.loads(json.dumps(PROFILE)) | {} From 367ee73d06cb083aafb9bfc30ae93a42658082b9 Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Mon, 9 Nov 2026 06:34:16 +0100 Subject: [PATCH 4/5] AGENT-1831: document-read include_pdf through the record ACL, drop the non-discriminating plan case - document-read with doc_id and include_pdf=oui reads the issued PDF with read_file (base64) after the broker read succeeded, checks sha256 against the shared record, refuses pdf_integrity_failed, pdf_too_large (5 MiB) and invalid_path (outside the issued folder of the document). - documents.json: remove document-read-without-proof, which also passed on an unusable broker. Co-Authored-By: Claude Opus 5.5 --- catalog.json | 2 +- document-studio/README.md | 9 +++- .../agents/main/workflows/document-read.json | 32 ++++++++++++- inventory/modules.json | 4 +- .../company-in-a-box/tests/documents.json | 16 ------- tooling/document-studio/build.py | 41 ++++++++++++++--- tooling/document-studio/tests/test_module.py | 45 ++++++++++++++++++- 7 files changed, 120 insertions(+), 29 deletions(-) diff --git a/catalog.json b/catalog.json index 2eae75b..f6ca299 100644 --- a/catalog.json +++ b/catalog.json @@ -647,7 +647,7 @@ "subpath": "document-studio", "manifest": "document-studio/module.yaml", "manifest_sha256": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "tree_sha256": "e21fb5684d2de6fd01717a342dc35fbcb8776094431372ae7d0372bc26cb3ebc", + "tree_sha256": "abc9594b8caf6a133d05c3fcfc33fc2613e3b139675483ea4458bdd5c4793ddf", "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 23313a6..04ef7e1 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -45,8 +45,13 @@ be able to rewrite the reference). `expected_revision` is `0` for the first publ the previous call (compare-and-set). The shared record (`document-studio.shared/v1`) holds `doc_id`, `title`, `template_key`, `number`, `version` (the revision of the Storage record at issue), `path` (Storage path of the issued PDF), `sha256` and `issued_at`. Removing access (`none`) does not need the Storage record, so it still works after a -cancellation; a cancelled document stays referenced until its owner removes the members. Reading the PDF itself is a -Storage right, separate from the ACL of the reference. +cancellation; a cancelled document stays referenced until its owner removes the members. The PDF itself is read through the ACL of the +record, not through the Storage rights of the member: `document-read` with `doc_id` and `include_pdf: oui` (optional, +default `non`; a form field, `non` by default) reads the PDF at `data.path` from the Agent's Storage with `read_file` +(base64) only after the broker read succeeded, recomputes its SHA-256 and refuses `pdf_integrity_failed` when it differs +from the shared `sha256`, `pdf_too_large` above 5 MiB, and `invalid_path` when the path is not an issued document of +`/document-studio/docs//issued/`. It returns `pdf_base64`, `pdf_sha256` and `pdf_bytes`. `include_pdf` without a +`doc_id` is refused. ## Optional service in the Company-in-a-Box template diff --git a/document-studio/agents/main/workflows/document-read.json b/document-studio/agents/main/workflows/document-read.json index 0837fd9..84dd229 100644 --- a/document-studio/agents/main/workflows/document-read.json +++ b/document-studio/agents/main/workflows/document-read.json @@ -11,6 +11,13 @@ "required": [], "additionalProperties": false, "properties": { + "include_pdf": { + "type": [ + "boolean", + "string" + ], + "description": "oui to also return the issued PDF (base64, 5 MiB at most, checked against the shared sha256); default non" + }, "doc_id": { "type": "string", "description": "Document identifier; empty (or absent) lists the references the caller may read", @@ -28,6 +35,23 @@ "title": "Identifiant du document (vide pour la liste)", "type": "string", "required": false + }, + { + "name": "include_pdf", + "title": "Joindre le PDF", + "type": "select", + "required": false, + "options": [ + { + "value": "non", + "label": "Non" + }, + { + "value": "oui", + "label": "Oui" + } + ], + "default": "non" } ], "actions_on_submit": [ @@ -41,10 +65,11 @@ "type": "code_execution", "context": { "allowed_tools": [ + "read_file", "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 . }};\nif (input.doc_id === undefined || input.doc_id === null || input.doc_id === \"\") {\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};\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\");\nreturn {...brokerView(item), items: [], total: 1};\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.\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};\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" } ], @@ -57,6 +82,9 @@ "shares": "{{ result.shares }}", "share_count": "{{ result.share_count }}", "items": "{{ result.items }}", - "total": "{{ result.total }}" + "total": "{{ result.total }}", + "pdf_base64": "{{ result.pdf_base64 }}", + "pdf_sha256": "{{ result.pdf_sha256 }}", + "pdf_bytes": "{{ result.pdf_bytes }}" } } diff --git a/inventory/modules.json b/inventory/modules.json index a68b55f..47e8083 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1237,7 +1237,7 @@ ], "sha256": { "document-studio/module.yaml": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "document-studio/agents/main/workflows/document-read.json": "d71940349fd9f9013989a0de9c78b07c93d6cb3b758f579c2f6f33bf24c79048", + "document-studio/agents/main/workflows/document-read.json": "73ddf49d2fef665dac560d67d32827fefc96c29cf3959b76f5cf7ad1416b0b5a", "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", @@ -1263,7 +1263,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "ea1e3c187debf0615c24169bd8b9eb8e054c11b4184e696d17606c6fe7c78981" + "code_sha256": "ea8b634997c92b811c879fe2de2354da9c1282ed34d164627d56dd74a422c624" } ] }, diff --git a/templates/company-in-a-box/tests/documents.json b/templates/company-in-a-box/tests/documents.json index d5450fe..36d0402 100644 --- a/templates/company-in-a-box/tests/documents.json +++ b/templates/company-in-a-box/tests/documents.json @@ -38,22 +38,6 @@ "expected": "failed" } ] - }, - { - "id": "document-read-without-proof", - "description": "Exécution technique sans preuve humaine : le broker ACL doit refuser cet accès. Les cas positifs sont vérifiés avec les comptes existants depuis la surface CIB.", - "workflow": { - "workflow_id": "document-read", - "input": { - "doc_id": "devis-demo" - } - }, - "assertions": [ - { - "type": "status", - "expected": "failed" - } - ] } ] } diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index c1f5183..0b7c942 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -640,7 +640,15 @@ def load_templates(with_files): READ_CODE = r""" const input = {{ json . }}; +const wantPdf = (() => { + const v = input.include_pdf; + if (v === undefined || v === null || v === "" || v === false || v === "non" || v === "false") return false; + if (v === true || v === "oui" || v === "true") return true; + return fail("include_pdf_invalid", "oui ou non attendu"); +})(); +const MAX_PDF_BYTES = 5 * 1024 * 1024; if (input.doc_id === undefined || input.doc_id === null || input.doc_id === "") { + if (wantPdf) fail("include_pdf_requires_doc_id", "indiquez le document dont lire le PDF"); const response = await callTool("recipe--application_data_v1", {operation: "list", namespace: NAMESPACE, prefix: ""}); const payload = response && response.data ? response.data : response; if (!payload || !Array.isArray(payload.items) || !Number.isSafeInteger(payload.total) || payload.total !== payload.items.length) fail("broker_list_invalid"); @@ -655,7 +663,27 @@ def load_templates(with_files): const id = docIdOf(input.doc_id); const item = brokerItem(await callTool("recipe--application_data_v1", {operation: "read", namespace: NAMESPACE, record_key: id}), id); if (!isObject(item.data)) fail("broker_record_data_invalid"); -return {...brokerView(item), items: [], total: 1}; +const out = {...brokerView(item), items: [], total: 1, pdf_base64: null, pdf_sha256: null, pdf_bytes: null}; +if (wantPdf) { + // Only after the broker read succeeded: the ACL of the record, not the Storage rights of the member, opens the PDF. + const path = item.data.path; + const prefix = ROOT + "/docs/" + id + "/issued/"; + 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); + if (typeof item.data.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(item.data.sha256)) fail("broker_record_data_invalid", "empreinte absente"); + let r; + try { r = await callTool("read_file", {path, encoding: "base64"}); } catch (e) { fail("storage_unavailable", String(e && e.message).slice(0, 200)); } + if (isObject(r) && isObject(r.data) && r.content === undefined) r = r.data; + const encoded = typeof r === "string" ? r : (isObject(r) && typeof r.content === "string" ? r.content : null); + if (encoded === null) fail("storage_read_failed", path); + const clean = encoded.replace(/\s+/g, ""); + if (clean.length > Math.ceil(MAX_PDF_BYTES / 3) * 4) fail("pdf_too_large", "au plus 5 Mio"); + const bytes = b64ToBytes(clean); + if (bytes.length > MAX_PDF_BYTES) fail("pdf_too_large", "au plus 5 Mio"); + const sha = await sha256Hex(bytes); + if (sha !== item.data.sha256) fail("pdf_integrity_failed", "l'empreinte du PDF lu ne correspond pas au record partagé"); + out.pdf_base64 = clean; out.pdf_sha256 = sha; out.pdf_bytes = bytes.length; +} +return out; """ @@ -1101,13 +1129,16 @@ def build(): workflow('document-read', 'Read shared documents', 'Reads, through the native application data broker, the reference of one shared document (with the permissions of the ' 'caller), or lists the references the caller may read when doc_id is empty. Only the rights of the caller apply.', - schema([], doc_id=text('Document identifier; empty (or absent) lists the references the caller may read', pattern='^([a-z0-9][a-z0-9-]{0,47})?$')), - [node('read', code(IMPORT, lib(), BROKER_LIB, READ_CODE), 'result', tools=[BROKER])], + schema([], include_pdf={'type': ['boolean', 'string'], 'description': 'oui to also return the issued PDF (base64, 5 MiB at most, checked against the shared sha256); default non'}, doc_id=text('Document identifier; empty (or absent) lists the references the caller may read', pattern='^([a-z0-9][a-z0-9-]{0,47})?$')), + [node('read', code(IMPORT, lib(), BROKER_LIB, READ_CODE), 'result', tools=['read_file', BROKER])], {'record': '{{ result.record }}', 'revision': '{{ result.revision }}', 'owner_user_id': '{{ result.owner_user_id }}', 'permissions': '{{ result.permissions }}', 'permissions_summary': '{{ result.permissions_summary }}', 'shares': '{{ result.shares }}', 'share_count': '{{ result.share_count }}', 'items': '{{ result.items }}', - 'total': '{{ result.total }}'}, - forms=[form('document-read', 'Relire un document partagé', [field('doc_id', 'Identifiant du document (vide pour la liste)', 'string', False)], ['read'])]) + 'total': '{{ result.total }}', 'pdf_base64': '{{ result.pdf_base64 }}', 'pdf_sha256': '{{ result.pdf_sha256 }}', + 'pdf_bytes': '{{ result.pdf_bytes }}'}, + forms=[form('document-read', 'Relire un document partagé', [ + field('doc_id', 'Identifiant du document (vide pour la liste)', 'string', False), + field('include_pdf', 'Joindre le PDF', 'select', False, options=[{'value': 'non', 'label': 'Non'}, {'value': 'oui', 'label': 'Oui'}], default='non')], ['read'])]) miniapp() manifest() diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index 0b89aeb..7384395 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -923,7 +923,7 @@ def share(self, fs, **extra): return run_node('document-share', 'share', ctx, fs) def test_workflows_use_only_the_broker_and_read_the_record(self): - for name, tools in (('document-share', ['read_file', 'recipe--application_data_v1']), ('document-read', ['recipe--application_data_v1'])): + for name, tools in (('document-share', ['read_file', 'recipe--application_data_v1']), ('document-read', ['read_file', 'recipe--application_data_v1'])): wf = load(WORKFLOWS / f'{name}.json') self.assertEqual(wf['actions'][0]['context']['allowed_tools'], tools) self.assertNotIn('write_file', wf['actions'][0]['code']) @@ -1012,6 +1012,49 @@ def test_republishing_reports_the_real_shares_and_read_accepts_an_empty_id(self) self.assertEqual(schema['required'], []) self.assertEqual(ok(self, run_node('document-read', 'read', {'doc_id': ''}, fs))['total'], 1) + def shared(self): + fs = self.share(self.issued(), share_subject_user_id='member-b')['fs'] + record = json.loads(fs['/document-studio/docs/devis-test/record.json']['text']) + return fs, record['issued']['file'] + + def test_include_pdf_returns_the_checked_pdf_only_after_the_broker_read(self): + fs, file = self.shared() + plain = run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'non'}, fs) + self.assertIsNone(ok(self, plain)['pdf_base64']) + self.assertNotIn('read_file', [c['name'] for c in plain['calls']]) + out = run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'oui'}, fs) + result = ok(self, out) + self.assertEqual([c['name'] for c in out['calls']], ['recipe--application_data_v1', 'read_file']) + self.assertEqual(out['calls'][1]['args'], {'path': file['path'], 'encoding': 'base64'}) + self.assertEqual(result['pdf_sha256'], file['sha256']) + self.assertEqual(hashlib.sha256(base64.b64decode(result['pdf_base64'])).hexdigest(), file['sha256']) + self.assertEqual(result['pdf_bytes'], len(base64.b64decode(result['pdf_base64']))) + self.assertEqual(ok(self, run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': True}, fs))['pdf_sha256'], file['sha256']) + + def test_include_pdf_is_refused_when_the_broker_refuses_and_without_an_id(self): + fs, _ = self.shared() + denied = run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'oui'}, fs, broker_error='access_denied') + self.assertIn('error', denied) + self.assertNotIn('read_file', [c['name'] for c in denied['calls']]) + self.assertTrue(run_node('document-read', 'read', {'include_pdf': 'oui'}, fs)['error'].startswith('include_pdf_requires_doc_id')) + self.assertTrue(run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'peut-etre'}, fs)['error'].startswith('include_pdf_invalid')) + + def test_include_pdf_checks_integrity_size_and_path(self): + fs, file = self.shared() + bad = json.loads(json.dumps(fs)) + bad[file['path']] = {'b64': base64.b64encode(b'%PDF-other').decode()} + self.assertTrue(run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'oui'}, bad)['error'].startswith('pdf_integrity_failed')) + big = json.loads(json.dumps(fs)) + big[file['path']] = {'b64': base64.b64encode(b'a' * (5 * 1024 * 1024 + 1)).decode()} + self.assertTrue(run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'oui'}, big)['error'].startswith('pdf_too_large')) + for wrong in ('/etc/passwd', '/document-studio/profile.json', '/document-studio/docs/autre/issued/x.pdf', + '/document-studio/docs/devis-test/issued/../record.json', '/document-studio/docs/devis-test/r2-aaaaaaaaaaaa/document.pdf'): + forged = json.loads(json.dumps(fs)) + forged['__broker']['devis-test']['data']['path'] = wrong + out = run_node('document-read', 'read', {'doc_id': 'devis-test', 'include_pdf': 'oui'}, forged) + self.assertTrue(out['error'].startswith('invalid_path'), (wrong, out.get('error'))) + self.assertNotIn('read_file', [c['name'] for c in out['calls']]) + class ProfileSourceTest(unittest.TestCase): BROKER_PROFILE = json.loads(json.dumps(PROFILE)) | {} From c82c4b550a503c51a54d4c83fe0bb3ce368c12b1 Mon Sep 17 00:00:00 2001 From: "Claude Code (agent)" Date: Mon, 9 Nov 2026 06:39:09 +0100 Subject: [PATCH 5/5] AGENT-1831: document-read list branch returns every declared output (pdf_* null) The runtime resolves each declared output path on every branch; the list branch lacked pdf_base64, pdf_sha256 and pdf_bytes. A test now checks all declared keys on every simulated branch of document-read and document-share. Co-Authored-By: Claude Opus 5.5 --- catalog.json | 2 +- .../agents/main/workflows/document-read.json | 2 +- inventory/modules.json | 4 ++-- tooling/document-studio/build.py | 2 +- tooling/document-studio/tests/test_module.py | 21 +++++++++++++++++++ 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/catalog.json b/catalog.json index f6ca299..7294cff 100644 --- a/catalog.json +++ b/catalog.json @@ -647,7 +647,7 @@ "subpath": "document-studio", "manifest": "document-studio/module.yaml", "manifest_sha256": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "tree_sha256": "abc9594b8caf6a133d05c3fcfc33fc2613e3b139675483ea4458bdd5c4793ddf", + "tree_sha256": "29506c05042540c7d48cbac82db0006ff390b824546b931a442a6b1f99e675e1", "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/agents/main/workflows/document-read.json b/document-studio/agents/main/workflows/document-read.json index 84dd229..2f0a66c 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};\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.\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", "output_key": "result" } ], diff --git a/inventory/modules.json b/inventory/modules.json index 47e8083..af292d2 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1237,7 +1237,7 @@ ], "sha256": { "document-studio/module.yaml": "64bb28f928d537ff486519146022efab8cc1e2edbe5bbc898a96012ccfe602eb", - "document-studio/agents/main/workflows/document-read.json": "73ddf49d2fef665dac560d67d32827fefc96c29cf3959b76f5cf7ad1416b0b5a", + "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", @@ -1263,7 +1263,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "ea8b634997c92b811c879fe2de2354da9c1282ed34d164627d56dd74a422c624" + "code_sha256": "9b7bfbe9723c6ed11b2af8a504f5f5e0dbe27c1fd636f87ee65e552b0f229b37" } ] }, diff --git a/tooling/document-studio/build.py b/tooling/document-studio/build.py index 0b7c942..ae73e6a 100644 --- a/tooling/document-studio/build.py +++ b/tooling/document-studio/build.py @@ -658,7 +658,7 @@ def load_templates(with_files): const d = isObject(view.data) ? view.data : (isObject(view.record) ? view.record : {}); 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 : {}}; }); - return {items, total: payload.total, record: null, revision: null, owner_user_id: "", permissions: null, permissions_summary: "", shares: [], share_count: 0}; + 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}; } const id = docIdOf(input.doc_id); const item = brokerItem(await callTool("recipe--application_data_v1", {operation: "read", namespace: NAMESPACE, record_key: id}), id); diff --git a/tooling/document-studio/tests/test_module.py b/tooling/document-studio/tests/test_module.py index 7384395..e75afed 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -1055,6 +1055,27 @@ def test_include_pdf_checks_integrity_size_and_path(self): self.assertTrue(out['error'].startswith('invalid_path'), (wrong, out.get('error'))) self.assertNotIn('read_file', [c['name'] for c in out['calls']]) + def declared_keys(self, name): + wf = load(WORKFLOWS / f'{name}.json') + return {m for v in wf['output'].values() if isinstance(v, str) for m in re.findall(r'\{\{ result\.(\w+) \}\}', v)} + + def test_every_declared_output_exists_on_every_branch(self): + # The runtime resolves each declared output path and fails when a key is absent, whatever the branch. + fs, _ = self.shared() + read_keys = self.declared_keys('document-read') + self.assertLessEqual({'pdf_base64', 'pdf_sha256', 'pdf_bytes', 'items', 'total', 'record'}, read_keys) + for label, ctx in (('list', {'doc_id': ''}), ('list-absent', {}), ('read', {'doc_id': 'devis-test'}), + ('read-pdf-non', {'doc_id': 'devis-test', 'include_pdf': 'non'}), ('read-pdf', {'doc_id': 'devis-test', 'include_pdf': 'oui'})): + result = ok(self, run_node('document-read', 'read', ctx, fs)) + self.assertLessEqual(read_keys, set(result), (label, read_keys - set(result))) + share_keys = self.declared_keys('document-share') + issued = self.issued() + for label, ctx in (('publish', {}), ('share', {'share_subject_user_id': 'member-b'})): + result = ok(self, self.share(issued, **ctx)) + self.assertLessEqual(share_keys, set(result), (label, share_keys - set(result))) + removal = ok(self, run_node('document-share', 'share', {'doc_id': 'devis-test', 'confirmation_manuelle': 'oui', 'expected_revision': '2', 'share_subject_user_id': 'member-b', 'share_permission': 'none'}, self.share(issued, share_subject_user_id='member-b')['fs'])) + self.assertLessEqual(share_keys, set(removal), share_keys - set(removal)) + class ProfileSourceTest(unittest.TestCase): BROKER_PROFILE = json.loads(json.dumps(PROFILE)) | {}