@konneal/engine 0.2.89 → 0.2.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  handleAsk
3
- } from "./chunk-NGPUMFYQ.js";
4
- import "./chunk-HVT2ZTWW.js";
3
+ } from "./chunk-ZIDDK32O.js";
4
+ import "./chunk-JHATKAWW.js";
5
5
  import "./chunk-3BL223VD.js";
6
6
  import "./chunk-LOBYXEVD.js";
7
7
  import "./chunk-SPKPH54J.js";
@@ -0,0 +1,521 @@
1
+ import {
2
+ embed,
3
+ hasLane,
4
+ portIndex,
5
+ portModelRunner
6
+ } from "./chunk-LOBYXEVD.js";
7
+ import {
8
+ standardKeysFrom
9
+ } from "./chunk-LVZTWUVJ.js";
10
+ import {
11
+ THRESHOLDS
12
+ } from "./chunk-2PCUAJJO.js";
13
+ import {
14
+ P
15
+ } from "./chunk-3FYJM7LH.js";
16
+
17
+ // workers/worker_public/src/refs.ts
18
+ var REF = /\[\[(u:[A-Za-z0-9_-]+)\]\]/g;
19
+ function availableUnitIds(hits) {
20
+ const ids = /* @__PURE__ */ new Set();
21
+ for (const h of hits) {
22
+ const u = h.metadata?.unit_id;
23
+ if (u) ids.add(u);
24
+ }
25
+ return ids;
26
+ }
27
+ function parseRefs(text) {
28
+ return [...text.matchAll(REF)].map((m) => m[1]);
29
+ }
30
+ function sanitizeRefs(text, available) {
31
+ const dropped = [];
32
+ const out = text.replace(REF, (full, id) => {
33
+ if (available.has(id)) return full;
34
+ dropped.push(id);
35
+ return "";
36
+ });
37
+ return { text: out, dropped };
38
+ }
39
+ async function resolveBlocks(db, refs) {
40
+ if (!refs.length) return [];
41
+ const uniq = [...new Set(refs)].slice(0, 12);
42
+ const blocks = [];
43
+ for (let i = 0; i < uniq.length; i += 20) {
44
+ const batch = uniq.slice(i, i + 20);
45
+ const placeholders = batch.map((_, n) => `?${n + 1}`).join(",");
46
+ try {
47
+ const res = await db.prepare(`SELECT unit_id, type, docidentifier, edition, payload FROM unit_payloads WHERE unit_id IN (${placeholders})`).bind(...batch).all();
48
+ for (const r of res.results) {
49
+ let payload = {};
50
+ try {
51
+ payload = JSON.parse(String(r.payload));
52
+ } catch {
53
+ continue;
54
+ }
55
+ blocks.push({
56
+ unit_id: String(r.unit_id),
57
+ type: String(r.type),
58
+ docidentifier: String(r.docidentifier ?? ""),
59
+ edition: r.edition ? String(r.edition) : void 0,
60
+ payload
61
+ });
62
+ }
63
+ } catch (e) {
64
+ console.log("resolveBlocks failed:", String(e).slice(0, 150));
65
+ }
66
+ }
67
+ return blocks;
68
+ }
69
+ async function contractV2(db, answer, usedHits) {
70
+ const available = availableUnitIds(usedHits);
71
+ const { text, dropped } = sanitizeRefs(answer, available);
72
+ if (dropped.length) console.log("refs: dropped", dropped.length, "invalid (not in passages)");
73
+ const refs = parseRefs(text);
74
+ const blocks = await resolveBlocks(db, refs);
75
+ return { text, blocks, dropped };
76
+ }
77
+ function tableRetyped(text, availableTable) {
78
+ if (!availableTable) return false;
79
+ return /(^|\n)\s*\|[^\n]+\|\s*(\n\s*\|[-: |]+\|\s*)?(\n|$)/.test(text) && (text.match(/\|/g) ?? []).length >= 6;
80
+ }
81
+
82
+ // workers/worker_public/src/modelplane.ts
83
+ var NODE_RE = /(?:^|[\s("'`])\/(req|conf|term|constraint|characteristic|state-machine|dimension)\/([a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)?)(?=[\s)"'`,;:.]|$)/i;
84
+ function modelNodeRefIn(text) {
85
+ if (!text) return null;
86
+ const m = text.match(NODE_RE);
87
+ if (!m) return null;
88
+ const id = `/${m[1].toLowerCase()}/${m[2]}`;
89
+ return id.length <= 120 ? id : null;
90
+ }
91
+ function standardForDocNumber(docNumber) {
92
+ if (!docNumber) return null;
93
+ const models = P().sources?.models;
94
+ if (!models?.standards?.length || !models?.standard_prefix) return null;
95
+ return models.standards.includes(docNumber) ? `${models.standard_prefix}${docNumber}` : null;
96
+ }
97
+ function licensedEntryForPackage(packageId) {
98
+ if (!packageId) return null;
99
+ return (P().sources?.licensed ?? []).find((l) => l.package === packageId) ?? null;
100
+ }
101
+ function licensedEntryForDocNumber(docNumber) {
102
+ if (!docNumber) return null;
103
+ return (P().sources?.licensed ?? []).find((l) => String(l.doc_number ?? "") === docNumber) ?? null;
104
+ }
105
+ function licenseBoundaryNote(docNumber, standardKeys) {
106
+ const entry = licensedEntryForDocNumber(docNumber);
107
+ if (!entry || standardKeys && standardKeys.has(entry.key)) return void 0;
108
+ const pointer = P().prompts?.vars?.license_declare_pointer;
109
+ return `License boundary \u2014 the question is about ${licenseBoundaryName(entry)}, a licensed publication (entitlement key ${entry.key}). The caller's organization license does not cover its text, so no passage of it was retrieved and NONE of its procedural content (steps, parameters, severities, limits) may be stated, paraphrased or recalled from memory. You MAY answer at the citation level: name the standard and edition, and cite the invoking clause from the PUBLIC passages in context (the Recommendation's own applicability and normative references are public and stay answerable). Then say the organization's license does not cover the standard's text` + (pointer ? ` and point to the declare flow: ${pointer}.` : ".");
110
+ }
111
+ function licenseBoundaryName(entry) {
112
+ const id = entry.doc_number ? ` ${entry.doc_number}` : ` ${entry.package}`;
113
+ return `${entry.title ?? "standard"}${entry.edition ? ` (${entry.edition})` : ""} \u2014${id}`;
114
+ }
115
+ function licenseBoundaryRefusal(docNumber, standardKeys) {
116
+ const entry = licensedEntryForDocNumber(docNumber);
117
+ if (!entry || standardKeys && standardKeys.has(entry.key)) return void 0;
118
+ const pointer = P().prompts?.vars?.license_declare_pointer;
119
+ return `${licenseBoundaryName(entry)} is a licensed publication and your organization's license does not cover its text, so I can't quote or summarize its procedure. I can answer at the citation level \u2014 the standard's title and edition, and the clause your Recommendation invokes \u2014 and the public ${P().publisher.name} content in full.` + (pointer ? ` To unlock the full text, an org admin can declare the license under ${pointer}.` : "");
120
+ }
121
+ async function fetchNode(env, standard, nodeId) {
122
+ try {
123
+ const row = await env.DB.prepare(
124
+ "SELECT standard, node_id, kind, name, clause_doc, clause_ref, content FROM model_nodes WHERE standard = ?1 AND node_id = ?2"
125
+ ).bind(standard, nodeId).first();
126
+ if (!row) return null;
127
+ const content = JSON.parse(String(row.content));
128
+ const clause = row.clause_doc && row.clause_ref ? { doc: String(row.clause_doc), ref: String(row.clause_ref), urn: `${row.clause_doc}#clause-${row.clause_ref}` } : row.clause_doc ? { doc: String(row.clause_doc), ref: "", urn: String(row.clause_doc) } : null;
129
+ return {
130
+ standard: String(row.standard),
131
+ node_id: String(row.node_id),
132
+ kind: String(row.kind),
133
+ name: String(row.name ?? row.node_id),
134
+ clause,
135
+ content
136
+ };
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+ async function bindModelNode(env, opts) {
142
+ const nodeId = modelNodeRefIn(opts.label) ?? modelNodeRefIn(opts.query);
143
+ if (!nodeId) return null;
144
+ const gate = (node) => {
145
+ if (!node) return null;
146
+ const entry = licensedEntryForPackage(node.standard);
147
+ return entry && !(opts.standardKeys?.has(entry.key) ?? false) ? { ...node, gated: true, content: {} } : node;
148
+ };
149
+ if (opts.standard) return gate(await fetchNode(env, opts.standard, nodeId));
150
+ try {
151
+ const rows = await env.DB.prepare("SELECT standard FROM model_nodes WHERE node_id = ?1 LIMIT 2").bind(nodeId).all();
152
+ const standards = (rows?.results ?? []).map((r) => String(r.standard));
153
+ if (standards.length === 1) return gate(await fetchNode(env, standards[0], nodeId));
154
+ return null;
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+ function clip(s, n = 500) {
160
+ const t = String(s ?? "").trim();
161
+ return t.length <= n ? t : t.slice(0, n - 1).trimEnd() + " \u2026";
162
+ }
163
+ function applicabilityText(app) {
164
+ if (!app || typeof app !== "object") return "";
165
+ const parts = [];
166
+ for (const [dim, cond] of Object.entries(app)) {
167
+ if (Array.isArray(cond)) parts.push(`${dim.replace(/_/g, " ")}: ${cond.join(", ")}`);
168
+ else if (cond && typeof cond === "object" && Array.isArray(cond.values)) {
169
+ parts.push(`${dim.replace(/_/g, " ")} (${cond.match ?? "any"}): ${cond.values.join(", ")}`);
170
+ }
171
+ }
172
+ return parts.join("; ");
173
+ }
174
+ function modelGroundingBlock(node) {
175
+ const c = node.content ?? {};
176
+ const lines = [];
177
+ lines.push(
178
+ P().prompts.vars.model_grounding_intro ?? "Model grounding \u2014 the model plane's own statement:"
179
+ );
180
+ lines.push(`Node: ${node.node_id} (${node.kind.replace(/_/g, " ")}) \u2014 ${node.name} [${node.standard}]`);
181
+ if (node.clause) lines.push(`Provenance: ${node.clause.urn}`);
182
+ if (c.statement) lines.push(`Statement: ${clip(c.statement)}`);
183
+ if (c.definition) lines.push(`Definition: ${clip(c.definition)}`);
184
+ if (c.purpose) lines.push(`Purpose: ${clip(c.purpose)}`);
185
+ const limit = c.limit ?? {};
186
+ if (limit.expression) lines.push(`Machine limit (the constraint the platform's verdict engine evaluates \u2014 quote it verbatim): ${limit.expression}`);
187
+ if (limit.accepts?.verdict) lines.push(`Machine limit: ${limit.accepts.verdict} ${limit.accepts.op} ${limit.accepts.limit} (the canonical acceptance chain)`);
188
+ if (c.check) lines.push(`Machine check: ${c.check}`);
189
+ if (c.derive) lines.push(`Derivation: ${c.derive}${Array.isArray(c.inputs) ? ` (inputs: ${c.inputs.join(", ")})` : ""}`);
190
+ const app = applicabilityText(c.applicability);
191
+ const scopeApp = applicabilityText(c.scope_applicability);
192
+ if (app || scopeApp) lines.push(`Applicability: ${[scopeApp, app].filter(Boolean).join("; ")}`);
193
+ if (Array.isArray(c.binds_to) && c.binds_to.length) lines.push(`Binds to: ${c.binds_to.join(", ")}`);
194
+ if (Array.isArray(c.targets) && c.targets.length) lines.push(`Verifies requirements: ${c.targets.join(", ")}`);
195
+ if (Array.isArray(c.preconditions) && c.preconditions.length) {
196
+ const pcs = c.preconditions.map((p) => `${p.id}: ${clip(p.check ?? (p.state ? `state = ${p.state}` : ""), 120)}`).join("; ");
197
+ lines.push(`Run-validity preconditions (a violation voids the run \u2014 invalid, never a fail): ${pcs}`);
198
+ }
199
+ if (c.acceptance_criteria?.description) lines.push(`Acceptance: ${clip(c.acceptance_criteria.description, 300)}`);
200
+ if (c.violation_meaning) lines.push(`Violation meaning (verbatim): ${clip(c.violation_meaning, 300)} \u2014 on violation: ${c.on_violation ?? "invalid"}`);
201
+ if (Array.isArray(c.values) && c.values.length) {
202
+ lines.push(`Values: ${c.values.map((v) => `${v.id}${v.implies?.length ? ` (implies ${v.implies.join(", ")})` : ""}`).join("; ")}`);
203
+ }
204
+ if (c.source_discrepancy) {
205
+ const sd = c.source_discrepancy;
206
+ lines.push(
207
+ `DECLARED SOURCE DISCREPANCY \u2014 the model and the text disagree; you MUST surface this and cite both: ${clip(sd.summary, 300)} Sources: ${(sd.sources ?? []).join(" and ")}. The model ${sd.resolution === "follows_clause_x" ? "follows one side" : "records the conflict without resolving it"}: ${clip(sd.rationale, 300)}`
208
+ );
209
+ }
210
+ lines.push(
211
+ "Rules for this answer: the machine facts (the constraint, the applicability, the acceptance, the provenance) come from THIS node \u2014 quote the machine limit verbatim, never invent one the node does not carry. If this model content and a prose passage disagree \u2014 including a passage from a different edition \u2014 say so explicitly and cite both (this node and the prose clause)."
212
+ );
213
+ return lines.join("\n");
214
+ }
215
+ function modelCitation(node) {
216
+ return {
217
+ doc_id: `model:${node.standard}`,
218
+ docidentifier: `${P().publisher.name} SMART model (${(() => {
219
+ const prefix = P().sources?.models?.standard_prefix ?? "";
220
+ const letter = prefix.replace(/^.*-/, "").toUpperCase();
221
+ return String(node.standard).replace(new RegExp(`^${prefix}`, "i"), `${letter} `);
222
+ })()})`,
223
+ edition: "",
224
+ language: "en",
225
+ clause_anchor: node.clause?.ref || "model",
226
+ clause_title: `${node.kind.replace(/_/g, " ")} \u2014 ${node.name} (${node.node_id})`,
227
+ status: "in-force",
228
+ corpus: "smart-model",
229
+ quality: "verified",
230
+ url: void 0,
231
+ snippet: `${node.node_id}${node.clause ? ` \xB7 ${node.clause.urn}` : ""}${node.content?.statement ? ` \u2014 ${clip(node.content.statement, 240)}` : ""}`,
232
+ score: 1
233
+ };
234
+ }
235
+ function modelEcho(node) {
236
+ return {
237
+ node_id: node.node_id.slice(0, 120),
238
+ kind: node.kind.slice(0, 40),
239
+ standard: node.standard.slice(0, 40),
240
+ ...node.clause?.urn ? { clause: node.clause.urn.slice(0, 120) } : {}
241
+ };
242
+ }
243
+
244
+ // workers/worker_public/src/tools-content.ts
245
+ var slug = (docidentifier) => docidentifier.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
246
+ var unitsGet = {
247
+ name: "units.get",
248
+ description: "Fetch typed Recommendation content \u2014 a table, formula or figure as structured data (columns, rows, MathML, caption), by its unit id. The machine-consumable form of a Recommendation's content, for computing with rather than reading.",
249
+ params: [{ key: "unit_id", required: true, description: "the unit id exactly as an answer's [[u:\u2026]] reference spells it" }],
250
+ audiences: ["mcp"],
251
+ handler: async (env, args) => {
252
+ const unit_id = String(args?.unit_id ?? "").trim().replace(/^\[?\[?u:/, "u:").replace(/]?\]?$/, "");
253
+ if (!/^u:[\w.-]+$/.test(unit_id)) return null;
254
+ const blocks = await resolveBlocks(env.DB, [unit_id]);
255
+ if (!blocks.length) {
256
+ return { name: "units.get", query: unit_id, output: `No typed unit "${unit_id}" exists in the indexed payloads. State this plainly.` };
257
+ }
258
+ return {
259
+ name: "units.get",
260
+ query: unit_id,
261
+ output: JSON.stringify(
262
+ blocks.map((b) => ({ unit_id: b.unit_id, type: b.type, docidentifier: b.docidentifier, payload: b.payload }))
263
+ )
264
+ };
265
+ }
266
+ };
267
+ var graphCites = {
268
+ name: "graph.cites",
269
+ description: "The bibliography edges: what a publication's own bibliography actually cites, extracted from its indexed bibliography sections. Returns the cited works' labels for a document (optionally scoped to an edition).",
270
+ params: [
271
+ { key: "doc", required: true, description: "the publication identifier, e.g. R 60-1:2021" },
272
+ { key: "edition", required: false, description: "an edition year to scope, e.g. 2021" }
273
+ ],
274
+ audiences: ["mcp"],
275
+ handler: async (env, args) => {
276
+ const doc = String(args?.doc ?? "").trim();
277
+ if (doc.length < 3) return null;
278
+ const edition = args?.edition ? String(args.edition).trim() : null;
279
+ const pat = `%${doc.replace(/[:\s]+/g, "%")}%${edition ? edition : ""}%`;
280
+ try {
281
+ const rows = await env.DB.prepare(
282
+ "SELECT DISTINCT n.label AS label FROM graph_edges e JOIN documents d ON e.src = d.canonical_id JOIN graph_nodes n ON e.dst = n.id WHERE d.docidentifier LIKE ?1 AND e.kind = 'cites' ORDER BY label LIMIT 60"
283
+ ).bind(pat).all();
284
+ const labels = (rows.results ?? []).map((r) => r.label).filter(Boolean);
285
+ return {
286
+ name: "graph.cites",
287
+ query: `${doc}${edition ? ` (${edition})` : ""}`,
288
+ output: labels.length ? `The publication's bibliography cites:
289
+ ${labels.map((l) => `- ${l}`).join("\n")}` : `No bibliography citations are indexed for "${doc}"${edition ? ` (${edition})` : ""}. State this plainly.`
290
+ };
291
+ } catch {
292
+ return null;
293
+ }
294
+ }
295
+ };
296
+ var docsSection = {
297
+ name: "docs.section",
298
+ description: "Fetch one clause of a publication's rendered document \u2014 its text and its permanent deep-link URL \u2014 for agents that need the human-formatted passage with its anchor.",
299
+ params: [
300
+ { key: "doc", required: true, description: "the publication identifier, e.g. R 60-1:2021" },
301
+ { key: "clause", required: true, description: "the clause anchor, e.g. 5.1.1 or annex-b" }
302
+ ],
303
+ audiences: ["mcp"],
304
+ handler: async (env, args) => {
305
+ const doc = String(args?.doc ?? "").trim();
306
+ const clause = String(args?.clause ?? "").trim();
307
+ if (doc.length < 3 || !clause) return null;
308
+ try {
309
+ const rows = await env.DB.prepare(
310
+ "SELECT docidentifier, clause_anchor, clause_title, text FROM chunks WHERE docidentifier LIKE ?1 AND REPLACE(clause_anchor, ' ', '') = ?2 LIMIT 1"
311
+ ).bind(`%${doc.replace(/[:\s]+/g, "%")}%`, clause).all();
312
+ const r = (rows.results ?? [])[0];
313
+ if (!r) {
314
+ return { name: "docs.section", query: `${doc} \xA7${clause}`, output: `No clause "${clause}" is indexed for "${doc}". State this plainly.` };
315
+ }
316
+ const url = `https://www.ommisa.org/docs/${slug(r.docidentifier)}.html#${r.clause_anchor}`;
317
+ return {
318
+ name: "docs.section",
319
+ query: `${r.docidentifier} \xA7${r.clause_anchor}`,
320
+ output: JSON.stringify({ docidentifier: r.docidentifier, clause: r.clause_anchor, title: r.clause_title, url, text: (r.text ?? "").slice(0, 4e3) })
321
+ };
322
+ } catch {
323
+ return null;
324
+ }
325
+ }
326
+ };
327
+ var documentsFamily = {
328
+ name: "documents.family",
329
+ description: "Look up the publication registry for a family: every edition with its derived status (in-force/superseded), which edition is ACTIVE (terminal of the successor chain), and supersession links. Use for current/latest-edition and edition-history questions.",
330
+ params: [{ key: "family", required: true, description: "the family key, e.g. R-60 (series letter and number)" }],
331
+ audiences: ["mcp"],
332
+ handler: async (env, args) => {
333
+ const family = String(args?.family ?? "").trim().toUpperCase();
334
+ if (!/^[A-Z]-\d{1,3}$/.test(family)) return null;
335
+ try {
336
+ const rows = await env.DB.prepare(
337
+ "SELECT d.docidentifier, d.derived_status, d.active, s.docidentifier AS succ FROM documents d LEFT JOIN documents s ON d.superseded_by = s.canonical_id WHERE d.family = ?1 ORDER BY d.part, d.edition"
338
+ ).bind(family).all();
339
+ const lines = (rows.results ?? []).map(
340
+ (r) => `${r.docidentifier} \u2014 ${r.derived_status}${r.active ? " [ACTIVE]" : ""}${r.succ ? ` \u2192 superseded by ${r.succ}` : ""}`
341
+ );
342
+ if (!lines.length) {
343
+ return { name: "documents.family", query: family, output: `No editions are registered for the family ${family}. State this plainly.` };
344
+ }
345
+ return { name: "documents.family", query: family, output: lines.join("\n") };
346
+ } catch {
347
+ return null;
348
+ }
349
+ }
350
+ };
351
+ var licensedSection = {
352
+ name: "licensed.section",
353
+ description: "Fetch one clause of a licensed standard's typed model content \u2014 requirements, condition sets and parameters as structured data \u2014 behind the caller's license entitlement keys. An unentitled caller receives the license boundary: the standard's title and edition and the declare flow, never its text.",
354
+ params: [
355
+ { key: "doc", required: true, description: "the standard's document number, e.g. 60068-2-30 or 61000-4-2" },
356
+ { key: "clause", required: true, description: "the clause number inside the standard, e.g. 5 or 9" },
357
+ { key: "licensed_standards", required: true, description: `the caller's license entitlement keys, e.g. ["std:iec-60068-2-30"] \u2014 validated against the licenses this deployment declares; keys it does not know drop` }
358
+ ],
359
+ audiences: ["mcp"],
360
+ handler: async (env, args) => {
361
+ const doc = String(args?.doc ?? "").trim();
362
+ const clause = String(args?.clause ?? "").trim();
363
+ if (doc.length < 3 || !clause) return null;
364
+ const docNumber = doc.replace(/^(?:ISO\/IEC|ISO|IEC)\s+/i, "").trim();
365
+ const entry = licensedEntryForDocNumber(docNumber);
366
+ if (!entry) {
367
+ return {
368
+ name: "licensed.section",
369
+ query: `${doc} \xA7${clause}`,
370
+ output: `"${doc}" is not among the licensed standards this deployment keys. For clauses of the public corpus use the docs.section tool instead. State this plainly.`
371
+ };
372
+ }
373
+ const keys = standardKeysFrom({ licensed_standards: args?.licensed_standards });
374
+ if (!keys.has(entry.key)) {
375
+ const refusal = licenseBoundaryRefusal(docNumber, keys);
376
+ return {
377
+ name: "licensed.section",
378
+ query: `${doc} \xA7${clause}`,
379
+ output: refusal ?? "License boundary \u2014 the caller's entitlement set does not cover this standard's text."
380
+ };
381
+ }
382
+ try {
383
+ const rows = await env.DB.prepare(
384
+ "SELECT node_id, kind, name, clause_ref, content FROM model_nodes WHERE standard = ?1 AND clause_ref = ?2 ORDER BY node_id LIMIT 20"
385
+ ).bind(entry.package, clause).all();
386
+ const nodes = rows.results ?? [];
387
+ if (!nodes.length) {
388
+ const c = await env.DB.prepare(
389
+ "SELECT DISTINCT clause_ref FROM model_nodes WHERE standard = ?1 ORDER BY clause_ref"
390
+ ).bind(entry.package).all();
391
+ const clauses = (c.results ?? []).map((r) => r.clause_ref).filter(Boolean).join(", ");
392
+ return {
393
+ name: "licensed.section",
394
+ query: `${doc} \xA7${clause}`,
395
+ output: `No typed nodes are indexed for ${doc} \xA7${clause}.${clauses ? ` The clauses with typed nodes: ${clauses}.` : ""} State this plainly.`
396
+ };
397
+ }
398
+ return {
399
+ name: "licensed.section",
400
+ query: `${doc} \xA7${clause}`,
401
+ output: JSON.stringify(
402
+ nodes.map((n) => {
403
+ let content = n.content;
404
+ try {
405
+ content = JSON.parse(n.content);
406
+ } catch {
407
+ }
408
+ return { node_id: n.node_id, kind: n.kind, name: n.name, clause: n.clause_ref, content };
409
+ })
410
+ )
411
+ };
412
+ } catch {
413
+ return null;
414
+ }
415
+ }
416
+ };
417
+ var glossaryLookup = {
418
+ name: "glossary.lookup",
419
+ description: "Look up a defined term in the terminology datasets \u2014 the concept's definition and its defining publication. Bind everyday words to the defined term before interpreting a question.",
420
+ params: [{ key: "term", required: true, description: "the term or everyday phrase to bind, e.g. creep or load cell" }],
421
+ audiences: ["mcp"],
422
+ handler: async (env, args) => {
423
+ const term = String(args?.term ?? "").trim();
424
+ if (term.length < 2) return null;
425
+ if (!hasLane(env, "glossary")) return null;
426
+ try {
427
+ const vec = await embed(portModelRunner(env), "", term);
428
+ const cands = await portIndex(env, "glossary").query({ vector: vec, topK: 5 });
429
+ const hits = cands.filter((m) => m.score >= THRESHOLDS.glossaryCosineFloor).map((m) => ({
430
+ term: String(m.metadata?.clause_title ?? "").trim(),
431
+ definition: String(m.metadata?.chunk_text ?? "").split(" \u2014 ").slice(1).join(" \u2014 ").slice(0, 400),
432
+ docidentifier: String(m.metadata?.docidentifier ?? "")
433
+ })).filter((x) => x.term && x.definition);
434
+ if (!hits.length) {
435
+ return { name: "glossary.lookup", query: term, output: `No defined term matches "${term}" in the terminology datasets. State this plainly.` };
436
+ }
437
+ const seen = /* @__PURE__ */ new Set();
438
+ const uniq = hits.filter((h) => {
439
+ const k = h.term.toLowerCase().replace(/[^a-z0-9 ]/g, "").replace(/labeler\b/g, "labeller").replace(/\s+/g, " ").trim();
440
+ if (seen.has(k)) return false;
441
+ seen.add(k);
442
+ return true;
443
+ }).slice(0, 3);
444
+ return {
445
+ name: "glossary.lookup",
446
+ query: term,
447
+ output: uniq.map((h) => `- ${h.term} (${h.docidentifier}): ${h.definition}`).join("\n")
448
+ };
449
+ } catch {
450
+ return null;
451
+ }
452
+ }
453
+ };
454
+
455
+ // workers/worker_public/src/tools.ts
456
+ function parseToolCall(text) {
457
+ const m = /^TOOL\s+([a-z_.]+)\s*(\{[^\n}]*\})?/m.exec(String(text ?? ""));
458
+ if (!m) return null;
459
+ let args = {};
460
+ if (m[2]) {
461
+ try {
462
+ args = JSON.parse(m[2]);
463
+ } catch {
464
+ return null;
465
+ }
466
+ } else if (/^TOOL\s+[a-z_.]+\s*\{/m.test(String(text ?? ""))) {
467
+ return null;
468
+ }
469
+ return { name: m[1].toLowerCase(), args };
470
+ }
471
+ var certificatesSearch = {
472
+ name: "certificates.search",
473
+ description: "Search the certificate register (a snapshot) by holder name, model designation, or a printed certificate number. Returns the matching rows \u2014 number, holder, model, issue year, status, and document links where on file \u2014 or the exact no-match statement for the string asked.",
474
+ params: [{ key: "query", required: true, description: "the holder, model, or printed certificate number to look up" }],
475
+ audiences: ["agent", "mcp"],
476
+ handler: async (env, args) => {
477
+ const query = String(args?.query ?? "").trim().slice(0, 160);
478
+ if (!query) return null;
479
+ const { searchRegister, registerNote, certificateLinks } = await import("./certificates-CO7KX2S2.js");
480
+ const reg = await searchRegister(env.DB, query, true);
481
+ const output = reg?.rows?.length ? [registerNote(reg.rows), certificateLinks(reg.rows)].filter(Boolean).join("\n") : `No certificate was found for "${query}" in the certificates database (the register snapshot). State this as the search's result, with the searched string visible.`;
482
+ return { name: "certificates.search", query, output };
483
+ }
484
+ };
485
+ var TOOLS_REGISTRY = [certificatesSearch, unitsGet, graphCites, docsSection, glossaryLookup, documentsFamily, licensedSection];
486
+ var TOOL_DECLARATION = [
487
+ "You may use one tool before answering, by writing a single line:",
488
+ ...TOOLS_REGISTRY.filter((t) => t.audiences.includes("agent")).map((t) => {
489
+ const shape = `{${t.params.map((p) => `"${p.key}": "<${p.description}>"`).join(", ")}}`;
490
+ return `TOOL ${t.name} ${shape}`;
491
+ }),
492
+ "The worker runs it and returns the result attributed \u2014 phrase the tool's result as what it returned, with the searched string visible in your answer. Use a tool when the question turns on what it answers (including from a photograph). If you do not need it, answer directly without the line."
493
+ ].join("\n");
494
+ async function runTool(env, call, audience = "agent") {
495
+ const spec = TOOLS_REGISTRY.find((t) => t.name === call.name && t.audiences.includes(audience));
496
+ if (!spec) return null;
497
+ return spec.handler(env, call.args ?? {});
498
+ }
499
+ function toolNote(r) {
500
+ return `The ${r.name} tool returned, for the query "${r.query}":
501
+ ${r.output}`;
502
+ }
503
+
504
+ export {
505
+ standardForDocNumber,
506
+ licensedEntryForPackage,
507
+ licenseBoundaryNote,
508
+ licenseBoundaryRefusal,
509
+ bindModelNode,
510
+ modelGroundingBlock,
511
+ modelCitation,
512
+ modelEcho,
513
+ resolveBlocks,
514
+ contractV2,
515
+ tableRetyped,
516
+ parseToolCall,
517
+ TOOLS_REGISTRY,
518
+ TOOL_DECLARATION,
519
+ runTool,
520
+ toolNote
521
+ };
@@ -1,12 +1,20 @@
1
1
  import {
2
2
  TOOL_DECLARATION,
3
+ bindModelNode,
3
4
  contractV2,
5
+ licenseBoundaryNote,
6
+ licenseBoundaryRefusal,
7
+ licensedEntryForPackage,
8
+ modelCitation,
9
+ modelEcho,
10
+ modelGroundingBlock,
4
11
  parseToolCall,
5
12
  resolveBlocks,
6
13
  runTool,
14
+ standardForDocNumber,
7
15
  tableRetyped,
8
16
  toolNote
9
- } from "./chunk-HVT2ZTWW.js";
17
+ } from "./chunk-JHATKAWW.js";
10
18
  import {
11
19
  NO_CONTEXT,
12
20
  answerQuality,
@@ -428,168 +436,6 @@ async function completeFigures(db, answer, alreadyAttached, used = []) {
428
436
  return figs;
429
437
  }
430
438
 
431
- // workers/worker_public/src/modelplane.ts
432
- var NODE_RE = /(?:^|[\s("'`])\/(req|conf|term|constraint|characteristic|state-machine|dimension)\/([a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)?)(?=[\s)"'`,;:.]|$)/i;
433
- function modelNodeRefIn(text) {
434
- if (!text) return null;
435
- const m = text.match(NODE_RE);
436
- if (!m) return null;
437
- const id = `/${m[1].toLowerCase()}/${m[2]}`;
438
- return id.length <= 120 ? id : null;
439
- }
440
- function standardForDocNumber(docNumber) {
441
- if (!docNumber) return null;
442
- const models = P().sources?.models;
443
- if (!models?.standards?.length || !models?.standard_prefix) return null;
444
- return models.standards.includes(docNumber) ? `${models.standard_prefix}${docNumber}` : null;
445
- }
446
- function licensedEntryForPackage(packageId) {
447
- if (!packageId) return null;
448
- return (P().sources?.licensed ?? []).find((l) => l.package === packageId) ?? null;
449
- }
450
- function licensedEntryForDocNumber(docNumber) {
451
- if (!docNumber) return null;
452
- return (P().sources?.licensed ?? []).find((l) => String(l.doc_number ?? "") === docNumber) ?? null;
453
- }
454
- function licenseBoundaryNote(docNumber, standardKeys) {
455
- const entry = licensedEntryForDocNumber(docNumber);
456
- if (!entry || standardKeys && standardKeys.has(entry.key)) return void 0;
457
- const pointer = P().prompts?.vars?.license_declare_pointer;
458
- return `License boundary \u2014 the question is about ${licenseBoundaryName(entry)}, a licensed publication (entitlement key ${entry.key}). The caller's organization license does not cover its text, so no passage of it was retrieved and NONE of its procedural content (steps, parameters, severities, limits) may be stated, paraphrased or recalled from memory. You MAY answer at the citation level: name the standard and edition, and cite the invoking clause from the PUBLIC passages in context (the Recommendation's own applicability and normative references are public and stay answerable). Then say the organization's license does not cover the standard's text` + (pointer ? ` and point to the declare flow: ${pointer}.` : ".");
459
- }
460
- function licenseBoundaryName(entry) {
461
- const id = entry.doc_number ? ` ${entry.doc_number}` : ` ${entry.package}`;
462
- return `${entry.title ?? "standard"}${entry.edition ? ` (${entry.edition})` : ""} \u2014${id}`;
463
- }
464
- function licenseBoundaryRefusal(docNumber, standardKeys) {
465
- const entry = licensedEntryForDocNumber(docNumber);
466
- if (!entry || standardKeys && standardKeys.has(entry.key)) return void 0;
467
- const pointer = P().prompts?.vars?.license_declare_pointer;
468
- return `${licenseBoundaryName(entry)} is a licensed publication and your organization's license does not cover its text, so I can't quote or summarize its procedure. I can answer at the citation level \u2014 the standard's title and edition, and the clause your Recommendation invokes \u2014 and the public ${P().publisher.name} content in full.` + (pointer ? ` To unlock the full text, an org admin can declare the license under ${pointer}.` : "");
469
- }
470
- async function fetchNode(env, standard, nodeId) {
471
- try {
472
- const row = await env.DB.prepare(
473
- "SELECT standard, node_id, kind, name, clause_doc, clause_ref, content FROM model_nodes WHERE standard = ?1 AND node_id = ?2"
474
- ).bind(standard, nodeId).first();
475
- if (!row) return null;
476
- const content = JSON.parse(String(row.content));
477
- const clause = row.clause_doc && row.clause_ref ? { doc: String(row.clause_doc), ref: String(row.clause_ref), urn: `${row.clause_doc}#clause-${row.clause_ref}` } : row.clause_doc ? { doc: String(row.clause_doc), ref: "", urn: String(row.clause_doc) } : null;
478
- return {
479
- standard: String(row.standard),
480
- node_id: String(row.node_id),
481
- kind: String(row.kind),
482
- name: String(row.name ?? row.node_id),
483
- clause,
484
- content
485
- };
486
- } catch {
487
- return null;
488
- }
489
- }
490
- async function bindModelNode(env, opts) {
491
- const nodeId = modelNodeRefIn(opts.label) ?? modelNodeRefIn(opts.query);
492
- if (!nodeId) return null;
493
- const gate = (node) => {
494
- if (!node) return null;
495
- const entry = licensedEntryForPackage(node.standard);
496
- return entry && !(opts.standardKeys?.has(entry.key) ?? false) ? { ...node, gated: true, content: {} } : node;
497
- };
498
- if (opts.standard) return gate(await fetchNode(env, opts.standard, nodeId));
499
- try {
500
- const rows = await env.DB.prepare("SELECT standard FROM model_nodes WHERE node_id = ?1 LIMIT 2").bind(nodeId).all();
501
- const standards = (rows?.results ?? []).map((r) => String(r.standard));
502
- if (standards.length === 1) return gate(await fetchNode(env, standards[0], nodeId));
503
- return null;
504
- } catch {
505
- return null;
506
- }
507
- }
508
- function clip(s, n = 500) {
509
- const t = String(s ?? "").trim();
510
- return t.length <= n ? t : t.slice(0, n - 1).trimEnd() + " \u2026";
511
- }
512
- function applicabilityText(app) {
513
- if (!app || typeof app !== "object") return "";
514
- const parts = [];
515
- for (const [dim, cond] of Object.entries(app)) {
516
- if (Array.isArray(cond)) parts.push(`${dim.replace(/_/g, " ")}: ${cond.join(", ")}`);
517
- else if (cond && typeof cond === "object" && Array.isArray(cond.values)) {
518
- parts.push(`${dim.replace(/_/g, " ")} (${cond.match ?? "any"}): ${cond.values.join(", ")}`);
519
- }
520
- }
521
- return parts.join("; ");
522
- }
523
- function modelGroundingBlock(node) {
524
- const c = node.content ?? {};
525
- const lines = [];
526
- lines.push(
527
- P().prompts.vars.model_grounding_intro ?? "Model grounding \u2014 the model plane's own statement:"
528
- );
529
- lines.push(`Node: ${node.node_id} (${node.kind.replace(/_/g, " ")}) \u2014 ${node.name} [${node.standard}]`);
530
- if (node.clause) lines.push(`Provenance: ${node.clause.urn}`);
531
- if (c.statement) lines.push(`Statement: ${clip(c.statement)}`);
532
- if (c.definition) lines.push(`Definition: ${clip(c.definition)}`);
533
- if (c.purpose) lines.push(`Purpose: ${clip(c.purpose)}`);
534
- const limit = c.limit ?? {};
535
- if (limit.expression) lines.push(`Machine limit (the constraint the platform's verdict engine evaluates \u2014 quote it verbatim): ${limit.expression}`);
536
- if (limit.accepts?.verdict) lines.push(`Machine limit: ${limit.accepts.verdict} ${limit.accepts.op} ${limit.accepts.limit} (the canonical acceptance chain)`);
537
- if (c.check) lines.push(`Machine check: ${c.check}`);
538
- if (c.derive) lines.push(`Derivation: ${c.derive}${Array.isArray(c.inputs) ? ` (inputs: ${c.inputs.join(", ")})` : ""}`);
539
- const app = applicabilityText(c.applicability);
540
- const scopeApp = applicabilityText(c.scope_applicability);
541
- if (app || scopeApp) lines.push(`Applicability: ${[scopeApp, app].filter(Boolean).join("; ")}`);
542
- if (Array.isArray(c.binds_to) && c.binds_to.length) lines.push(`Binds to: ${c.binds_to.join(", ")}`);
543
- if (Array.isArray(c.targets) && c.targets.length) lines.push(`Verifies requirements: ${c.targets.join(", ")}`);
544
- if (Array.isArray(c.preconditions) && c.preconditions.length) {
545
- const pcs = c.preconditions.map((p) => `${p.id}: ${clip(p.check ?? (p.state ? `state = ${p.state}` : ""), 120)}`).join("; ");
546
- lines.push(`Run-validity preconditions (a violation voids the run \u2014 invalid, never a fail): ${pcs}`);
547
- }
548
- if (c.acceptance_criteria?.description) lines.push(`Acceptance: ${clip(c.acceptance_criteria.description, 300)}`);
549
- if (c.violation_meaning) lines.push(`Violation meaning (verbatim): ${clip(c.violation_meaning, 300)} \u2014 on violation: ${c.on_violation ?? "invalid"}`);
550
- if (Array.isArray(c.values) && c.values.length) {
551
- lines.push(`Values: ${c.values.map((v) => `${v.id}${v.implies?.length ? ` (implies ${v.implies.join(", ")})` : ""}`).join("; ")}`);
552
- }
553
- if (c.source_discrepancy) {
554
- const sd = c.source_discrepancy;
555
- lines.push(
556
- `DECLARED SOURCE DISCREPANCY \u2014 the model and the text disagree; you MUST surface this and cite both: ${clip(sd.summary, 300)} Sources: ${(sd.sources ?? []).join(" and ")}. The model ${sd.resolution === "follows_clause_x" ? "follows one side" : "records the conflict without resolving it"}: ${clip(sd.rationale, 300)}`
557
- );
558
- }
559
- lines.push(
560
- "Rules for this answer: the machine facts (the constraint, the applicability, the acceptance, the provenance) come from THIS node \u2014 quote the machine limit verbatim, never invent one the node does not carry. If this model content and a prose passage disagree \u2014 including a passage from a different edition \u2014 say so explicitly and cite both (this node and the prose clause)."
561
- );
562
- return lines.join("\n");
563
- }
564
- function modelCitation(node) {
565
- return {
566
- doc_id: `model:${node.standard}`,
567
- docidentifier: `${P().publisher.name} SMART model (${(() => {
568
- const prefix = P().sources?.models?.standard_prefix ?? "";
569
- const letter = prefix.replace(/^.*-/, "").toUpperCase();
570
- return String(node.standard).replace(new RegExp(`^${prefix}`, "i"), `${letter} `);
571
- })()})`,
572
- edition: "",
573
- language: "en",
574
- clause_anchor: node.clause?.ref || "model",
575
- clause_title: `${node.kind.replace(/_/g, " ")} \u2014 ${node.name} (${node.node_id})`,
576
- status: "in-force",
577
- corpus: "smart-model",
578
- quality: "verified",
579
- url: void 0,
580
- snippet: `${node.node_id}${node.clause ? ` \xB7 ${node.clause.urn}` : ""}${node.content?.statement ? ` \u2014 ${clip(node.content.statement, 240)}` : ""}`,
581
- score: 1
582
- };
583
- }
584
- function modelEcho(node) {
585
- return {
586
- node_id: node.node_id.slice(0, 120),
587
- kind: node.kind.slice(0, 40),
588
- standard: node.standard.slice(0, 40),
589
- ...node.clause?.urn ? { clause: node.clause.urn.slice(0, 120) } : {}
590
- };
591
- }
592
-
593
439
  // workers/worker_public/src/verdict.ts
594
440
  function tokenize(src) {
595
441
  const toks = [];
@@ -3093,8 +2939,6 @@ export {
3093
2939
  handleMemories,
3094
2940
  scoreFaithfulness,
3095
2941
  checkQuoteAnchors,
3096
- bindModelNode,
3097
- modelGroundingBlock,
3098
2942
  scoreJudge,
3099
2943
  handleAsk
3100
2944
  };
@@ -4,8 +4,9 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-HVT2ZTWW.js";
7
+ } from "./chunk-JHATKAWW.js";
8
8
  import "./chunk-LOBYXEVD.js";
9
+ import "./chunk-LVZTWUVJ.js";
9
10
  import "./chunk-2PCUAJJO.js";
10
11
  import "./chunk-3FYJM7LH.js";
11
12
  export {
@@ -2,4 +2,6 @@ import type { ToolSpec } from "./tools.ts";
2
2
  export declare const unitsGet: ToolSpec;
3
3
  export declare const graphCites: ToolSpec;
4
4
  export declare const docsSection: ToolSpec;
5
+ export declare const documentsFamily: ToolSpec;
6
+ export declare const licensedSection: ToolSpec;
5
7
  export declare const glossaryLookup: ToolSpec;
@@ -1,15 +1,15 @@
1
1
  import {
2
- bindModelNode,
3
2
  checkQuoteAnchors,
4
3
  handleAsk,
5
4
  handleMemories,
6
- modelGroundingBlock,
7
5
  scoreFaithfulness,
8
6
  scoreJudge
9
- } from "../../chunk-NGPUMFYQ.js";
7
+ } from "../../chunk-ZIDDK32O.js";
10
8
  import {
11
- TOOLS_REGISTRY
12
- } from "../../chunk-HVT2ZTWW.js";
9
+ TOOLS_REGISTRY,
10
+ bindModelNode,
11
+ modelGroundingBlock
12
+ } from "../../chunk-JHATKAWW.js";
13
13
  import {
14
14
  handleSearch
15
15
  } from "../../chunk-TJTEBS4S.js";
@@ -973,12 +973,12 @@ async function handleMcp(env, ctx, req, tier, key) {
973
973
  // stream:false forces the JSON lane (anon defaults to SSE)
974
974
  body: JSON.stringify({ ...args, stream: false })
975
975
  });
976
- const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-MVAWZZS2.js");
976
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-4NFFHVTW.js");
977
977
  if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
978
978
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
979
979
  return r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
980
980
  }
981
- const res = name === "ask" ? await (await import("../../ask-OYW3QMOW.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-G76DK4AF.js")).handleSearch(env, ctx, inner, tier, key);
981
+ const res = name === "ask" ? await (await import("../../ask-PUU6HHRZ.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-G76DK4AF.js")).handleSearch(env, ctx, inner, tier, key);
982
982
  return res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
983
983
  });
984
984
  if (out.ok && "accepted" in out) return new Response(null, { status: 202 });
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  "playwright": "^1.62.1",
28
28
  "yaml": "^2.9.1"
29
29
  },
30
- "version": "0.2.89",
30
+ "version": "0.2.91",
31
31
  "description": "The Konneal engine: the publisher-agnostic build pipeline and API plane for standards intelligence (retrieval, answer contract, verdicts, evaluation).",
32
32
  "license": "BSD-3-Clause",
33
33
  "type": "module",
@@ -10,6 +10,8 @@ import { resolveBlocks } from "./refs.ts";
10
10
  import { portIndex, portModelRunner, hasLane } from "./env.ts";
11
11
  import { embed } from "./ai.ts";
12
12
  import { THRESHOLDS } from "./config.ts";
13
+ import { standardKeysFrom } from "./requestScope.ts";
14
+ import { licenseBoundaryRefusal, licensedEntryForDocNumber } from "./modelplane.ts";
13
15
 
14
16
  const slug = (docidentifier: string) =>
15
17
  docidentifier
@@ -21,7 +23,7 @@ export const unitsGet: ToolSpec = {
21
23
  name: "units.get",
22
24
  description:
23
25
  "Fetch typed Recommendation content — a table, formula or figure as structured data (columns, rows, MathML, caption), by its unit id. The machine-consumable form of a Recommendation's content, for computing with rather than reading.",
24
- params: [{ key: "unit_id", required: true, description: "the unit id, e.g. u:table-1 or u:form-3 (ids appear in answers' [[u:…]] references)" }],
26
+ params: [{ key: "unit_id", required: true, description: "the unit id exactly as an answer's [[u:…]] reference spells it" }],
25
27
  audiences: ["mcp"],
26
28
  handler: async (env, args) => {
27
29
  const unit_id = String(args?.unit_id ?? "").trim().replace(/^\[?\[?u:/, "u:").replace(/]?\]?$/, "");
@@ -109,6 +111,114 @@ export const docsSection: ToolSpec = {
109
111
  },
110
112
  };
111
113
 
114
+ export const documentsFamily: ToolSpec = {
115
+ name: "documents.family",
116
+ description:
117
+ "Look up the publication registry for a family: every edition with its derived status (in-force/superseded), which edition is ACTIVE (terminal of the successor chain), and supersession links. Use for current/latest-edition and edition-history questions.",
118
+ params: [{ key: "family", required: true, description: "the family key, e.g. R-60 (series letter and number)" }],
119
+ audiences: ["mcp"],
120
+ handler: async (env, args) => {
121
+ const family = String(args?.family ?? "").trim().toUpperCase();
122
+ if (!/^[A-Z]-\d{1,3}$/.test(family)) return null;
123
+ try {
124
+ const rows = await env.DB.prepare(
125
+ "SELECT d.docidentifier, d.derived_status, d.active, s.docidentifier AS succ FROM documents d LEFT JOIN documents s ON d.superseded_by = s.canonical_id WHERE d.family = ?1 ORDER BY d.part, d.edition",
126
+ )
127
+ .bind(family)
128
+ .all();
129
+ const lines = ((rows.results ?? []) as { docidentifier: string; derived_status: string; active: number; succ: string | null }[]).map(
130
+ (r) => `${r.docidentifier} — ${r.derived_status}${r.active ? " [ACTIVE]" : ""}${r.succ ? ` → superseded by ${r.succ}` : ""}`,
131
+ );
132
+ if (!lines.length) {
133
+ return { name: "documents.family", query: family, output: `No editions are registered for the family ${family}. State this plainly.` };
134
+ }
135
+ return { name: "documents.family", query: family, output: lines.join("\n") };
136
+ } catch {
137
+ return null;
138
+ }
139
+ },
140
+ };
141
+
142
+
143
+ // The licensed library (the owner's 2026-10-04 direction): "return
144
+ // clause X of document Y" for licensed standards, behind the SAME
145
+ // entitlement predicate the ask path applies — the caller declares
146
+ // keys, the deployment's declared whitelist validates them (a forged
147
+ // key can never widen scope), and the unentitled caller receives the
148
+ // boundary refusal: the standard's title and edition, the declare
149
+ // pointer, never a word of the text. The entitled caller gets the
150
+ // model plane's typed nodes for the clause — the computing form.
151
+ export const licensedSection: ToolSpec = {
152
+ name: "licensed.section",
153
+ description:
154
+ "Fetch one clause of a licensed standard's typed model content — requirements, condition sets and parameters as structured data — behind the caller's license entitlement keys. An unentitled caller receives the license boundary: the standard's title and edition and the declare flow, never its text.",
155
+ params: [
156
+ { key: "doc", required: true, description: "the standard's document number, e.g. 60068-2-30 or 61000-4-2" },
157
+ { key: "clause", required: true, description: "the clause number inside the standard, e.g. 5 or 9" },
158
+ { key: "licensed_standards", required: true, description: 'the caller\'s license entitlement keys, e.g. ["std:iec-60068-2-30"] — validated against the licenses this deployment declares; keys it does not know drop' },
159
+ ],
160
+ audiences: ["mcp"],
161
+ handler: async (env, args) => {
162
+ const doc = String(args?.doc ?? "").trim();
163
+ const clause = String(args?.clause ?? "").trim();
164
+ if (doc.length < 3 || !clause) return null;
165
+ // "IEC 60068-2-30" / "ISO/IEC 17025" → the bare doc number the
166
+ // licensed registry keys on
167
+ const docNumber = doc.replace(/^(?:ISO\/IEC|ISO|IEC)\s+/i, "").trim();
168
+ const entry = licensedEntryForDocNumber(docNumber);
169
+ if (!entry) {
170
+ return {
171
+ name: "licensed.section",
172
+ query: `${doc} §${clause}`,
173
+ output: `"${doc}" is not among the licensed standards this deployment keys. For clauses of the public corpus use the docs.section tool instead. State this plainly.`,
174
+ };
175
+ }
176
+ const keys = standardKeysFrom({ licensed_standards: args?.licensed_standards });
177
+ if (!keys.has(entry.key)) {
178
+ const refusal = licenseBoundaryRefusal(docNumber, keys);
179
+ return {
180
+ name: "licensed.section",
181
+ query: `${doc} §${clause}`,
182
+ output: refusal ?? "License boundary — the caller's entitlement set does not cover this standard's text.",
183
+ };
184
+ }
185
+ try {
186
+ const rows = await env.DB.prepare(
187
+ "SELECT node_id, kind, name, clause_ref, content FROM model_nodes WHERE standard = ?1 AND clause_ref = ?2 ORDER BY node_id LIMIT 20",
188
+ )
189
+ .bind(entry.package, clause)
190
+ .all();
191
+ const nodes = ((rows.results ?? []) as { node_id: string; kind: string; name: string | null; clause_ref: string; content: string }[]);
192
+ if (!nodes.length) {
193
+ const c = await env.DB.prepare(
194
+ "SELECT DISTINCT clause_ref FROM model_nodes WHERE standard = ?1 ORDER BY clause_ref",
195
+ )
196
+ .bind(entry.package)
197
+ .all();
198
+ const clauses = ((c.results ?? []) as { clause_ref: string }[]).map((r) => r.clause_ref).filter(Boolean).join(", ");
199
+ return {
200
+ name: "licensed.section",
201
+ query: `${doc} §${clause}`,
202
+ output: `No typed nodes are indexed for ${doc} §${clause}.${clauses ? ` The clauses with typed nodes: ${clauses}.` : ""} State this plainly.`,
203
+ };
204
+ }
205
+ return {
206
+ name: "licensed.section",
207
+ query: `${doc} §${clause}`,
208
+ output: JSON.stringify(
209
+ nodes.map((n) => {
210
+ let content: unknown = n.content;
211
+ try { content = JSON.parse(n.content); } catch { /* verbatim when not JSON */ }
212
+ return { node_id: n.node_id, kind: n.kind, name: n.name, clause: n.clause_ref, content };
213
+ }),
214
+ ),
215
+ };
216
+ } catch {
217
+ return null;
218
+ }
219
+ },
220
+ };
221
+
112
222
  export const glossaryLookup: ToolSpec = {
113
223
  name: "glossary.lookup",
114
224
  description:
@@ -64,9 +64,9 @@ const certificatesSearch: ToolSpec = {
64
64
  },
65
65
  };
66
66
 
67
- import { unitsGet, graphCites, docsSection, glossaryLookup } from "./tools-content.ts";
67
+ import { unitsGet, graphCites, docsSection, glossaryLookup, documentsFamily, licensedSection } from "./tools-content.ts";
68
68
 
69
- export const TOOLS_REGISTRY: ToolSpec[] = [certificatesSearch, unitsGet, graphCites, docsSection, glossaryLookup];
69
+ export const TOOLS_REGISTRY: ToolSpec[] = [certificatesSearch, unitsGet, graphCites, docsSection, glossaryLookup, documentsFamily, licensedSection];
70
70
 
71
71
  /** The agent loop's protocol declaration, GENERATED from the registry —
72
72
  * the model's tool vocabulary is always the registry's, never a
@@ -1,255 +0,0 @@
1
- import {
2
- embed,
3
- hasLane,
4
- portIndex,
5
- portModelRunner
6
- } from "./chunk-LOBYXEVD.js";
7
- import {
8
- THRESHOLDS
9
- } from "./chunk-2PCUAJJO.js";
10
-
11
- // workers/worker_public/src/refs.ts
12
- var REF = /\[\[(u:[A-Za-z0-9_-]+)\]\]/g;
13
- function availableUnitIds(hits) {
14
- const ids = /* @__PURE__ */ new Set();
15
- for (const h of hits) {
16
- const u = h.metadata?.unit_id;
17
- if (u) ids.add(u);
18
- }
19
- return ids;
20
- }
21
- function parseRefs(text) {
22
- return [...text.matchAll(REF)].map((m) => m[1]);
23
- }
24
- function sanitizeRefs(text, available) {
25
- const dropped = [];
26
- const out = text.replace(REF, (full, id) => {
27
- if (available.has(id)) return full;
28
- dropped.push(id);
29
- return "";
30
- });
31
- return { text: out, dropped };
32
- }
33
- async function resolveBlocks(db, refs) {
34
- if (!refs.length) return [];
35
- const uniq = [...new Set(refs)].slice(0, 12);
36
- const blocks = [];
37
- for (let i = 0; i < uniq.length; i += 20) {
38
- const batch = uniq.slice(i, i + 20);
39
- const placeholders = batch.map((_, n) => `?${n + 1}`).join(",");
40
- try {
41
- const res = await db.prepare(`SELECT unit_id, type, docidentifier, edition, payload FROM unit_payloads WHERE unit_id IN (${placeholders})`).bind(...batch).all();
42
- for (const r of res.results) {
43
- let payload = {};
44
- try {
45
- payload = JSON.parse(String(r.payload));
46
- } catch {
47
- continue;
48
- }
49
- blocks.push({
50
- unit_id: String(r.unit_id),
51
- type: String(r.type),
52
- docidentifier: String(r.docidentifier ?? ""),
53
- edition: r.edition ? String(r.edition) : void 0,
54
- payload
55
- });
56
- }
57
- } catch (e) {
58
- console.log("resolveBlocks failed:", String(e).slice(0, 150));
59
- }
60
- }
61
- return blocks;
62
- }
63
- async function contractV2(db, answer, usedHits) {
64
- const available = availableUnitIds(usedHits);
65
- const { text, dropped } = sanitizeRefs(answer, available);
66
- if (dropped.length) console.log("refs: dropped", dropped.length, "invalid (not in passages)");
67
- const refs = parseRefs(text);
68
- const blocks = await resolveBlocks(db, refs);
69
- return { text, blocks, dropped };
70
- }
71
- function tableRetyped(text, availableTable) {
72
- if (!availableTable) return false;
73
- return /(^|\n)\s*\|[^\n]+\|\s*(\n\s*\|[-: |]+\|\s*)?(\n|$)/.test(text) && (text.match(/\|/g) ?? []).length >= 6;
74
- }
75
-
76
- // workers/worker_public/src/tools-content.ts
77
- var slug = (docidentifier) => docidentifier.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
78
- var unitsGet = {
79
- name: "units.get",
80
- description: "Fetch typed Recommendation content \u2014 a table, formula or figure as structured data (columns, rows, MathML, caption), by its unit id. The machine-consumable form of a Recommendation's content, for computing with rather than reading.",
81
- params: [{ key: "unit_id", required: true, description: "the unit id, e.g. u:table-1 or u:form-3 (ids appear in answers' [[u:\u2026]] references)" }],
82
- audiences: ["mcp"],
83
- handler: async (env, args) => {
84
- const unit_id = String(args?.unit_id ?? "").trim().replace(/^\[?\[?u:/, "u:").replace(/]?\]?$/, "");
85
- if (!/^u:[\w.-]+$/.test(unit_id)) return null;
86
- const blocks = await resolveBlocks(env.DB, [unit_id]);
87
- if (!blocks.length) {
88
- return { name: "units.get", query: unit_id, output: `No typed unit "${unit_id}" exists in the indexed payloads. State this plainly.` };
89
- }
90
- return {
91
- name: "units.get",
92
- query: unit_id,
93
- output: JSON.stringify(
94
- blocks.map((b) => ({ unit_id: b.unit_id, type: b.type, docidentifier: b.docidentifier, payload: b.payload }))
95
- )
96
- };
97
- }
98
- };
99
- var graphCites = {
100
- name: "graph.cites",
101
- description: "The bibliography edges: what a publication's own bibliography actually cites, extracted from its indexed bibliography sections. Returns the cited works' labels for a document (optionally scoped to an edition).",
102
- params: [
103
- { key: "doc", required: true, description: "the publication identifier, e.g. R 60-1:2021" },
104
- { key: "edition", required: false, description: "an edition year to scope, e.g. 2021" }
105
- ],
106
- audiences: ["mcp"],
107
- handler: async (env, args) => {
108
- const doc = String(args?.doc ?? "").trim();
109
- if (doc.length < 3) return null;
110
- const edition = args?.edition ? String(args.edition).trim() : null;
111
- const pat = `%${doc.replace(/[:\s]+/g, "%")}%${edition ? edition : ""}%`;
112
- try {
113
- const rows = await env.DB.prepare(
114
- "SELECT DISTINCT n.label AS label FROM graph_edges e JOIN documents d ON e.src = d.canonical_id JOIN graph_nodes n ON e.dst = n.id WHERE d.docidentifier LIKE ?1 AND e.kind = 'cites' ORDER BY label LIMIT 60"
115
- ).bind(pat).all();
116
- const labels = (rows.results ?? []).map((r) => r.label).filter(Boolean);
117
- return {
118
- name: "graph.cites",
119
- query: `${doc}${edition ? ` (${edition})` : ""}`,
120
- output: labels.length ? `The publication's bibliography cites:
121
- ${labels.map((l) => `- ${l}`).join("\n")}` : `No bibliography citations are indexed for "${doc}"${edition ? ` (${edition})` : ""}. State this plainly.`
122
- };
123
- } catch {
124
- return null;
125
- }
126
- }
127
- };
128
- var docsSection = {
129
- name: "docs.section",
130
- description: "Fetch one clause of a publication's rendered document \u2014 its text and its permanent deep-link URL \u2014 for agents that need the human-formatted passage with its anchor.",
131
- params: [
132
- { key: "doc", required: true, description: "the publication identifier, e.g. R 60-1:2021" },
133
- { key: "clause", required: true, description: "the clause anchor, e.g. 5.1.1 or annex-b" }
134
- ],
135
- audiences: ["mcp"],
136
- handler: async (env, args) => {
137
- const doc = String(args?.doc ?? "").trim();
138
- const clause = String(args?.clause ?? "").trim();
139
- if (doc.length < 3 || !clause) return null;
140
- try {
141
- const rows = await env.DB.prepare(
142
- "SELECT docidentifier, clause_anchor, clause_title, text FROM chunks WHERE docidentifier LIKE ?1 AND REPLACE(clause_anchor, ' ', '') = ?2 LIMIT 1"
143
- ).bind(`%${doc.replace(/[:\s]+/g, "%")}%`, clause).all();
144
- const r = (rows.results ?? [])[0];
145
- if (!r) {
146
- return { name: "docs.section", query: `${doc} \xA7${clause}`, output: `No clause "${clause}" is indexed for "${doc}". State this plainly.` };
147
- }
148
- const url = `https://www.ommisa.org/docs/${slug(r.docidentifier)}.html#${r.clause_anchor}`;
149
- return {
150
- name: "docs.section",
151
- query: `${r.docidentifier} \xA7${r.clause_anchor}`,
152
- output: JSON.stringify({ docidentifier: r.docidentifier, clause: r.clause_anchor, title: r.clause_title, url, text: (r.text ?? "").slice(0, 4e3) })
153
- };
154
- } catch {
155
- return null;
156
- }
157
- }
158
- };
159
- var glossaryLookup = {
160
- name: "glossary.lookup",
161
- description: "Look up a defined term in the terminology datasets \u2014 the concept's definition and its defining publication. Bind everyday words to the defined term before interpreting a question.",
162
- params: [{ key: "term", required: true, description: "the term or everyday phrase to bind, e.g. creep or load cell" }],
163
- audiences: ["mcp"],
164
- handler: async (env, args) => {
165
- const term = String(args?.term ?? "").trim();
166
- if (term.length < 2) return null;
167
- if (!hasLane(env, "glossary")) return null;
168
- try {
169
- const vec = await embed(portModelRunner(env), "", term);
170
- const cands = await portIndex(env, "glossary").query({ vector: vec, topK: 5 });
171
- const hits = cands.filter((m) => m.score >= THRESHOLDS.glossaryCosineFloor).map((m) => ({
172
- term: String(m.metadata?.clause_title ?? "").trim(),
173
- definition: String(m.metadata?.chunk_text ?? "").split(" \u2014 ").slice(1).join(" \u2014 ").slice(0, 400),
174
- docidentifier: String(m.metadata?.docidentifier ?? "")
175
- })).filter((x) => x.term && x.definition);
176
- if (!hits.length) {
177
- return { name: "glossary.lookup", query: term, output: `No defined term matches "${term}" in the terminology datasets. State this plainly.` };
178
- }
179
- const seen = /* @__PURE__ */ new Set();
180
- const uniq = hits.filter((h) => {
181
- const k = h.term.toLowerCase().replace(/[^a-z0-9 ]/g, "").replace(/labeler\b/g, "labeller").replace(/\s+/g, " ").trim();
182
- if (seen.has(k)) return false;
183
- seen.add(k);
184
- return true;
185
- }).slice(0, 3);
186
- return {
187
- name: "glossary.lookup",
188
- query: term,
189
- output: uniq.map((h) => `- ${h.term} (${h.docidentifier}): ${h.definition}`).join("\n")
190
- };
191
- } catch {
192
- return null;
193
- }
194
- }
195
- };
196
-
197
- // workers/worker_public/src/tools.ts
198
- function parseToolCall(text) {
199
- const m = /^TOOL\s+([a-z_.]+)\s*(\{[^\n}]*\})?/m.exec(String(text ?? ""));
200
- if (!m) return null;
201
- let args = {};
202
- if (m[2]) {
203
- try {
204
- args = JSON.parse(m[2]);
205
- } catch {
206
- return null;
207
- }
208
- } else if (/^TOOL\s+[a-z_.]+\s*\{/m.test(String(text ?? ""))) {
209
- return null;
210
- }
211
- return { name: m[1].toLowerCase(), args };
212
- }
213
- var certificatesSearch = {
214
- name: "certificates.search",
215
- description: "Search the certificate register (a snapshot) by holder name, model designation, or a printed certificate number. Returns the matching rows \u2014 number, holder, model, issue year, status, and document links where on file \u2014 or the exact no-match statement for the string asked.",
216
- params: [{ key: "query", required: true, description: "the holder, model, or printed certificate number to look up" }],
217
- audiences: ["agent", "mcp"],
218
- handler: async (env, args) => {
219
- const query = String(args?.query ?? "").trim().slice(0, 160);
220
- if (!query) return null;
221
- const { searchRegister, registerNote, certificateLinks } = await import("./certificates-CO7KX2S2.js");
222
- const reg = await searchRegister(env.DB, query, true);
223
- const output = reg?.rows?.length ? [registerNote(reg.rows), certificateLinks(reg.rows)].filter(Boolean).join("\n") : `No certificate was found for "${query}" in the certificates database (the register snapshot). State this as the search's result, with the searched string visible.`;
224
- return { name: "certificates.search", query, output };
225
- }
226
- };
227
- var TOOLS_REGISTRY = [certificatesSearch, unitsGet, graphCites, docsSection, glossaryLookup];
228
- var TOOL_DECLARATION = [
229
- "You may use one tool before answering, by writing a single line:",
230
- ...TOOLS_REGISTRY.filter((t) => t.audiences.includes("agent")).map((t) => {
231
- const shape = `{${t.params.map((p) => `"${p.key}": "<${p.description}>"`).join(", ")}}`;
232
- return `TOOL ${t.name} ${shape}`;
233
- }),
234
- "The worker runs it and returns the result attributed \u2014 phrase the tool's result as what it returned, with the searched string visible in your answer. Use a tool when the question turns on what it answers (including from a photograph). If you do not need it, answer directly without the line."
235
- ].join("\n");
236
- async function runTool(env, call, audience = "agent") {
237
- const spec = TOOLS_REGISTRY.find((t) => t.name === call.name && t.audiences.includes(audience));
238
- if (!spec) return null;
239
- return spec.handler(env, call.args ?? {});
240
- }
241
- function toolNote(r) {
242
- return `The ${r.name} tool returned, for the query "${r.query}":
243
- ${r.output}`;
244
- }
245
-
246
- export {
247
- resolveBlocks,
248
- contractV2,
249
- tableRetyped,
250
- parseToolCall,
251
- TOOLS_REGISTRY,
252
- TOOL_DECLARATION,
253
- runTool,
254
- toolNote
255
- };