diff --git a/catalog.json b/catalog.json index 0f87ab7..64ff3d7 100644 --- a/catalog.json +++ b/catalog.json @@ -643,11 +643,11 @@ { "key": "document-studio", "name": "Document studio", - "version": "0.2.0", + "version": "0.3.0", "subpath": "document-studio", "manifest": "document-studio/module.yaml", - "manifest_sha256": "2e09f02654084161cdea77ebbdeb479e7da92034c5939b63cfb73402747cdecb", - "tree_sha256": "b1d2ddedab8e740cf8313da9a5fa6094b7b8da875035a5c9e98626c8454091d2", + "manifest_sha256": "f31b391b04ecf28700efb19584a020a2e72ddcb5c7ade5c5b6f6f3113f4562db", + "tree_sha256": "66f0b03609f2dfbb16859747646ae16fb778703f8544b36f318b8e94ae497fc0", "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." @@ -693,6 +693,10 @@ "key": "document-studio-profile-save", "name": "Save the company profile" }, + { + "key": "document-share", + "name": "Share an issued document" + }, { "key": "document-studio-new-version", "name": "Add a DOCX version" @@ -705,7 +709,8 @@ "queries": [ "document-studio-list", "document-studio-review-read", - "document-studio-template-read" + "document-studio-template-read", + "document-read" ], "requires": { "runtimes": [ @@ -720,7 +725,7 @@ "model": "free" }, "maturity": "preview", - "workflows": 13, + "workflows": 15, "miniapps": 1 }, { diff --git a/document-studio/README.md b/document-studio/README.md index 331dc91..0d73110 100644 --- a/document-studio/README.md +++ b/document-studio/README.md @@ -28,6 +28,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 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 @@ -37,6 +39,31 @@ 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. 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 + +`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. `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 `draft` (successive renders) → `approved` → `issued`. `cancelled` is reachable @@ -48,7 +75,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. @@ -60,8 +87,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. ## DOCX versions @@ -127,11 +157,10 @@ renderer, on synthetic data. They do not prove the behavior on a One. ## Known limits (V0) +- 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. - Concurrent `mark-authoritative`: two calls on the same document at the same time are not safe. Both may pass the second read and the later write wins, which can leave the wrong version authoritative or bring a superseded one back while both calls report success. Serialise them (one writer per document). Moving the manifest to `application_data_v1`, which has compare-and-swap, lifts this limit (lot 4). - Versions: Storage has no compare-and-swap. A manifest is read, the version file and redline are written, then the manifest is read again and written only if its text is unchanged (`concurrent_update` otherwise; a first manifest is written without overwrite). The window between the second read and the write is small, not null: allow one writer at a time per document. Files written before an abandoned manifest write stay orphaned in `versions/`. Pass `base_version` and `base_manifest_sha256` (returned as `manifest_sha256`) to make a stale caller fail. - Versions are DOCX only (XLSX and PDF are out of this lot), the comparison and its 20 MiB input limit are those of `office_compare_v1`, and there is no review MiniApp for versions yet. - -- 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 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 rendering (DOCX files are only versioned), 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..2f0a66c --- /dev/null +++ b/document-studio/agents/main/workflows/document-read.json @@ -0,0 +1,90 @@ +{ + "$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": { + "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", + "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 + }, + { + "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": [ + "read" + ] + } + ], + "actions": [ + { + "id": "read", + "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 . }};\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" + } + ], + "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 }}", + "pdf_base64": "{{ result.pdf_base64 }}", + "pdf_sha256": "{{ result.pdf_sha256 }}", + "pdf_bytes": "{{ result.pdf_bytes }}" + } +} 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..2b7a8bb --- /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.\" : (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" + } + ], + "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/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-mark-authoritative.json b/document-studio/agents/main/workflows/document-studio-mark-authoritative.json index f73c33c..df3a83d 100644 --- a/document-studio/agents/main/workflows/document-studio-mark-authoritative.json +++ b/document-studio/agents/main/workflows/document-studio-mark-authoritative.json @@ -103,7 +103,7 @@ "office_inspect_v1" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true);\n if (!ok) { errors.push(path + \" : type \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n if (key === \"quote\") checkQuoteNumbers(d);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\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// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"version\", \"confirmation_manuelle\", \"approved_by\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst version = optionalInteger(input.version, \"version\", 1);\nif (version === undefined) fail(\"version_required\");\nconst approvedBy = text(input.approved_by, \"approved_by\", 200, false);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version qui fait foi\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nif (!manifest) fail(\"manifest_not_found\", \"aucune version enregistrée pour \" + id);\nconst entry = manifest.versions.find((e) => e.version === version);\nif (!entry) fail(\"version_not_found\", \"version \" + version);\n// Replay: the version already is authoritative, nothing is written.\nif (entry.status === \"authoritative\") return versionSummary(id, entry, manifest, msha, true);\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + msha + \") ; rien n'a été écrit\");\nif (entry.status !== \"draft\") fail(\"status_invalid\", \"la version \" + version + \" est \" + entry.status + \" : ajoutez une nouvelle version au lieu de la rétablir\");\nconst current = authoritativeOf(manifest);\nif (current && current.version > version) fail(\"status_invalid\", \"la version \" + current.version + \" fait foi et est plus récente : ajoutez une nouvelle version\");\nawait readVersionFile(entry, true);\nconst at = nowIso();\nconst versions = manifest.versions.map((e) => {\n if (e.version === version) return {...e, status: \"authoritative\", supersedes: current ? current.version : null, authoritative_at: at, ...(approvedBy ? {approved_by: approvedBy} : {})};\n if (current && e.version === current.version) return {...e, status: \"superseded\", superseded_by: version, superseded_at: at};\n return e;\n});\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions, history: manifest.history.concat([{at, action: \"marked_authoritative\", version, supersedes: current ? current.version : null, ...(approvedBy ? {approved_by: approvedBy} : {}), note: \"confirmation manuelle donnée\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, versions[version - 1], next, written, false);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true);\n if (!ok) { errors.push(path + \" : type \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n if (key === \"quote\") checkQuoteNumbers(d);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrequireConfirmation(input);\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"version\", \"confirmation_manuelle\", \"approved_by\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst version = optionalInteger(input.version, \"version\", 1);\nif (version === undefined) fail(\"version_required\");\nconst approvedBy = text(input.approved_by, \"approved_by\", 200, false);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version qui fait foi\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nif (!manifest) fail(\"manifest_not_found\", \"aucune version enregistrée pour \" + id);\nconst entry = manifest.versions.find((e) => e.version === version);\nif (!entry) fail(\"version_not_found\", \"version \" + version);\n// Replay: the version already is authoritative, nothing is written.\nif (entry.status === \"authoritative\") return versionSummary(id, entry, manifest, msha, true);\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + msha + \") ; rien n'a été écrit\");\nif (entry.status !== \"draft\") fail(\"status_invalid\", \"la version \" + version + \" est \" + entry.status + \" : ajoutez une nouvelle version au lieu de la rétablir\");\nconst current = authoritativeOf(manifest);\nif (current && current.version > version) fail(\"status_invalid\", \"la version \" + current.version + \" fait foi et est plus récente : ajoutez une nouvelle version\");\nawait readVersionFile(entry, true);\nconst at = nowIso();\nconst versions = manifest.versions.map((e) => {\n if (e.version === version) return {...e, status: \"authoritative\", supersedes: current ? current.version : null, authoritative_at: at, ...(approvedBy ? {approved_by: approvedBy} : {})};\n if (current && e.version === current.version) return {...e, status: \"superseded\", superseded_by: version, superseded_at: at};\n return e;\n});\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions, history: manifest.history.concat([{at, action: \"marked_authoritative\", version, supersedes: current ? current.version : null, ...(approvedBy ? {approved_by: approvedBy} : {}), note: \"confirmation manuelle donnée\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, versions[version - 1], next, written, false);\n", "output_key": "result" } ], diff --git a/document-studio/agents/main/workflows/document-studio-new-version.json b/document-studio/agents/main/workflows/document-studio-new-version.json index cbfa311..ad62dcc 100644 --- a/document-studio/agents/main/workflows/document-studio-new-version.json +++ b/document-studio/agents/main/workflows/document-studio-new-version.json @@ -83,7 +83,7 @@ "office_inspect_v1" ] }, - "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true);\n if (!ok) { errors.push(path + \" : type \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n if (key === \"quote\") checkQuoteNumbers(d);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\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// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"source_path\", \"author\", \"base_version\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst source = sourcePathOf(input.source_path);\nconst author = text(input.author, \"author\", 200, true);\nconst baseVersion = optionalInteger(input.base_version, \"base_version\", 0);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nif (source.startsWith(versionsDir(id) + \"/\")) fail(\"source_invalid\", \"la source ne peut pas être un fichier du dossier des versions\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nconst latest = lastVersion(manifest);\nconst latestN = latest ? latest.version : 0;\nconst file = await readDocx(source, \"source_not_found\");\n// The request fingerprint covers what the caller decided (document, bytes, author), never the base: a replay of ANY earlier\n// write is recognised whatever the manifest became since, and writes nothing.\nconst request = await fingerprint({action: \"new-version\", doc_id: id, sha256: file.sha, author});\nconst replayed = manifest ? manifest.versions.find((e) => e.request_sha256 === request && (baseVersion === undefined || baseVersion === e.version - 1)) : undefined;\nif (replayed) return versionSummary(id, replayed, manifest, msha, true);\nif (baseVersion !== undefined && baseVersion !== latestN) fail(\"base_version_conflict\", \"la dernière version est \" + latestN + \", la demande part de \" + baseVersion + \" ; rien n'a été écrit\");\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + (msha || \"absente\") + \") ; rien n'a été écrit\");\nif (latest && latest.sha256 === file.sha) fail(\"version_unchanged\", \"le fichier est identique à la version \" + latest.version);\n// The first version never goes through office_compare_v1: the engine reads it here, before any write.\nif (!latest) await inspectDocx(file, source);\nconst n = latestN + 1;\nconst dir = versionsDir(id);\nconst short = file.sha.slice(0, 12);\nlet redline = null, changes = null;\nif (latest) {\n const prev = await readVersionFile(latest);\n const cmp = await compareVersions(prev, file, author, n);\n redline = await storeRedline(dir, n, short, cmp.file);\n changes = cmp.changes;\n}\nconst path = dir + \"/v\" + n + \"-\" + short + \".docx\";\nawait storeBytes(path, file.b64, file.sha);\nconst entry = {version: n, sha256: file.sha, bytes: file.bytes, storage_ref: path, redline_ref: redline ? redline.path : null, redline_sha256: redline ? redline.sha256 : null,\n changes, author, created_at: nowIso(), status: \"draft\", supersedes: null, base_version: latest ? latest.version : null, request_sha256: request};\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions: (manifest ? manifest.versions : []).concat([entry]),\n history: (manifest ? manifest.history : []).concat([{at: entry.created_at, action: \"version_added\", version: n, author, note: latest ? \"comparée à la version \" + latest.version : \"première version\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, entry, next, written, false);\n", + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst ROOT = \"/document-studio\";\nconst ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;\nconst STATUSES = [\"draft\", \"approved\", \"issued\", \"cancelled\"];\n\nfunction fail(code, message) { throw new Error(message ? code + \": \" + message : code); }\nfunction isObject(v) { return v !== null && typeof v === \"object\" && !Array.isArray(v); }\nfunction confirmed(v) { return v === true || v === \"true\" || v === \"oui\"; }\nfunction requireConfirmation(input) { if (!confirmed(input.confirmation_manuelle)) fail(\"manual_confirmation_required\", \"confirmez explicitement (confirmation_manuelle = oui)\"); }\n// The clock can be injected by the offline test bench (globalThis.__dsNow); in a One it is always the real clock.\nfunction clock() { return typeof globalThis.__dsNow === \"string\" ? new Date(globalThis.__dsNow) : new Date(); }\nfunction today() { return clock().toISOString().slice(0, 10); }\nfunction nowIso() { return clock().toISOString(); }\nfunction own(o, k) { return Object.prototype.hasOwnProperty.call(o, k); }\n// External data (model answer, patch, answers, profile) never carries these keys, at any depth.\nfunction rejectUnsafeKeys(v, label) {\n if (Array.isArray(v)) { v.forEach((x) => rejectUnsafeKeys(x, label)); return; }\n if (!isObject(v)) return;\n // An object literal written as {\"__proto__\": ...} in generated code sets the prototype instead of a key.\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) fail(\"data_invalid\", label + \" : prototype inattendu\");\n for (const k of Object.keys(v)) {\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") fail(\"data_invalid\", label + \" : clé interdite \" + k);\n rejectUnsafeKeys(v[k], label);\n }\n}\nfunction docIdOf(v) { if (typeof v !== \"string\" || !ID_RE.test(v)) fail(\"doc_id_invalid\", \"attendu : minuscules, chiffres et tirets, 48 caractères au plus\"); return v; }\nfunction slugify(text) {\n const base = String(text || \"\").normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40).replace(/-+$/g, \"\");\n return base || \"doc\";\n}\nfunction shortSuffix() { const bytes = new Uint8Array(3); crypto.getRandomValues(bytes); return Array.from(bytes, (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction validDate(v) {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(typeof v === \"string\" ? v : \"\");\n if (!m) return false;\n const d = new Date(v + \"T00:00:00Z\");\n return !Number.isNaN(d.getTime()) && d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() + 1 === Number(m[2]) && d.getUTCDate() === Number(m[3]);\n}\nfunction text(v, name, max, required) {\n if (v === undefined || v === null || v === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof v !== \"string\" || v.length > max) fail(name + \"_invalid\");\n const t = v.trim();\n if (required && !t) fail(name + \"_required\");\n return t;\n}\nfunction canonical(v) { return Array.isArray(v) ? \"[\" + v.map(canonical).join(\",\") + \"]\" : isObject(v) ? \"{\" + Object.keys(v).sort().map((k) => JSON.stringify(k) + \":\" + canonical(v[k])).join(\",\") + \"}\" : JSON.stringify(v); }\nasync function fingerprint(v) { return sha256Hex(new TextEncoder().encode(canonical(v))); }\nfunction b64ToBytes(b64) { const bin = atob(b64); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; }\nasync function sha256Hex(bytes) { const d = await crypto.subtle.digest(\"SHA-256\", bytes); return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, \"0\")).join(\"\"); }\nfunction parseJsonValue(v) {\n // llm_call with llm_response_format \"text\" yields {text, model, provider}.\n if (v && typeof v === \"object\" && !Array.isArray(v) && typeof v.text === \"string\") v = v.text;\n if (typeof v !== \"string\") { rejectUnsafeKeys(v, \"réponse du modèle\"); return v; }\n const cleaned = v.trim().replace(/^```(?:json)?\\s*/i, \"\").replace(/\\s*```$/, \"\");\n let parsed;\n try { parsed = JSON.parse(cleaned); } catch (e) { fail(\"llm_output_invalid\", \"réponse non JSON\"); }\n rejectUnsafeKeys(parsed, \"réponse du modèle\");\n return parsed;\n}\n\n// Subset of JSON Schema: $ref (#/$defs), type, enum, required, properties, additionalProperties false,\n// items, minItems, maxItems, minLength, pattern, format date, minimum, maximum, exclusiveMinimum.\nfunction checkSchema(schema, value, path, root, errors) {\n if (errors.length >= 8) return;\n if (schema.$ref) {\n if (!schema.$ref.startsWith(\"#/\")) fail(\"schema_ref_unsupported\", schema.$ref);\n let node = root;\n for (const part of schema.$ref.slice(2).split(\"/\")) node = node ? node[part] : undefined;\n if (!node) fail(\"schema_ref_unknown\", schema.$ref);\n return checkSchema(node, value, path, root, errors);\n }\n if (value === null) {\n if (schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes(\"null\")) || schema.type === \"null\") return;\n errors.push(path + \" : null non autorisé\");\n return;\n }\n const types = Array.isArray(schema.type) ? schema.type : (schema.type ? [schema.type] : []);\n if (types.length) {\n const ok = types.some((t) => t === \"null\" ? false : t === \"string\" ? typeof value === \"string\" : t === \"number\" ? (typeof value === \"number\" && Number.isFinite(value)) : t === \"integer\" ? Number.isInteger(value) : t === \"boolean\" ? typeof value === \"boolean\" : t === \"array\" ? Array.isArray(value) : t === \"object\" ? isObject(value) : true);\n if (!ok) { errors.push(path + \" : type \" + types.join(\"|\") + \" attendu\"); return; }\n }\n if (schema.enum && !schema.enum.includes(value)) errors.push(path + \" : valeur hors liste\");\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) errors.push(path + \" : vide ou trop court\");\n if (schema.maxLength !== undefined && value.length > schema.maxLength) errors.push(path + \" : trop long\");\n if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(path + \" : format invalide\");\n if (schema.format === \"date\" && !validDate(value)) errors.push(path + \" : date AAAA-MM-JJ invalide\");\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) errors.push(path + \" : inférieur au minimum\");\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) errors.push(path + \" : doit être supérieur à \" + schema.exclusiveMinimum);\n if (schema.maximum !== undefined && value > schema.maximum) errors.push(path + \" : supérieur au maximum\");\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) errors.push(path + \" : trop peu d'éléments\");\n if (schema.maxItems !== undefined && value.length > schema.maxItems) errors.push(path + \" : trop d'éléments\");\n if (schema.items) value.forEach((item, i) => checkSchema(schema.items, item, path + \"[\" + i + \"]\", root, errors));\n }\n if (isObject(value)) {\n for (const key of schema.required || []) if (value[key] === undefined || value[key] === null) errors.push(path + \".\" + key + \" : requis\");\n const props = schema.properties || {};\n for (const key of Object.keys(props)) if (value[key] !== undefined) checkSchema(props[key], value[key], path + \".\" + key, root, errors);\n if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!own(props, key)) errors.push(path + \".\" + key + \" : champ inconnu\");\n }\n}\nfunction resolveRef(schema, root) {\n let node = schema;\n while (node && node.$ref) { let n = root; for (const part of node.$ref.slice(2).split(\"/\")) n = n ? n[part] : undefined; node = n; }\n return node || {};\n}\nfunction isNullable(schema, root) { const n = resolveRef(schema, root); return n.nullable === true || n.type === \"null\" || (Array.isArray(n.type) && n.type.includes(\"null\")); }\n// An optional property set to null is removed before validation (simplest for a model); a required one stays and fails.\nfunction stripNulls(schema, value, root) {\n const node = resolveRef(schema, root);\n if (Array.isArray(value)) return node.items ? value.map((v) => stripNulls(node.items, v, root)) : value;\n if (!isObject(value)) return value;\n const props = node.properties || {};\n const out = Object.create(null);\n for (const [key, v] of Object.entries(value)) {\n const sub = own(props, key) ? props[key] : null;\n if (v === null && !(node.required || []).includes(key) && !(sub && isNullable(sub, root))) continue;\n Object.defineProperty(out, key, {value: sub ? stripNulls(sub, v, root) : v, enumerable: true, writable: true, configurable: true});\n }\n return out;\n}\nfunction validateSchema(schema, value, label) {\n const errors = [];\n checkSchema(schema, value, \"$\", schema, errors);\n if (errors.length) fail(\"data_invalid\", label + \" : \" + errors.join(\" ; \"));\n}\n\nfunction fmtMoney(cents) {\n const big = BigInt(cents);\n const abs = big < 0n ? -big : big;\n const grouped = String(abs / 100n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \" \");\n return (big < 0n ? \"-\" : \"\") + grouped + \",\" + String(abs % 100n).padStart(2, \"0\") + \" €\";\n}\nfunction fmtNumber(n) { return String(n).replace(\".\", \",\"); }\nconst VAT_RATES = [0, 2.1, 5.5, 10, 20];\n// Exact check on the shortest decimal writing of the number (the JSON literal): no tolerance, no exponent.\nfunction decimalsAtMost(n, places) { return typeof n === \"number\" && Number.isFinite(n) && new RegExp(\"^-?\\\\d+(\\\\.\\\\d{1,\" + places + \"})?$\").test(String(n)); }\nfunction checkQuoteNumbers(d) {\n const errors = [];\n d.lines.forEach((l, i) => {\n const at = \"lines[\" + i + \"]\";\n const q1000 = Math.round(l.quantity * 1000);\n const p100 = Math.round(l.unit_price_ht * 100);\n if (!decimalsAtMost(l.quantity, 3)) errors.push(at + \".quantity : 3 décimales au plus\");\n else if (q1000 < 1 || q1000 > 1e9) errors.push(at + \".quantity : entre 0,001 et 1000000\");\n if (!decimalsAtMost(l.unit_price_ht, 2)) errors.push(at + \".unit_price_ht : 2 décimales au plus\");\n else if (p100 < 0 || p100 > 1e11) errors.push(at + \".unit_price_ht : entre 0 et 1000000000\");\n if (!VAT_RATES.includes(l.vat_rate)) errors.push(at + \".vat_rate : taux autorisés 0, 2.1, 5.5, 10 ou 20\");\n });\n if (!errors.length) { try { quoteAmounts(d); } catch (e) { errors.push(String(e.message).replace(/^data_invalid: /, \"\")); } }\n if (errors.length) fail(\"data_invalid\", \"données du gabarit quote : \" + errors.slice(0, 8).join(\" ; \"));\n}\nfunction fmtRate(r) { return fmtNumber(r) + \" %\"; }\n\n// Amounts and totals are computed here, in BigInt cents (no intermediate Number), from the lines. They are never\n// taken from the model. Rounding to the cent is half up. Every amount stays under 1e16 cents (100 trillion euros).\nconst MAX_CENTS = 10000000000000000n;\nfunction quoteAmounts(d) {\n const lines = [];\n let ht = 0n;\n const groups = new Map();\n for (const l of d.lines) {\n const q1000 = BigInt(Math.round(l.quantity * 1000));\n const unit = BigInt(Math.round(l.unit_price_ht * 100));\n const total = (q1000 * unit + 500n) / 1000n;\n const rate = BigInt(Math.round(l.vat_rate * 100));\n if (total > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant de ligne trop grand\");\n ht += total;\n groups.set(rate, (groups.get(rate) || 0n) + total);\n lines.push({l, unit, total, rate});\n }\n let vatTotal = 0n;\n const vat = Array.from(groups.entries()).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([rate, base]) => {\n const cents = (base * rate + 5000n) / 10000n;\n vatTotal += cents;\n return {rate, cents};\n });\n if (ht > MAX_CENTS || ht + vatTotal > MAX_CENTS) fail(\"data_invalid\", \"totaux : montant du document trop grand\");\n return {lines, ht, vat, ttc: ht + vatTotal};\n}\nfunction quoteData(d) {\n const a = quoteAmounts(d);\n const lines = a.lines.map(({l, unit, total, rate}) => ({description: l.description, quantity: fmtNumber(l.quantity) + (l.unit ? \" \" + l.unit : \"\"), unit_price_ht: fmtMoney(unit), vat_rate: fmtRate(Number(rate) / 100), total_ht: fmtMoney(total)}));\n const customer = d.customer;\n return {reference: d.reference, customer: {name: customer.name, address_lines: customer.address_lines || [], contact: customer.contact || \"\"}, lines, totals: {total_ht: fmtMoney(a.ht), vat: a.vat.map((v) => ({rate: fmtRate(Number(v.rate) / 100), amount: fmtMoney(v.cents)})), total_ttc: fmtMoney(a.ttc)}, valid_until: d.valid_until, terms: d.terms || [], payment_terms: d.payment_terms || \"\"};\n}\nfunction templateData(key, data) { return key === \"quote\" ? quoteData(data) : data; }\n\n// Draft data: reference default, validation against the draft schema, then against the template input schema.\nfunction normalizeData(key, data, id) {\n if (!isObject(data)) fail(\"data_invalid\", \"les données doivent être un objet\");\n rejectUnsafeKeys(data, \"données\");\n let d = stripNulls(TEMPLATES[key].draft_schema, data, TEMPLATES[key].draft_schema);\n if (key === \"quote\" && (d.reference === undefined || d.reference === null || d.reference === \"\")) d = {...d, reference: id.toUpperCase()};\n const tpl = TEMPLATES[key];\n validateSchema(tpl.draft_schema, d, \"données du gabarit \" + key);\n if (key === \"quote\") checkQuoteNumbers(d);\n validateSchema(tpl.input_schema, templateData(key, d), \"gabarit \" + key);\n return d;\n}\n\nfunction summarize(rec) {\n const last = rec.renders.length ? rec.renders[rec.renders.length - 1] : null;\n return {doc_id: rec.doc_id, template_key: rec.template_key, title: rec.title, locale: rec.locale, status: rec.status, number: rec.number, revision: rec.revision, renders: rec.renders.length, last_render: last ? {revision: last.revision, mode: last.mode, path: last.file.path, sha256: last.file.sha256, pages: last.previews.length} : null, issued: rec.issued};\n}\nfunction checkRecord(rec, id) {\n if (!isObject(rec) || rec.schema !== \"document-studio.record/v1\" || rec.doc_id !== id || !STATUSES.includes(rec.status) || !Number.isInteger(rec.revision) || !Array.isArray(rec.renders) || !Array.isArray(rec.history) || typeof rec.template_key !== \"string\" || !isObject(rec.data)) fail(\"record_invalid\", id);\n return rec;\n}\n\nfunction unwrap(r) {\n if (isObject(r) && isObject(r.data) && r.content === undefined && r.file === undefined && r.status === undefined) return r.data;\n return r;\n}\nfunction isMissing(message) { return /not found|does not exist|no such/i.test(message); }\nasync function readText(path, extra) {\n let r;\n try { r = unwrap(await callTool(\"read_file\", {path, ...(extra || {})})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) fail(\"storage_not_found\", path);\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n if (typeof r === \"string\") return r;\n if (isObject(r) && typeof r.content === \"string\") return r.content;\n fail(\"storage_read_failed\", path);\n}\nasync function readJson(path) {\n const raw = await readText(path);\n try { return JSON.parse(raw); } catch (e) { fail(\"json_corrupt\", path); }\n}\nasync function writeJson(path, value, overwrite) {\n await callTool(\"write_file\", {path, content: JSON.stringify(value, null, 2) + \"\\n\", overwrite});\n}\nasync function listPaths(path) {\n let r;\n try { r = unwrap(await callTool(\"list_files\", {path})); } catch (e) {\n const message = String(e && e.message);\n if (isMissing(message)) return [];\n fail(\"storage_unavailable\", message.slice(0, 200));\n }\n const entries = Array.isArray(r) ? r : (isObject(r) ? (r.files || r.entries || []) : []);\n return entries.map((e) => (typeof e === \"string\" ? e : (isObject(e) && typeof e.path === \"string\" ? e.path : \"\"))).filter(Boolean);\n}\nfunction recordPath(id) { return ROOT + \"/docs/\" + id + \"/record.json\"; }\nfunction remember(rec) { Object.defineProperty(rec, \"_loaded\", {value: {revision: rec.revision, status: rec.status}, enumerable: false, writable: true, configurable: true}); return rec; }\nasync function loadRecord(id) {\n let rec;\n try { rec = await readJson(recordPath(id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"document_not_found\", id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", id);\n throw e;\n }\n return remember(checkRecord(rec, id));\n}\n// Storage has no conditional write: the record is read again just before the write, and the write is abandoned when\n// another actor changed it (revision or status). The window is small, not null.\nasync function saveRecord(rec) {\n let fresh;\n try { fresh = await readJson(recordPath(rec.doc_id)); } catch (e) {\n const m = String(e && e.message);\n if (m.startsWith(\"storage_not_found\")) fail(\"concurrent_update\", \"le dossier a disparu : \" + rec.doc_id);\n if (m.startsWith(\"json_corrupt\")) fail(\"record_corrupt\", rec.doc_id);\n throw e;\n }\n const was = rec._loaded;\n if (!isObject(fresh) || !was || fresh.revision !== was.revision || fresh.status !== was.status || fresh.status === \"cancelled\" && was.status !== \"cancelled\") fail(\"concurrent_update\", \"le dossier \" + rec.doc_id + \" a changé pendant l'opération ; rien n'a été écrit\");\n await writeJson(recordPath(rec.doc_id), rec, true);\n remember(rec);\n}\n\n// DOCX versions of a document. Everything lives in Storage under docs//versions/: one immutable file per version\n// (name carries the version number and 12 characters of the SHA-256), one redline per version (office_compare_v1 between\n// the previous version and this one) and ONE manifest. The record of the document (record.json) is never written here.\nconst MAX_DOCX_BYTES = 20 * 1024 * 1024;\nconst SHA_RE = /^[0-9a-f]{64}$/;\nconst MANIFEST_SCHEMA = \"document-studio.versions/v1\";\nconst VERSION_STATUSES = [\"draft\", \"authoritative\", \"superseded\"];\nfunction versionsDir(id) { return ROOT + \"/docs/\" + id + \"/versions\"; }\nfunction manifestPath(id) { return versionsDir(id) + \"/manifest.json\"; }\nfunction onlyInput(input, allowed) {\n if (!isObject(input)) fail(\"input_invalid\", \"objet attendu\");\n for (const k of Object.keys(input)) if (!allowed.includes(k)) fail(\"input_unknown_field\", k);\n}\nfunction optionalInteger(v, name, min) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const n = typeof v === \"string\" && /^\\d{1,9}$/.test(v.trim()) ? Number(v.trim()) : v;\n if (!Number.isInteger(n) || n < min) fail(name + \"_invalid\", \"entier attendu, \" + min + \" au minimum\");\n return n;\n}\nfunction optionalDigest(v, name) {\n if (v === undefined || v === null || v === \"\") return undefined;\n const d = typeof v === \"string\" ? v.trim().toLowerCase() : \"\";\n if (!SHA_RE.test(d)) fail(name + \"_invalid\", \"empreinte SHA-256 hexadécimale attendue\");\n return d;\n}\nfunction sourcePathOf(v) {\n if (typeof v !== \"string\" || !v.startsWith(\"/\") || v.length > 300 || v.includes(\"..\") || v.includes(\"//\") || /\\s$/.test(v) || !/\\.docx$/i.test(v)) fail(\"source_invalid\", \"chemin Storage absolu d'un fichier .docx attendu\");\n return v;\n}\nfunction lastVersion(m) { return m && m.versions.length ? m.versions[m.versions.length - 1] : null; }\nfunction authoritativeOf(m) { return m ? (m.versions.find((e) => e.status === \"authoritative\") || null) : null; }\nasync function manifestSha(raw) { return raw === null ? null : sha256Hex(new TextEncoder().encode(raw)); }\nfunction checkManifest(m, id) {\n if (!isObject(m) || m.schema !== MANIFEST_SCHEMA || m.doc_id !== id || !Array.isArray(m.versions) || !Array.isArray(m.history)) fail(\"manifest_corrupt\", id);\n let authoritative = 0;\n m.versions.forEach((e, i) => {\n if (!isObject(e) || e.version !== i + 1 || typeof e.sha256 !== \"string\" || !SHA_RE.test(e.sha256) || typeof e.storage_ref !== \"string\" || typeof e.author !== \"string\" || typeof e.created_at !== \"string\" || !VERSION_STATUSES.includes(e.status) || typeof e.request_sha256 !== \"string\") fail(\"manifest_corrupt\", id + \" : version \" + (i + 1));\n if (e.status === \"authoritative\") authoritative += 1;\n });\n if (authoritative > 1) fail(\"manifest_corrupt\", id + \" : plusieurs versions font foi\");\n return m;\n}\n// Reads the manifest and keeps its raw text: the fingerprint of that text is the optimistic-concurrency token.\nasync function loadManifest(id) {\n let raw = null;\n try { raw = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (raw === null) return {raw: null, manifest: null, sha: null};\n let parsed;\n try { parsed = JSON.parse(raw); } catch (e) { fail(\"manifest_corrupt\", id + \" : JSON illisible\"); }\n try { rejectUnsafeKeys(parsed, \"manifeste\"); } catch (e) { fail(\"manifest_corrupt\", id + \" : \" + String(e.message).slice(0, 120)); }\n return {raw, manifest: checkManifest(parsed, id), sha: await manifestSha(raw)};\n}\n// Storage has no conditional write (no compare-and-swap): the manifest is read again just before the write and the write is\n// abandoned when its text changed since the first read. A first manifest is written without overwrite. The window between the\n// second read and the write is small, not null: one writer at a time per document.\nasync function writeManifest(id, manifest, expectedRaw) {\n let fresh = null;\n try { fresh = await readText(manifestPath(id)); } catch (e) {\n if (!String(e && e.message).startsWith(\"storage_not_found\")) throw e;\n }\n if (fresh !== expectedRaw) fail(\"concurrent_update\", \"le manifeste de \" + id + \" a changé pendant l'opération ; rien n'a été écrit dans le manifeste\");\n const body = JSON.stringify(manifest, null, 2) + \"\\n\";\n try { await callTool(\"write_file\", {path: manifestPath(id), content: body, overwrite: expectedRaw !== null}); } catch (e) {\n if (expectedRaw === null) fail(\"concurrent_update\", \"le manifeste de \" + id + \" vient d'être créé par un autre acteur\");\n throw e;\n }\n return sha256Hex(new TextEncoder().encode(body));\n}\n// Structural check of the ZIP package, without a library: end-of-central-directory record, every central directory entry\n// and its local header must be readable, and the package must hold [Content_Types].xml and word/document.xml. Entry\n// contents are not inflated here; the comparison engine does the full parse on every version after the first.\nfunction docxProblem(bytes) {\n const n = bytes.length;\n if (n < 22) return \"fichier trop court pour un paquet ZIP\";\n const dv = new DataView(bytes.buffer, bytes.byteOffset, n);\n let eocd = -1;\n for (let i = n - 22; i >= Math.max(0, n - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }\n if (eocd < 0) return \"fin d'archive ZIP introuvable\";\n const count = dv.getUint16(eocd + 10, true), size = dv.getUint32(eocd + 12, true), offset = dv.getUint32(eocd + 16, true);\n if (count === 0 || count === 0xffff || offset + size > eocd) return \"répertoire central ZIP invalide\";\n const names = new Set();\n let at = offset;\n for (let k = 0; k < count; k++) {\n if (at + 46 > eocd || dv.getUint32(at, true) !== 0x02014b50) return \"entrée ZIP illisible\";\n const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true), local = dv.getUint32(at + 42, true);\n if (at + 46 + nameLen > eocd) return \"nom d'entrée ZIP illisible\";\n if (local + 30 > offset || dv.getUint32(local, true) !== 0x04034b50) return \"en-tête local ZIP illisible\";\n names.add(new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen)));\n at += 46 + nameLen + extraLen + commentLen;\n }\n if (!names.has(\"[Content_Types].xml\") || !names.has(\"word/document.xml\")) return \"ce n'est pas un DOCX ([Content_Types].xml ou word/document.xml absent)\";\n return \"\";\n}\nasync function readDocx(path, missingCode) {\n let encoded;\n try { encoded = (await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"); } catch (e) {\n if (missingCode && String(e && e.message).startsWith(\"storage_not_found\")) fail(missingCode, path);\n throw e;\n }\n let bytes;\n try { bytes = b64ToBytes(encoded); } catch (e) { fail(\"docx_invalid\", path + \" : contenu non lisible\"); }\n if (bytes.length > MAX_DOCX_BYTES) fail(\"docx_too_large\", path + \" : 20 Mio au plus\");\n const why = docxProblem(bytes);\n if (why) fail(\"docx_invalid\", path + \" : \" + why);\n return {b64: encoded, bytes: bytes.length, sha: await sha256Hex(bytes)};\n}\n// Real validation by the document engine (office_inspect_v1): the structural check above is only a fast first filter. An error,\n// a refusal or an answer without a structure means the file is not a readable DOCX.\nasync function inspectDocx(file, label) {\n let raw;\n try { raw = await callTool(\"office_inspect_v1\", {format: \"docx\", file: {content_base64: file.b64}}); } catch (e) { fail(\"docx_invalid\", label + \" : \" + String(e && e.message).slice(0, 200)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"docx_invalid\", label + \" : \" + res.error + (res.message ? \" : \" + String(res.message).slice(0, 200) : \"\"));\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.structure) || !Number.isInteger(res.structure.blocks)) fail(\"docx_invalid\", label + \" : le moteur n'a pas pu lire le document\");\n}\n// The version a manifest entry points at must still be the bytes it fingerprinted.\nasync function readVersionFile(entry, withEngine) {\n const f = await readDocx(entry.storage_ref, \"version_integrity_failed\");\n if (f.sha !== entry.sha256) fail(\"version_integrity_failed\", \"v\" + entry.version + \" : l'empreinte du fichier ne correspond plus au manifeste\");\n if (withEngine) await inspectDocx(f, entry.storage_ref);\n return f;\n}\n// File names carry the content: the same name can only ever hold the same bytes, so a retry may overwrite it safely.\nasync function storeBytes(path, b64, expectedSha) {\n await callTool(\"write_file\", {path, content: b64, encoding: \"base64\", overwrite: true});\n let back;\n try { back = await sha256Hex(b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\"))); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n if (back !== expectedSha) fail(\"version_integrity_failed\", path + \" : empreinte relue différente de celle écrite\");\n}\nfunction countOf(v, name) { if (!Number.isInteger(v) || v < 0) fail(\"compare_invalid\", \"décompte \" + name + \" invalide\"); return v; }\nasync function compareVersions(prev, next, author, n) {\n let raw;\n try { raw = await callTool(\"office_compare_v1\", {before: {content_base64: prev.b64}, after: {content_base64: next.b64}, author, filename: \"redline-v\" + n + \".docx\"}); } catch (e) { fail(\"compare_failed\", String(e && e.message).slice(0, 300)); }\n const res = unwrap(raw);\n if (isObject(res) && res.error) fail(\"compare_failed\", res.error + (res.message ? \" : \" + res.message : \"\"));\n rejectUnsafeKeys(res, \"réponse office\");\n if (!isObject(res) || res.status !== \"ok\" || !isObject(res.file) || !isObject(res.changes)) fail(\"compare_invalid\", \"réponse inattendue de office_compare_v1\");\n const changes = {insertions: countOf(res.changes.insertions, \"insertions\"), deletions: countOf(res.changes.deletions, \"deletions\"),\n changed_paragraphs: res.changes.changed_paragraphs === undefined || res.changes.changed_paragraphs === null ? null : countOf(res.changes.changed_paragraphs, \"changed_paragraphs\")};\n return {file: res.file, changes};\n}\n// The redline is stored from the buffer reference when the tool gives one, else from base64; its fingerprint is checked.\nasync function storeRedline(dir, n, short, f) {\n let b64, sha = typeof f.sha256 === \"string\" ? f.sha256.toLowerCase() : \"\";\n const path = dir + \"/v\" + n + \"-redline-\" + short + \".docx\";\n if (f.ref !== undefined && f.ref !== null && f.ref !== \"\") {\n await callTool(\"write_file\", {path, buffer_ref: f.ref, overwrite: true});\n let stored;\n try { stored = b64ToBytes((await readText(path, {encoding: \"base64\"})).replace(/\\s+/g, \"\")); } catch (e) { fail(\"version_integrity_failed\", path + \" : relecture impossible\"); }\n const actual = await sha256Hex(stored);\n if (sha && sha !== actual) fail(\"version_integrity_failed\", path + \" : empreinte différente de celle annoncée\");\n return {path, sha256: actual};\n }\n if (typeof f.content_base64 !== \"string\") fail(\"compare_invalid\", \"le comparateur n'a rendu ni référence ni contenu\");\n b64 = f.content_base64.replace(/\\s+/g, \"\");\n let bytes;\n try { bytes = b64ToBytes(b64); } catch (e) { fail(\"compare_invalid\", \"contenu base64 illisible\"); }\n const computed = await sha256Hex(bytes);\n if (sha && sha !== computed) fail(\"version_integrity_failed\", path + \" : empreinte annoncée différente du contenu\");\n await storeBytes(path, b64, computed);\n return {path, sha256: computed};\n}\nfunction versionSummary(doc, entry, manifest, msha, replayed) {\n const auth = authoritativeOf(manifest);\n return {doc_id: doc, version: entry.version, status: entry.status, supersedes: entry.supersedes === undefined ? null : entry.supersedes, sha256: entry.sha256, storage_ref: entry.storage_ref,\n redline_ref: entry.redline_ref === undefined ? null : entry.redline_ref, changes: entry.changes === undefined ? null : entry.changes,\n authoritative_version: auth ? auth.version : null, versions: manifest.versions.length, manifest_ref: manifestPath(doc), manifest_sha256: msha, replayed};\n}\n\nconst input = {{ json . }};\nrejectUnsafeKeys(input, \"demande\");\nonlyInput(input, [\"doc_id\", \"source_path\", \"author\", \"base_version\", \"base_manifest_sha256\"]);\nconst id = docIdOf(input.doc_id);\nconst source = sourcePathOf(input.source_path);\nconst author = text(input.author, \"author\", 200, true);\nconst baseVersion = optionalInteger(input.base_version, \"base_version\", 0);\nconst baseSha = optionalDigest(input.base_manifest_sha256, \"base_manifest_sha256\");\nif (source.startsWith(versionsDir(id) + \"/\")) fail(\"source_invalid\", \"la source ne peut pas être un fichier du dossier des versions\");\nconst rec = await loadRecord(id);\nif (rec.status === \"cancelled\") fail(\"document_cancelled\", \"un document annulé n'accepte plus de version\");\nconst {raw, manifest, sha: msha} = await loadManifest(id);\nconst latest = lastVersion(manifest);\nconst latestN = latest ? latest.version : 0;\nconst file = await readDocx(source, \"source_not_found\");\n// The request fingerprint covers what the caller decided (document, bytes, author), never the base: a replay of ANY earlier\n// write is recognised whatever the manifest became since, and writes nothing.\nconst request = await fingerprint({action: \"new-version\", doc_id: id, sha256: file.sha, author});\nconst replayed = manifest ? manifest.versions.find((e) => e.request_sha256 === request && (baseVersion === undefined || baseVersion === e.version - 1)) : undefined;\nif (replayed) return versionSummary(id, replayed, manifest, msha, true);\nif (baseVersion !== undefined && baseVersion !== latestN) fail(\"base_version_conflict\", \"la dernière version est \" + latestN + \", la demande part de \" + baseVersion + \" ; rien n'a été écrit\");\nif (baseSha !== undefined && baseSha !== msha) fail(\"base_version_conflict\", \"le manifeste a changé depuis sa lecture (empreinte \" + (msha || \"absente\") + \") ; rien n'a été écrit\");\nif (latest && latest.sha256 === file.sha) fail(\"version_unchanged\", \"le fichier est identique à la version \" + latest.version);\n// The first version never goes through office_compare_v1: the engine reads it here, before any write.\nif (!latest) await inspectDocx(file, source);\nconst n = latestN + 1;\nconst dir = versionsDir(id);\nconst short = file.sha.slice(0, 12);\nlet redline = null, changes = null;\nif (latest) {\n const prev = await readVersionFile(latest);\n const cmp = await compareVersions(prev, file, author, n);\n redline = await storeRedline(dir, n, short, cmp.file);\n changes = cmp.changes;\n}\nconst path = dir + \"/v\" + n + \"-\" + short + \".docx\";\nawait storeBytes(path, file.b64, file.sha);\nconst entry = {version: n, sha256: file.sha, bytes: file.bytes, storage_ref: path, redline_ref: redline ? redline.path : null, redline_sha256: redline ? redline.sha256 : null,\n changes, author, created_at: nowIso(), status: \"draft\", supersedes: null, base_version: latest ? latest.version : null, request_sha256: request};\nconst next = {schema: MANIFEST_SCHEMA, doc_id: id, versions: (manifest ? manifest.versions : []).concat([entry]),\n history: (manifest ? manifest.history : []).concat([{at: entry.created_at, action: \"version_added\", version: n, author, note: latest ? \"comparée à la version \" + latest.version : \"première version\"}])};\nconst written = await writeManifest(id, next, raw);\nreturn versionSummary(id, entry, next, written, false);\n", "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/document-studio/module.yaml b/document-studio/module.yaml index 107509d..dbdfee2 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.2.0", + "version": "0.3.0", "provides": { "actions": [ { @@ -54,6 +54,12 @@ "workflow_id": "document-studio-profile-save", "workflow_version": "1" }, + { + "key": "document-share", + "name": "Share an issued document", + "workflow_id": "document-share", + "workflow_version": "1" + }, { "key": "document-studio-new-version", "name": "Add a DOCX version", @@ -85,6 +91,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 ea8c8a8..65798f2 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -1205,9 +1205,9 @@ }, { "key": "document-studio", - "version": "0.2.0", + "version": "0.3.0", "manifest": "document-studio/module.yaml", - "workflows": 13, + "workflows": 15, "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", @@ -1236,24 +1238,52 @@ "document-studio/agents/main/miniapps/document-studio-review.json" ], "sha256": { - "document-studio/module.yaml": "2e09f02654084161cdea77ebbdeb479e7da92034c5939b63cfb73402747cdecb", - "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-mark-authoritative.json": "4077fc003cd00ddee422e776e315515b2deaa1b271846f73bc26b3568beee472", - "document-studio/agents/main/workflows/document-studio-new-version.json": "eff7d8a8f52e1bea1a4282397310b093714e3e6c8f6455ce62c73411cc52fcc5", + "document-studio/module.yaml": "f31b391b04ecf28700efb19584a020a2e72ddcb5c7ade5c5b6f6f3113f4562db", + "document-studio/agents/main/workflows/document-read.json": "732f3f29d3ba2a0b8d11b70f3ec26f34c08e3f80f0106156f9357936e1db333a", + "document-studio/agents/main/workflows/document-share.json": "f7755cb4f6049b97e8ca9b762929e5b51fd8b98dc8c2d8ec7dec9588449acf8d", + "document-studio/agents/main/workflows/document-studio-cancel.json": "a23e2f969ff387c63dd28614bb491cda5aaef9837c08f395e75bba3667ccd973", + "document-studio/agents/main/workflows/document-studio-draft.json": "c6b0593f2ad8db5ecab9f17fa47019e94054b8e66c917e0bac6447695141454d", + "document-studio/agents/main/workflows/document-studio-export.json": "231e46fecd19be8aa951b7e4f5862a7cec2b8edf79ee65ba001038150ac37dd4", + "document-studio/agents/main/workflows/document-studio-finalize.json": "c97ae082c17494abb2106cf70ecc68cb4d597da4015ed7eae85f314b640891fe", + "document-studio/agents/main/workflows/document-studio-list.json": "7319e6be4646a32166957ac122eb0bc8e9fc99ad2bd569d1345b373f344c9722", + "document-studio/agents/main/workflows/document-studio-mark-authoritative.json": "f5c484e13b1bc45b15c3106f7c6502e4ba168af9c1c283548171a02f12c25884", + "document-studio/agents/main/workflows/document-studio-new-version.json": "804c6e1f71c235e2d03a262d9da34cff1192a9cc85275b8d5cbafccd69492b41", "document-studio/agents/main/workflows/document-studio-plan.json": "47a1a75463b75cdfc287a56f80a23f3faef513ae46b6b980a0851579089eb99b", - "document-studio/agents/main/workflows/document-studio-profile-save.json": "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" } }, "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": "9b7bfbe9723c6ed11b2af8a504f5f5e0dbe27c1fd636f87ee65e552b0f229b37" + } + ] + }, + "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": "659157ddb8688061a808d19c50ef5dfc096d7cf89d0a08518f313f5dfdd2a79c" + } + ] + }, "document-studio/agents/main/workflows/document-studio-cancel.json": { "workflow_id": "document-studio-cancel", "actions": [ @@ -1263,7 +1293,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "f1917d69e3f6037738be1d01b1596f493e100e8531724aa9c3f812277e34441c" + "code_sha256": "69ce0757ceafdd4371bb9fd30155b0a1b9d217b86b28b0c3017e40f50341a261" } ] }, @@ -1289,7 +1319,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "84cd3cdb86438410be7feb0f37a661dbbee58c1009a1de60fad4aa46cea6253e" + "code_sha256": "8b7eeb51061f9da9222cf5b187679b58ee8f8c89640ef0f04985b6a141f8f513" } ] }, @@ -1302,7 +1332,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "7afe7e008045c2dbd7a94dd38795eef6b03f53e9fe22b24714523dbacf542792" + "code_sha256": "165025885224b0ee3c3c74ee87ece42d292eb524d694ac46156db2661e2f2885" } ] }, @@ -1315,7 +1345,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "0b7fb78a4eaf763a38684b03c62e39340c51c5244295f1eb00c43d5f934e9117" + "code_sha256": "24cfa7e9ccac2ea0cd7437d08268cfc71776a65cbfd30372d48dce2d44237695" } ] }, @@ -1328,7 +1358,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "9ea76c328efb36d97b4cda1c4cff6f290a56ec5950564155f3b549fdb955a2c4" + "code_sha256": "2d14a0e71bb6ad4807f9361fd379d4531025e37a027a3794463417739a2675da" } ] }, @@ -1341,7 +1371,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "20b53ce431029441722b8867fb76889fd3512c5c6f64919e6cfa9ef147ee4f1f" + "code_sha256": "e3b507ae9d6b3c93110843d486d946b3c60a57d3946d555b4913ad45ce0421d4" } ] }, @@ -1354,7 +1384,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "d5f16778a62ce2a1e47972ea74efdb7e171469b25425714d7d5336dc801eafa5" + "code_sha256": "f7962e164ada6d946cfcacaecdc0c9faf5a644f40d9dd59d838c8ba8eadafb75" } ] }, @@ -1393,7 +1423,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "d7534ddd9f68d4a12d292c697b8696f6b40d21d4140d89f8a010c589ae9f90c8" + "code_sha256": "6ce377baeb157712a931eed1841ed49abd80e35ec555f499e6218ef56852cf42" } ] }, @@ -1406,7 +1436,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "7acdf05706263ae55bb475399eeccd796b6965f15b32c3c54239d24741467edd" + "code_sha256": "28ff2644edbfd9ae06fe59b342b28f594bd93c8ede7bf0121fee143c2dba2dd1" } ] }, @@ -1419,7 +1449,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "00664e1d1bc38d410cfe9da07f7a4149ad8b8d22db1b92d744c017bc9521f6b7" + "code_sha256": "24847650286455761816d9e591374331e7bc1b07f947bb46da2a40ed29e94107" } ] }, @@ -1432,7 +1462,7 @@ "type": "code_execution", "runtime": "deno", "runtime_source": "contract default", - "code_sha256": "c9790097344a4efb7d26f1908662ed92d374fbffa30d1b877864adb75f717175" + "code_sha256": "df64ef6b951bff53cf9d112beed8fa48a90505609d30769d0ed9438beea8c4be" } ] }, @@ -1500,6 +1530,12 @@ "workflow_id": "document-studio-profile-save", "workflow_version": "1" }, + { + "key": "document-share", + "name": "Share an issued document", + "workflow_id": "document-share", + "workflow_version": "1" + }, { "key": "document-studio-new-version", "name": "Add a DOCX version", @@ -1531,6 +1567,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 f9c720c..54e549c 100644 --- a/modules.json +++ b/modules.json @@ -31,9 +31,9 @@ }, { "key": "document-studio", - "version": "0.2.0", + "version": "0.3.0", "manifest": "document-studio/module.yaml", - "workflows": 13, + "workflows": 15, "miniapps": 1 }, { diff --git a/templates/company-in-a-box/compose.py b/templates/company-in-a-box/compose.py index eeb2d1e..c5c00ea 100755 --- a/templates/company-in-a-box/compose.py +++ b/templates/company-in-a-box/compose.py @@ -17,6 +17,24 @@ 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.3.0", + "role": "cib_documents", + # document-read carries no required_role, like contenu-read: any member of the Application may call it + # and the ACL of each shared record decides what it returns. None = no role. + "gates": {"document-studio-profile-save": "cib_admin", "document-read": None}, + }, +} +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 +103,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 +120,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 +152,23 @@ 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 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 = [] + 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" + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( @@ -148,6 +183,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 +201,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 +232,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 +276,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 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") + 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..36d0402 --- /dev/null +++ b/templates/company-in-a-box/tests/documents.json @@ -0,0 +1,43 @@ +{ + "$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" + } + ] + } + ] +} diff --git a/templates/company-in-a-box/tests/test_compose.py b/templates/company-in-a-box/tests/test_compose.py index e95a5d2..9d14553 100644 --- a/templates/company-in-a-box/tests/test_compose.py +++ b/templates/company-in-a-box/tests/test_compose.py @@ -120,6 +120,60 @@ 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.get("required_role") for w in draft["public_surface"]["workflows"]} + self.assertEqual(len(roles), 15) + self.assertEqual(roles["document-studio-profile-save"], "cib_admin") + 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") + (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 2abb084..84df772 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.2.0' +VERSION = '0.3.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' COMPARE_TOOL = 'office_compare_v1' INSPECT_TOOL = 'office_inspect_v1' VERSION_TOOLS = STORAGE_TOOLS + [COMPARE_TOOL, INSPECT_TOOL] @@ -377,17 +380,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 +459,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(); } @@ -802,6 +827,122 @@ 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." : (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""" +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"); + 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, 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); +if (!isObject(item.data)) fail("broker_record_data_invalid"); +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; +""" + + def code(*parts): body = ''.join(parts) assert '{{' not in body.replace('{{ json . }}', ''), 'a double-brace sequence in the JavaScript' @@ -816,7 +957,7 @@ def node(action_id, source, output_key, tools=None): return data -def lib(*, templates=None, io=False, profile=False, render=False, numbering=False, versions=False): +def lib(*, templates=None, io=False, profile=False, render=False, numbering=False, load_profile=False, versions=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') @@ -827,6 +968,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: @@ -968,7 +1111,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''' @@ -1035,7 +1178,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''' @@ -1155,8 +1298,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', @@ -1170,8 +1313,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', @@ -1251,6 +1394,42 @@ 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([], 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 }}', '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() @@ -1306,9 +1485,10 @@ def ref(key, name): 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-share', 'Share an issued document'), ref('document-studio-new-version', 'Add a DOCX version'), ref('document-studio-mark-authoritative', 'Mark a version authoritative')], '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 9db235d..a1abd20 100644 --- a/tooling/document-studio/tests/test_module.py +++ b/tooling/document-studio/tests/test_module.py @@ -66,6 +66,44 @@ 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-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]; + 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 === "office_inspect_v1") { const data = Buffer.from(args.file.content_base64, "base64"); if (opts.inspect_error) throw new Error(opts.inspect_error); @@ -179,7 +217,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), 13) + self.assertEqual(len(refs), 15) 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)) @@ -891,6 +929,227 @@ 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', ['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']) + 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')) + + 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) + + 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']]) + + 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)) | {} + + 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') + DIR = '/document-studio/docs/devis-test/versions'