@aglyn/plugins-ai 1.3.0 → 1.4.0
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.
- package/package.json +17 -17
- package/src/lib/components/ai-insight-dialog.component.js +7 -2
- package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
- package/src/lib/components/ai-job-request.component.d.ts +28 -0
- package/src/lib/components/ai-job-request.component.js +103 -0
- package/src/lib/components/ai-job-request.component.js.map +1 -0
- package/src/lib/components/ai-jobs-list-page.component.d.ts +2 -0
- package/src/lib/components/ai-jobs-list-page.component.js +2 -2
- package/src/lib/components/ai-jobs-list-page.component.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +36 -6
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +34 -5
- package/src/lib/insights/ai-insight-digest.js +171 -10
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +1 -1
- package/src/lib/jobs/ai-job-insight-step.js +5 -1
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/model/ai-insight.d.ts +4 -0
- package/src/lib/model/ai-insight.js +1 -0
- package/src/lib/model/ai-insight.js.map +1 -1
- package/src/lib/model/ai-site-build-progress.d.ts +8 -0
- package/src/lib/model/ai-site-build-progress.js +62 -1
- package/src/lib/model/ai-site-build-progress.js.map +1 -1
- package/src/lib/plugin.js +1 -1
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/runtime/ai-insight-check.js +22 -6
- package/src/lib/runtime/ai-insight-check.js.map +1 -1
- package/src/lib/server/ai-insight-digest-route.js +3 -1
- package/src/lib/server/ai-insight-digest-route.js.map +1 -1
- package/src/lib/tools/ai-insight-tool.js +11 -3
- package/src/lib/tools/ai-insight-tool.js.map +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -14,7 +15,7 @@
|
|
|
14
15
|
* See the License for the specific language governing permissions and
|
|
15
16
|
* limitations under the License.
|
|
16
17
|
*/ import { hasPersonalDetails } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
17
|
-
import { AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_MAX_CHARS, AI_INSIGHT_MAX_CITED_ROWS, AI_INSIGHT_MAX_CITES, AI_INSIGHT_MAX_INSIGHTS } from "../model/ai-insight.js";
|
|
18
|
+
import { AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_HEADLINE_MAX_CHARS, AI_INSIGHT_MAX_CHARS, AI_INSIGHT_MAX_CITED_ROWS, AI_INSIGHT_MAX_CITES, AI_INSIGHT_MAX_INSIGHTS } from "../model/ai-insight.js";
|
|
18
19
|
const MARKUP = /<\/?[a-z][^>]*>|```|^#{1,6}\s|\*\*/im;
|
|
19
20
|
/**
|
|
20
21
|
* A number as a sentence writes it: an optional sign and currency symbol, the
|
|
@@ -157,13 +158,25 @@ const truncate = (value, decimals)=>{
|
|
|
157
158
|
if (rise === fall) return null;
|
|
158
159
|
return rise ? 'rise' : 'fall';
|
|
159
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* The headline a person may read. One that runs long is only dropped: the
|
|
163
|
+
* insight keeps its sentence, because length says nothing about whether it is
|
|
164
|
+
* true.
|
|
165
|
+
*/ function insightHeadline(insight) {
|
|
166
|
+
const headline = typeof (insight == null ? void 0 : insight.headline) === 'string' ? insight.headline.trim() : '';
|
|
167
|
+
return headline.length <= AI_INSIGHT_HEADLINE_MAX_CHARS ? headline : '';
|
|
168
|
+
}
|
|
160
169
|
/** One insight's findings against the tables the job read; empty when it traces. */ export function checkAiInsight(insight, tables) {
|
|
161
|
-
const
|
|
162
|
-
if (!
|
|
170
|
+
const sentences = typeof (insight == null ? void 0 : insight.text) === 'string' ? insight.text.trim() : '';
|
|
171
|
+
if (!sentences) return [
|
|
163
172
|
'insight-empty'
|
|
164
173
|
];
|
|
165
174
|
const findings = [];
|
|
166
|
-
if (
|
|
175
|
+
if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long');
|
|
176
|
+
// The headline is held to everything the sentence is: it is the part a
|
|
177
|
+
// person reads first, and often the only part.
|
|
178
|
+
const headline = insightHeadline(insight);
|
|
179
|
+
const text = headline ? `${headline}. ${sentences}` : sentences;
|
|
167
180
|
if (MARKUP.test(text)) findings.push('insight-markup');
|
|
168
181
|
if (hasPersonalDetails(text)) findings.push('insight-personal-details');
|
|
169
182
|
const cites = Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : [];
|
|
@@ -259,13 +272,16 @@ const truncate = (value, decimals)=>{
|
|
|
259
272
|
});
|
|
260
273
|
findings.push(...own);
|
|
261
274
|
} else {
|
|
262
|
-
|
|
275
|
+
const headline = insightHeadline(insight);
|
|
276
|
+
kept.push(_extends({}, headline ? {
|
|
277
|
+
headline
|
|
278
|
+
} : {}, {
|
|
263
279
|
text: insight.text.trim(),
|
|
264
280
|
cites: insight.cites.slice(0, AI_INSIGHT_MAX_CITES).map((cite)=>({
|
|
265
281
|
table: cite.table,
|
|
266
282
|
rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS)
|
|
267
283
|
}))
|
|
268
|
-
});
|
|
284
|
+
}));
|
|
269
285
|
}
|
|
270
286
|
});
|
|
271
287
|
const gap = aiInsightGap(answer == null ? void 0 : answer.gap);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/runtime/ai-insight-check.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hasPersonalDetails } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_GAP_MAX_CHARS,\n AI_INSIGHT_MAX_CHARS,\n AI_INSIGHT_MAX_CITED_ROWS,\n AI_INSIGHT_MAX_CITES,\n AI_INSIGHT_MAX_INSIGHTS,\n type AiInsight,\n type AiInsightAnswer,\n type AiInsightCitation,\n type AiInsightTable,\n} from '../model/ai-insight'\n\n/**\n * THE TRACE (AGL-2915): whether an insight's words agree with the rows it\n * cites.\n *\n * An insight job hands the model tables that code computed, and the model\n * writes sentences about them. Nothing about a sentence makes it true, so each\n * one is read back against the figures before a person sees it:\n *\n * - it cites at least one row, of a table this job actually read;\n * - every number it writes is a figure in a row it cites — as the table has\n * it, or rounded to the decimals written, in the unit written — or the\n * length of a cited window, a date in it, or a count of the rows cited;\n * - a rise or a fall it names agrees with the sign of the change it quotes;\n * - it names nobody: no email address and no phone number.\n *\n * An insight that fails any of these is LEFT OUT, never repaired: a sentence\n * whose number cannot be found is exactly the sentence a person must not act\n * on, and rewriting it would be the model's guess again. The rest of the\n * answer stands. What is left out is counted, so the console can say so.\n */\n\n/** Why an insight was left out, as a finding code. */\nexport type AiInsightFinding =\n | 'insight-empty'\n | 'insight-too-long'\n | 'insight-markup'\n | 'insight-personal-details'\n | 'insight-no-citation'\n | 'insight-unknown-table'\n | 'insight-unknown-row'\n | 'insight-number-untraced'\n | 'insight-direction'\n | 'insight-too-many'\n\nexport interface AiInsightVerdict {\n insight: AiInsight\n findings: string[]\n}\n\nexport interface AiInsightCheck {\n /** The insights a person may read, in the order written. */\n kept: AiInsight[]\n /** The insights left out, each with why. */\n left: AiInsightVerdict[]\n /** The gap sentence, when it is one a person may read. */\n gap: string | null\n /** Every finding, in order, for the eval harness and the logs. */\n findings: string[]\n}\n\nconst MARKUP = /<\\/?[a-z][^>]*>|```|^#{1,6}\\s|\\*\\*/im\n\n/**\n * A number as a sentence writes it: an optional sign and currency symbol, the\n * digits with their thousands separators, the decimals, and a unit.\n */\nconst NUMBER = /(?<![\\p{L}\\p{N}_.])([+\\-−]?)([$€£¥]?)(\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.(\\d+))?(?:\\s?(%|percent\\b|k\\b|thousand\\b|m\\b|million\\b|seconds?\\b|secs?\\b|s\\b|minutes?\\b|mins?\\b|hours?\\b|hrs?\\b|h\\b))?/giu\n\n/** Minutes and seconds written together (`2m 04s`), read as one figure in seconds. */\nconst DURATION = /(?<![\\p{L}\\p{N}_.])(?:(\\d+)\\s?h(?:ours?|rs?)?\\s+)?(\\d+)\\s?m(?:in(?:utes?)?)?\\s+(\\d{1,2})\\s?s(?:ec(?:onds?)?)?\\b/giu\n\nconst RISING = /\\b(?:rose|rise[sn]?|rising|grew|grow(?:s|n|ing)?|increas(?:e|ed|es|ing)|up|higher|gain(?:ed|s)?|jump(?:ed|s)?|climb(?:ed|s)?|more)\\b/i\nconst FALLING = /\\b(?:fell|fall(?:s|en|ing)?|drop(?:ped|s)?|declin(?:e|ed|es|ing)|decreas(?:e|ed|es|ing)|down|lower|lost|shr[au]nk|less|fewer)\\b/i\n\ninterface WrittenNumber {\n /** The figure as written, unsigned, in the unit's base (a percent, seconds, a plain count). */\n value: number\n decimals: number\n negative: boolean\n unit: 'percent' | 'thousand' | 'million' | 'seconds' | 'minutes' | 'hours' | 'currency' | null\n /** Where in the text it starts, for the words before it. */\n at: number\n raw: string\n}\n\nfunction unitOf(symbol: string, unit: string | undefined): WrittenNumber['unit'] {\n const word = (unit ?? '').toLowerCase()\n if (word === '%' || word === 'percent') return 'percent'\n if (word === 'k' || word === 'thousand') return 'thousand'\n if (word === 'm' || word === 'million') return 'million'\n if (/^(?:seconds?|secs?|s)$/.test(word)) return 'seconds'\n if (/^(?:minutes?|mins?)$/.test(word)) return 'minutes'\n if (/^(?:hours?|hrs?|h)$/.test(word)) return 'hours'\n return symbol ? 'currency' : null\n}\n\n/** Every figure a sentence writes, durations written as minutes and seconds read as one. */\nexport function aiInsightNumbers(text: string): WrittenNumber[] {\n const found: WrittenNumber[] = []\n const covered: Array<[number, number]> = []\n for (const match of text.matchAll(DURATION)) {\n const hours = Number(match[1] ?? 0)\n const seconds = hours * 3_600 + Number(match[2]) * 60 + Number(match[3])\n const at = match.index ?? 0\n covered.push([at, at + match[0].length])\n found.push({ value: seconds, decimals: 0, negative: false, unit: 'seconds', at, raw: match[0] })\n }\n for (const match of text.matchAll(NUMBER)) {\n const at = match.index ?? 0\n if (covered.some(([start, end]) => at >= start && at < end)) continue\n const whole = match[3].replace(/,/g, '')\n const decimals = match[4] ?? ''\n found.push({\n value: Number(decimals ? `${whole}.${decimals}` : whole),\n decimals: decimals.length,\n negative: match[1] === '-' || match[1] === '−',\n unit: unitOf(match[2], match[5]),\n at,\n raw: match[0],\n })\n }\n return found.sort((a, b) => a.at - b.at)\n}\n\nconst round = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.round(value * scale) / scale\n}\n\nconst truncate = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.trunc(value * scale) / scale\n}\n\n/** Whether a written figure reads a cell's value, at the decimals written, rounded or cut. */\nfunction reads(written: WrittenNumber, cell: number, scale: number): boolean {\n const base = Math.abs(cell) / scale\n const value = Math.abs(written.value)\n return round(base, written.decimals) === value || truncate(base, written.decimals) === value\n}\n\n/** The scales a unit may read a column's cells at: a percent is not a count, and seconds are not dollars. */\nfunction scalesFor(written: WrittenNumber, kind: AiInsightTable['columns'][number]['kind']): number[] {\n switch (written.unit) {\n case 'percent':\n return kind === 'percent' || kind === 'change' || kind === 'number' ? [1] : []\n case 'currency':\n return kind === 'money' ? [1] : []\n case 'thousand':\n return kind === 'count' || kind === 'number' || kind === 'money' ? [1_000] : []\n case 'million':\n return kind === 'count' || kind === 'number' || kind === 'money'\n ? [1_000_000]\n : kind === 'duration'\n ? [60]\n : []\n case 'seconds':\n return kind === 'duration' ? [1] : []\n case 'minutes':\n return kind === 'duration' ? [60] : []\n case 'hours':\n return kind === 'duration' ? [3_600] : []\n default:\n return kind === 'date' || kind === 'text' ? [] : kind === 'duration' ? [1, 60] : [1]\n }\n}\n\ninterface CitedCell {\n table: AiInsightTable\n kind: AiInsightTable['columns'][number]['kind']\n value: number\n}\n\n/** The numbers a citation vouches for beyond its cells: the window, its dates, and how many rows. */\nfunction framingNumbers(tables: readonly AiInsightTable[], cites: readonly AiInsightCitation[]): Set<number> {\n const numbers = new Set<number>()\n for (const table of tables) {\n if (table.period) {\n numbers.add(table.period.days)\n for (const day of [table.period.from, table.period.to]) {\n const [year, month, date] = day.split('-').map(Number)\n numbers.add(year).add(month).add(date)\n }\n }\n numbers.add(table.rows.length)\n }\n for (const cite of cites) numbers.add(cite.rows.length)\n numbers.add(cites.reduce((total, cite) => total + cite.rows.length, 0))\n return numbers\n}\n\n/** Whether a figure's digits are written inside a cited label: a year in a campaign's name, a path's number. */\nfunction inLabel(written: WrittenNumber, labels: readonly string[]): boolean {\n if (written.unit !== null || written.negative) return false\n const digits = written.raw.replace(/[^\\d.]/g, '')\n return labels.some((label) => new RegExp(`(?<![\\\\d.])${digits.replace('.', '\\\\.')}(?![\\\\d.])`).test(label))\n}\n\n/** The sign the words just before a figure give it, or `null` when they give none. */\nfunction directionBefore(text: string, at: number): 'rise' | 'fall' | null {\n const before = text.slice(Math.max(0, at - 40), at)\n const words = before.split(/\\s+/).slice(-4).join(' ')\n const rise = RISING.test(words)\n const fall = FALLING.test(words)\n if (rise === fall) return null\n return rise ? 'rise' : 'fall'\n}\n\n/** One insight's findings against the tables the job read; empty when it traces. */\nexport function checkAiInsight(insight: AiInsight, tables: readonly AiInsightTable[]): string[] {\n const text = typeof insight?.text === 'string' ? insight.text.trim() : ''\n if (!text) return ['insight-empty']\n const findings: string[] = []\n if (text.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long')\n if (MARKUP.test(text)) findings.push('insight-markup')\n if (hasPersonalDetails(text)) findings.push('insight-personal-details')\n\n const cites = Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : []\n if (!cites.length || cites.every((cite) => !Array.isArray(cite?.rows) || !cite.rows.length)) {\n return [...findings, 'insight-no-citation']\n }\n const cells: CitedCell[] = []\n const labels: string[] = []\n const cited: AiInsightTable[] = []\n for (const cite of cites) {\n const table = tables.find((entry) => entry.ref === cite?.table)\n if (!table) {\n findings.push(`insight-unknown-table:${String(cite?.table)}`)\n continue\n }\n cited.push(table)\n for (const index of (cite.rows ?? []).slice(0, AI_INSIGHT_MAX_CITED_ROWS)) {\n const row = Number.isInteger(index) ? table.rows[index] : undefined\n if (!row) {\n findings.push(`insight-unknown-row:${table.ref}:${String(index)}`)\n continue\n }\n for (const column of table.columns) {\n const value = row[column.key]\n if (typeof value === 'number' && Number.isFinite(value)) {\n cells.push({ table, kind: column.kind, value })\n } else if (typeof value === 'string') {\n labels.push(value)\n if (column.kind === 'date') {\n for (const part of value.split('-').map(Number)) {\n cells.push({ table, kind: 'count', value: part })\n }\n }\n }\n }\n }\n }\n if (findings.some((finding) => finding.startsWith('insight-unknown-'))) return findings\n\n const framing = framingNumbers(cited, cites)\n for (const written of aiInsightNumbers(text)) {\n const matched = cells.filter((cell) =>\n scalesFor(written, cell.kind).some((scale) => reads(written, cell.value, scale)),\n )\n const framed =\n written.unit === null && written.decimals === 0 && !written.negative && framing.has(written.value)\n if (!matched.length && !framed && !inLabel(written, labels)) {\n findings.push(`insight-number-untraced:${written.raw.trim()}`)\n continue\n }\n // A rise or a fall is checked against the change it quotes, and only then:\n // \"down\" beside a count is not a claim about a sign.\n const changes = matched.filter((cell) => cell.kind === 'change' && cell.value !== 0)\n if (!changes.length || changes.length !== matched.length) continue\n const direction = directionBefore(text, written.at)\n if (!direction) continue\n const agrees = changes.some((cell) => (direction === 'rise' ? cell.value > 0 : cell.value < 0))\n if (!agrees) findings.push(`insight-direction:${written.raw.trim()}`)\n }\n return findings\n}\n\n/** The gap sentence a person may read: short, without figures and naming nobody; `null` otherwise. */\nexport function aiInsightGap(gap: unknown): string | null {\n if (typeof gap !== 'string') return null\n const text = gap.replace(/\\s+/g, ' ').trim()\n if (!text || text.length > AI_INSIGHT_GAP_MAX_CHARS || /\\d/.test(text) || MARKUP.test(text)) return null\n return hasPersonalDetails(text) ? null : text\n}\n\n/**\n * An answer held to the trace: the insights that trace kept in the order\n * written, the rest left out with why, and past `AI_INSIGHT_MAX_INSIGHTS`\n * nothing more is read.\n */\nexport function checkAiInsightAnswer(\n answer: Partial<AiInsightAnswer> | null | undefined,\n tables: readonly AiInsightTable[],\n): AiInsightCheck {\n const insights = Array.isArray(answer?.insights) ? answer.insights : []\n const kept: AiInsight[] = []\n const left: AiInsightVerdict[] = []\n const findings: string[] = []\n insights.forEach((insight, index) => {\n const own =\n index >= AI_INSIGHT_MAX_INSIGHTS ? ['insight-too-many'] : checkAiInsight(insight, tables)\n if (own.length) {\n left.push({ insight, findings: own })\n findings.push(...own)\n } else {\n kept.push({\n text: insight.text.trim(),\n cites: insight.cites.slice(0, AI_INSIGHT_MAX_CITES).map((cite) => ({\n table: cite.table,\n rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS),\n })),\n })\n }\n })\n const gap = aiInsightGap(answer?.gap)\n if (answer?.gap && !gap) findings.push('insight-gap-unreadable')\n return { kept, left, gap, findings }\n}\n"],"names":["hasPersonalDetails","AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_INSIGHTS","MARKUP","NUMBER","DURATION","RISING","FALLING","unitOf","symbol","unit","word","toLowerCase","test","aiInsightNumbers","text","found","covered","match","matchAll","hours","Number","seconds","at","index","push","length","value","decimals","negative","raw","some","start","end","whole","replace","sort","a","b","round","scale","Math","truncate","trunc","reads","written","cell","base","abs","scalesFor","kind","framingNumbers","tables","cites","numbers","Set","table","period","add","days","day","from","to","year","month","date","split","map","rows","cite","reduce","total","inLabel","labels","digits","label","RegExp","directionBefore","before","slice","max","words","join","rise","fall","checkAiInsight","insight","trim","findings","Array","isArray","every","cells","cited","find","entry","ref","String","row","isInteger","undefined","column","columns","key","isFinite","part","finding","startsWith","framing","matched","filter","framed","has","changes","direction","agrees","aiInsightGap","gap","checkAiInsightAnswer","answer","insights","kept","left","forEach","own"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,wBAAwB,EACxBC,oBAAoB,EACpBC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,QAKlB,yBAAqB;AAoD5B,MAAMC,SAAS;AAEf;;;CAGC,GACD,MAAMC,SAAS;AAEf,oFAAoF,GACpF,MAAMC,WAAW;AAEjB,MAAMC,SAAS;AACf,MAAMC,UAAU;AAahB,SAASC,OAAOC,MAAc,EAAEC,IAAwB;IACtD,MAAMC,OAAO,CAACD,eAAAA,OAAQ,IAAIE,WAAW;IACrC,IAAID,SAAS,OAAOA,SAAS,WAAW,OAAO;IAC/C,IAAIA,SAAS,OAAOA,SAAS,YAAY,OAAO;IAChD,IAAIA,SAAS,OAAOA,SAAS,WAAW,OAAO;IAC/C,IAAI,yBAAyBE,IAAI,CAACF,OAAO,OAAO;IAChD,IAAI,uBAAuBE,IAAI,CAACF,OAAO,OAAO;IAC9C,IAAI,sBAAsBE,IAAI,CAACF,OAAO,OAAO;IAC7C,OAAOF,SAAS,aAAa;AAC/B;AAEA,0FAA0F,GAC1F,OAAO,SAASK,iBAAiBC,IAAY;IAC3C,MAAMC,QAAyB,EAAE;IACjC,MAAMC,UAAmC,EAAE;IAC3C,KAAK,MAAMC,SAASH,KAAKI,QAAQ,CAACd,UAAW;YACtBa,SAEVA;QAFX,MAAME,QAAQC,QAAOH,UAAAA,KAAK,CAAC,EAAE,YAARA,UA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GACD,OAAO,SAASuG,qBACdC,MAAmD,EACnDnE,MAAiC;IAEjC,MAAMoE,WAAW/B,MAAMC,OAAO,CAAC6B,0BAAAA,OAAQC,QAAQ,IAAID,OAAOC,QAAQ,GAAG,EAAE;IACvE,MAAMC,OAAoB,EAAE;IAC5B,MAAMC,OAA2B,EAAE;IACnC,MAAMlC,WAAqB,EAAE;IAC7BgC,SAASG,OAAO,CAAC,CAACrC,SAAS9D;QACzB,MAAMoG,MACJpG,SAAStB,0BAA0B;YAAC;SAAmB,GAAGmF,eAAeC,SAASlC;QACpF,IAAIwE,IAAIlG,MAAM,EAAE;YACdgG,KAAKjG,IAAI,CAAC;gBAAE6D;gBAASE,UAAUoC;YAAI;YACnCpC,SAAS/D,IAAI,IAAImG;QACnB,OAAO;YACLH,KAAKhG,IAAI,CAAC;gBACRV,MAAMuE,QAAQvE,IAAI,CAACwE,IAAI;gBACvBlC,OAAOiC,QAAQjC,KAAK,CAAC0B,KAAK,CAAC,GAAG9E,sBAAsBkE,GAAG,CAAC,CAACE,OAAU,CAAA;wBACjEb,OAAOa,KAAKb,KAAK;wBACjBY,MAAMC,KAAKD,IAAI,CAACW,KAAK,CAAC,GAAG/E;oBAC3B,CAAA;YACF;QACF;IACF;IACA,MAAMqH,MAAMD,aAAaG,0BAAAA,OAAQF,GAAG;IACpC,IAAIE,CAAAA,0BAAAA,OAAQF,GAAG,KAAI,CAACA,KAAK7B,SAAS/D,IAAI,CAAC;IACvC,OAAO;QAAEgG;QAAMC;QAAML;QAAK7B;IAAS;AACrC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/runtime/ai-insight-check.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { hasPersonalDetails } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_GAP_MAX_CHARS,\n AI_INSIGHT_HEADLINE_MAX_CHARS,\n AI_INSIGHT_MAX_CHARS,\n AI_INSIGHT_MAX_CITED_ROWS,\n AI_INSIGHT_MAX_CITES,\n AI_INSIGHT_MAX_INSIGHTS,\n type AiInsight,\n type AiInsightAnswer,\n type AiInsightCitation,\n type AiInsightTable,\n} from '../model/ai-insight'\n\n/**\n * THE TRACE (AGL-2915): whether an insight's words agree with the rows it\n * cites.\n *\n * An insight job hands the model tables that code computed, and the model\n * writes sentences about them. Nothing about a sentence makes it true, so each\n * one is read back against the figures before a person sees it:\n *\n * - it cites at least one row, of a table this job actually read;\n * - every number it writes is a figure in a row it cites — as the table has\n * it, or rounded to the decimals written, in the unit written — or the\n * length of a cited window, a date in it, or a count of the rows cited;\n * - a rise or a fall it names agrees with the sign of the change it quotes;\n * - it names nobody: no email address and no phone number.\n *\n * An insight that fails any of these is LEFT OUT, never repaired: a sentence\n * whose number cannot be found is exactly the sentence a person must not act\n * on, and rewriting it would be the model's guess again. The rest of the\n * answer stands. What is left out is counted, so the console can say so.\n */\n\n/** Why an insight was left out, as a finding code. */\nexport type AiInsightFinding =\n | 'insight-empty'\n | 'insight-too-long'\n | 'insight-markup'\n | 'insight-personal-details'\n | 'insight-no-citation'\n | 'insight-unknown-table'\n | 'insight-unknown-row'\n | 'insight-number-untraced'\n | 'insight-direction'\n | 'insight-too-many'\n\nexport interface AiInsightVerdict {\n insight: AiInsight\n findings: string[]\n}\n\nexport interface AiInsightCheck {\n /** The insights a person may read, in the order written. */\n kept: AiInsight[]\n /** The insights left out, each with why. */\n left: AiInsightVerdict[]\n /** The gap sentence, when it is one a person may read. */\n gap: string | null\n /** Every finding, in order, for the eval harness and the logs. */\n findings: string[]\n}\n\nconst MARKUP = /<\\/?[a-z][^>]*>|```|^#{1,6}\\s|\\*\\*/im\n\n/**\n * A number as a sentence writes it: an optional sign and currency symbol, the\n * digits with their thousands separators, the decimals, and a unit.\n */\nconst NUMBER = /(?<![\\p{L}\\p{N}_.])([+\\-−]?)([$€£¥]?)(\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.(\\d+))?(?:\\s?(%|percent\\b|k\\b|thousand\\b|m\\b|million\\b|seconds?\\b|secs?\\b|s\\b|minutes?\\b|mins?\\b|hours?\\b|hrs?\\b|h\\b))?/giu\n\n/** Minutes and seconds written together (`2m 04s`), read as one figure in seconds. */\nconst DURATION = /(?<![\\p{L}\\p{N}_.])(?:(\\d+)\\s?h(?:ours?|rs?)?\\s+)?(\\d+)\\s?m(?:in(?:utes?)?)?\\s+(\\d{1,2})\\s?s(?:ec(?:onds?)?)?\\b/giu\n\nconst RISING = /\\b(?:rose|rise[sn]?|rising|grew|grow(?:s|n|ing)?|increas(?:e|ed|es|ing)|up|higher|gain(?:ed|s)?|jump(?:ed|s)?|climb(?:ed|s)?|more)\\b/i\nconst FALLING = /\\b(?:fell|fall(?:s|en|ing)?|drop(?:ped|s)?|declin(?:e|ed|es|ing)|decreas(?:e|ed|es|ing)|down|lower|lost|shr[au]nk|less|fewer)\\b/i\n\ninterface WrittenNumber {\n /** The figure as written, unsigned, in the unit's base (a percent, seconds, a plain count). */\n value: number\n decimals: number\n negative: boolean\n unit: 'percent' | 'thousand' | 'million' | 'seconds' | 'minutes' | 'hours' | 'currency' | null\n /** Where in the text it starts, for the words before it. */\n at: number\n raw: string\n}\n\nfunction unitOf(symbol: string, unit: string | undefined): WrittenNumber['unit'] {\n const word = (unit ?? '').toLowerCase()\n if (word === '%' || word === 'percent') return 'percent'\n if (word === 'k' || word === 'thousand') return 'thousand'\n if (word === 'm' || word === 'million') return 'million'\n if (/^(?:seconds?|secs?|s)$/.test(word)) return 'seconds'\n if (/^(?:minutes?|mins?)$/.test(word)) return 'minutes'\n if (/^(?:hours?|hrs?|h)$/.test(word)) return 'hours'\n return symbol ? 'currency' : null\n}\n\n/** Every figure a sentence writes, durations written as minutes and seconds read as one. */\nexport function aiInsightNumbers(text: string): WrittenNumber[] {\n const found: WrittenNumber[] = []\n const covered: Array<[number, number]> = []\n for (const match of text.matchAll(DURATION)) {\n const hours = Number(match[1] ?? 0)\n const seconds = hours * 3_600 + Number(match[2]) * 60 + Number(match[3])\n const at = match.index ?? 0\n covered.push([at, at + match[0].length])\n found.push({ value: seconds, decimals: 0, negative: false, unit: 'seconds', at, raw: match[0] })\n }\n for (const match of text.matchAll(NUMBER)) {\n const at = match.index ?? 0\n if (covered.some(([start, end]) => at >= start && at < end)) continue\n const whole = match[3].replace(/,/g, '')\n const decimals = match[4] ?? ''\n found.push({\n value: Number(decimals ? `${whole}.${decimals}` : whole),\n decimals: decimals.length,\n negative: match[1] === '-' || match[1] === '−',\n unit: unitOf(match[2], match[5]),\n at,\n raw: match[0],\n })\n }\n return found.sort((a, b) => a.at - b.at)\n}\n\nconst round = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.round(value * scale) / scale\n}\n\nconst truncate = (value: number, decimals: number) => {\n const scale = 10 ** decimals\n return Math.trunc(value * scale) / scale\n}\n\n/** Whether a written figure reads a cell's value, at the decimals written, rounded or cut. */\nfunction reads(written: WrittenNumber, cell: number, scale: number): boolean {\n const base = Math.abs(cell) / scale\n const value = Math.abs(written.value)\n return round(base, written.decimals) === value || truncate(base, written.decimals) === value\n}\n\n/** The scales a unit may read a column's cells at: a percent is not a count, and seconds are not dollars. */\nfunction scalesFor(written: WrittenNumber, kind: AiInsightTable['columns'][number]['kind']): number[] {\n switch (written.unit) {\n case 'percent':\n return kind === 'percent' || kind === 'change' || kind === 'number' ? [1] : []\n case 'currency':\n return kind === 'money' ? [1] : []\n case 'thousand':\n return kind === 'count' || kind === 'number' || kind === 'money' ? [1_000] : []\n case 'million':\n return kind === 'count' || kind === 'number' || kind === 'money'\n ? [1_000_000]\n : kind === 'duration'\n ? [60]\n : []\n case 'seconds':\n return kind === 'duration' ? [1] : []\n case 'minutes':\n return kind === 'duration' ? [60] : []\n case 'hours':\n return kind === 'duration' ? [3_600] : []\n default:\n return kind === 'date' || kind === 'text' ? [] : kind === 'duration' ? [1, 60] : [1]\n }\n}\n\ninterface CitedCell {\n table: AiInsightTable\n kind: AiInsightTable['columns'][number]['kind']\n value: number\n}\n\n/** The numbers a citation vouches for beyond its cells: the window, its dates, and how many rows. */\nfunction framingNumbers(tables: readonly AiInsightTable[], cites: readonly AiInsightCitation[]): Set<number> {\n const numbers = new Set<number>()\n for (const table of tables) {\n if (table.period) {\n numbers.add(table.period.days)\n for (const day of [table.period.from, table.period.to]) {\n const [year, month, date] = day.split('-').map(Number)\n numbers.add(year).add(month).add(date)\n }\n }\n numbers.add(table.rows.length)\n }\n for (const cite of cites) numbers.add(cite.rows.length)\n numbers.add(cites.reduce((total, cite) => total + cite.rows.length, 0))\n return numbers\n}\n\n/** Whether a figure's digits are written inside a cited label: a year in a campaign's name, a path's number. */\nfunction inLabel(written: WrittenNumber, labels: readonly string[]): boolean {\n if (written.unit !== null || written.negative) return false\n const digits = written.raw.replace(/[^\\d.]/g, '')\n return labels.some((label) => new RegExp(`(?<![\\\\d.])${digits.replace('.', '\\\\.')}(?![\\\\d.])`).test(label))\n}\n\n/** The sign the words just before a figure give it, or `null` when they give none. */\nfunction directionBefore(text: string, at: number): 'rise' | 'fall' | null {\n const before = text.slice(Math.max(0, at - 40), at)\n const words = before.split(/\\s+/).slice(-4).join(' ')\n const rise = RISING.test(words)\n const fall = FALLING.test(words)\n if (rise === fall) return null\n return rise ? 'rise' : 'fall'\n}\n\n/**\n * The headline a person may read. One that runs long is only dropped: the\n * insight keeps its sentence, because length says nothing about whether it is\n * true.\n */\nfunction insightHeadline(insight: AiInsight): string {\n const headline = typeof insight?.headline === 'string' ? insight.headline.trim() : ''\n return headline.length <= AI_INSIGHT_HEADLINE_MAX_CHARS ? headline : ''\n}\n\n/** One insight's findings against the tables the job read; empty when it traces. */\nexport function checkAiInsight(insight: AiInsight, tables: readonly AiInsightTable[]): string[] {\n const sentences = typeof insight?.text === 'string' ? insight.text.trim() : ''\n if (!sentences) return ['insight-empty']\n const findings: string[] = []\n if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long')\n // The headline is held to everything the sentence is: it is the part a\n // person reads first, and often the only part.\n const headline = insightHeadline(insight)\n const text = headline ? `${headline}. ${sentences}` : sentences\n if (MARKUP.test(text)) findings.push('insight-markup')\n if (hasPersonalDetails(text)) findings.push('insight-personal-details')\n\n const cites = Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : []\n if (!cites.length || cites.every((cite) => !Array.isArray(cite?.rows) || !cite.rows.length)) {\n return [...findings, 'insight-no-citation']\n }\n const cells: CitedCell[] = []\n const labels: string[] = []\n const cited: AiInsightTable[] = []\n for (const cite of cites) {\n const table = tables.find((entry) => entry.ref === cite?.table)\n if (!table) {\n findings.push(`insight-unknown-table:${String(cite?.table)}`)\n continue\n }\n cited.push(table)\n for (const index of (cite.rows ?? []).slice(0, AI_INSIGHT_MAX_CITED_ROWS)) {\n const row = Number.isInteger(index) ? table.rows[index] : undefined\n if (!row) {\n findings.push(`insight-unknown-row:${table.ref}:${String(index)}`)\n continue\n }\n for (const column of table.columns) {\n const value = row[column.key]\n if (typeof value === 'number' && Number.isFinite(value)) {\n cells.push({ table, kind: column.kind, value })\n } else if (typeof value === 'string') {\n labels.push(value)\n if (column.kind === 'date') {\n for (const part of value.split('-').map(Number)) {\n cells.push({ table, kind: 'count', value: part })\n }\n }\n }\n }\n }\n }\n if (findings.some((finding) => finding.startsWith('insight-unknown-'))) return findings\n\n const framing = framingNumbers(cited, cites)\n for (const written of aiInsightNumbers(text)) {\n const matched = cells.filter((cell) =>\n scalesFor(written, cell.kind).some((scale) => reads(written, cell.value, scale)),\n )\n const framed =\n written.unit === null && written.decimals === 0 && !written.negative && framing.has(written.value)\n if (!matched.length && !framed && !inLabel(written, labels)) {\n findings.push(`insight-number-untraced:${written.raw.trim()}`)\n continue\n }\n // A rise or a fall is checked against the change it quotes, and only then:\n // \"down\" beside a count is not a claim about a sign.\n const changes = matched.filter((cell) => cell.kind === 'change' && cell.value !== 0)\n if (!changes.length || changes.length !== matched.length) continue\n const direction = directionBefore(text, written.at)\n if (!direction) continue\n const agrees = changes.some((cell) => (direction === 'rise' ? cell.value > 0 : cell.value < 0))\n if (!agrees) findings.push(`insight-direction:${written.raw.trim()}`)\n }\n return findings\n}\n\n/** The gap sentence a person may read: short, without figures and naming nobody; `null` otherwise. */\nexport function aiInsightGap(gap: unknown): string | null {\n if (typeof gap !== 'string') return null\n const text = gap.replace(/\\s+/g, ' ').trim()\n if (!text || text.length > AI_INSIGHT_GAP_MAX_CHARS || /\\d/.test(text) || MARKUP.test(text)) return null\n return hasPersonalDetails(text) ? null : text\n}\n\n/**\n * An answer held to the trace: the insights that trace kept in the order\n * written, the rest left out with why, and past `AI_INSIGHT_MAX_INSIGHTS`\n * nothing more is read.\n */\nexport function checkAiInsightAnswer(\n answer: Partial<AiInsightAnswer> | null | undefined,\n tables: readonly AiInsightTable[],\n): AiInsightCheck {\n const insights = Array.isArray(answer?.insights) ? answer.insights : []\n const kept: AiInsight[] = []\n const left: AiInsightVerdict[] = []\n const findings: string[] = []\n insights.forEach((insight, index) => {\n const own =\n index >= AI_INSIGHT_MAX_INSIGHTS ? ['insight-too-many'] : checkAiInsight(insight, tables)\n if (own.length) {\n left.push({ insight, findings: own })\n findings.push(...own)\n } else {\n const headline = insightHeadline(insight)\n kept.push({\n ...(headline ? { headline } : {}),\n text: insight.text.trim(),\n cites: insight.cites.slice(0, AI_INSIGHT_MAX_CITES).map((cite) => ({\n table: cite.table,\n rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS),\n })),\n })\n }\n })\n const gap = aiInsightGap(answer?.gap)\n if (answer?.gap && !gap) findings.push('insight-gap-unreadable')\n return { kept, left, gap, findings }\n}\n"],"names":["hasPersonalDetails","AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_INSIGHTS","MARKUP","NUMBER","DURATION","RISING","FALLING","unitOf","symbol","unit","word","toLowerCase","test","aiInsightNumbers","text","found","covered","match","matchAll","hours","Number","seconds","at","index","push","length","value","decimals","negative","raw","some","start","end","whole","replace","sort","a","b","round","scale","Math","truncate","trunc","reads","written","cell","base","abs","scalesFor","kind","framingNumbers","tables","cites","numbers","Set","table","period","add","days","day","from","to","year","month","date","split","map","rows","cite","reduce","total","inLabel","labels","digits","label","RegExp","directionBefore","before","slice","max","words","join","rise","fall","insightHeadline","insight","headline","trim","checkAiInsight","sentences","findings","Array","isArray","every","cells","cited","find","entry","ref","String","row","isInteger","undefined","column","columns","key","isFinite","part","finding","startsWith","framing","matched","filter","framed","has","changes","direction","agrees","aiInsightGap","gap","checkAiInsightAnswer","answer","insights","kept","left","forEach","own"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,wBAAwB,EACxBC,6BAA6B,EAC7BC,oBAAoB,EACpBC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,QAKlB,yBAAqB;AAoD5B,MAAMC,SAAS;AAEf;;;CAGC,GACD,MAAMC,SAAS;AAEf,oFAAoF,GACpF,MAAMC,WAAW;AAEjB,MAAMC,SAAS;AACf,MAAMC,UAAU;AAahB,SAASC,OAAOC,MAAc,EAAEC,IAAwB;IACtD,MAAMC,OAAO,CAACD,eAAAA,OAAQ,IAAIE,WAAW;IACrC,IAAID,SAAS,OAAOA,SAAS,WAAW,OAAO;IAC/C,IAAIA,SAAS,OAAOA,SAAS,YAAY,OAAO;IAChD,IAAIA,SAAS,OAAOA,S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O;YACL,MAAMxC,WAAWF,gBAAgBC;YACjCsC,KAAKnG,IAAI,CAAC,aACJ8D,WAAW;gBAAEA;YAAS,IAAI,CAAC;gBAC/BxE,MAAMuE,QAAQvE,IAAI,CAACyE,IAAI;gBACvBnC,OAAOiC,QAAQjC,KAAK,CAAC0B,KAAK,CAAC,GAAG9E,sBAAsBkE,GAAG,CAAC,CAACE,OAAU,CAAA;wBACjEb,OAAOa,KAAKb,KAAK;wBACjBY,MAAMC,KAAKD,IAAI,CAACW,KAAK,CAAC,GAAG/E;oBAC3B,CAAA;;QAEJ;IACF;IACA,MAAMwH,MAAMD,aAAaG,0BAAAA,OAAQF,GAAG;IACpC,IAAIE,CAAAA,0BAAAA,OAAQF,GAAG,KAAI,CAACA,KAAK7B,SAASlE,IAAI,CAAC;IACvC,OAAO;QAAEmG;QAAMC;QAAML;QAAK7B;IAAS;AACrC"}
|
|
@@ -28,6 +28,7 @@ import { notifyUsers } from "@aglyn/tenant-data-admin/server/notifications";
|
|
|
28
28
|
import { renderSystemEmailContent, systemEmailBrand } from "@aglyn/tenant-data-admin/server/render-system-email";
|
|
29
29
|
import { listOrgMembers, memberHasPermissionOnHost } from "@aglyn/tenant-data-admin/server/organizations";
|
|
30
30
|
import { getServerReleaseFlagValues } from "@aglyn/tenant-data-admin/server/release-flags";
|
|
31
|
+
import { weeklySummaryEmailColors } from "@aglyn/tenant-data-admin/server/weekly-summary";
|
|
31
32
|
import { safeEqual } from "@aglyn/tenant-data-admin/server/safe-equal";
|
|
32
33
|
import { runAiInsightDigestSweep } from "../insights/ai-insight-digest.js";
|
|
33
34
|
/**
|
|
@@ -150,7 +151,8 @@ import { runAiInsightDigestSweep } from "../insights/ai-insight-digest.js";
|
|
|
150
151
|
},
|
|
151
152
|
// An email link must be absolute; with no console URL configured the
|
|
152
153
|
// digest says where to look without one.
|
|
153
|
-
consoleOrigin: ((_process_env_NEXT_PUBLIC_CONSOLE_URL = process.env.NEXT_PUBLIC_CONSOLE_URL) != null ? _process_env_NEXT_PUBLIC_CONSOLE_URL : '').trim().replace(/\/+$/, '')
|
|
154
|
+
consoleOrigin: ((_process_env_NEXT_PUBLIC_CONSOLE_URL = process.env.NEXT_PUBLIC_CONSOLE_URL) != null ? _process_env_NEXT_PUBLIC_CONSOLE_URL : '').trim().replace(/\/+$/, ''),
|
|
155
|
+
colors: weeklySummaryEmailColors
|
|
154
156
|
};
|
|
155
157
|
const report = await runAiInsightDigestSweep(deps, {
|
|
156
158
|
cursor
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-insight-digest-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: exempt — server-internal cron (x-cron-secret) with no user\n// caller; it asks each workspace's ai-generate pause before it creates a job,\n// and the jobs it creates are held by the same pause on the beat.\n\nimport { writeCronBeat } from '@aglyn/aglyn/app-utils/health-report'\nimport { rateLimitedRetryAtMs, sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { featureLockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport { listOrgMembers, memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { getServerReleaseFlagValues } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { safeEqual } from '@aglyn/tenant-data-admin/server/safe-equal'\nimport {\n AI_INSIGHTS_DIGEST_CRON_ID,\n runAiInsightDigestSweep,\n type AiInsightDigestDeps,\n} from '../insights/ai-insight-digest'\n\n/**\n * The weekly insights' scheduled route (AGL-2915):\n * `POST /api/admin/ai-insights-digest`.\n *\n * Cloud Scheduler calls it at 06:00 and 14:00 UTC through\n * `consoleAiInsightsDigest` in `cloud/functions`, on the console's\n * `CRON_SECRET`: 501 while the secret is unset, 401 without it. Monday's\n * first run makes the week's digests, which the AI jobs beat then writes, and\n * every run after it delivers what is written — see `ai-insight-digest.ts`.\n * `/api/admin/` is the path because the console's edge lets the cron secret's\n * header through there. It stamps `ai-insights-digest` for\n * `/api/health/crons` on every authorized call.\n */\nexport async function POST(request: Request): Promise<Response> {\n if (request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const secret = process.env.CRON_SECRET\n if (!secret) {\n return Response.json({ error: 'The weekly insights are not configured (CRON_SECRET).' }, { status: 501 })\n }\n if (\n !safeEqual(request.headers.get('x-cron-secret'), secret) &&\n !safeEqual(request.headers.get('authorization'), `Bearer ${secret}`)\n ) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n const firestore = firebaseAdmin.app().firestore()\n // The inventory row's id, written out: `cron-beat-wiring.spec.ts` finds a\n // job's stamp by the quoted id beside the call.\n await writeCronBeat(firestore, 'ai-insights-digest' satisfies typeof AI_INSIGHTS_DIGEST_CRON_ID)\n\n let cursor: string | null = null\n try {\n const body = (await request.json()) as { cursor?: unknown } | null\n const raw = body?.cursor\n cursor = typeof raw === 'string' && raw && !raw.includes('/') ? raw : null\n } catch {\n // A bodyless POST is the first call of a run.\n }\n\n try {\n // The platform switch holds the whole run, as it holds the jobs beat.\n if (await featureLockdownRefusal({ feature: 'ai-generate' })) {\n return Response.json({ held: true, done: true, nextCursor: null }, { status: 200 })\n }\n const flags = await getServerReleaseFlagValues()\n const deps: AiInsightDigestDeps = {\n firestore,\n now: new Date(),\n flagValue: flags['release_ai_generative'],\n // The digest's audience: a locked or disabled account is not told\n // (AGL-3418).\n listMembers: async (orgId) => {\n const members = await listOrgMembers(orgId)\n const reachable = new Set(\n await withoutMailWithheldAccounts(members.map((member) => member.$id)),\n )\n return members.filter((member) => reachable.has(member.$id))\n },\n mayGenerate: (orgId, hostId, member) => memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'),\n paused: async (orgId) => Boolean(await featureLockdownRefusal({ feature: 'ai-generate', orgId })),\n notify: (uid, payload) => notifyUsers([uid], { type: 'content.insightsDigest', ...payload }),\n send: async (email) => {\n const recipients = await filterSuppressedEmails([email.to], firestore)\n if (!recipients.length) return { sent: false, rateLimited: false }\n // The `ai-insights-digest` system email (AGL-3367), in the org's brand.\n const content = await renderSystemEmailContent(\n 'ai-insights-digest',\n { 'site.name': email.siteName, 'digest.body': email.text, ...email.merge },\n systemEmailBrand(email.org),\n { subject: email.subject, text: email.text },\n )\n const result = await sendEmail({\n to: recipients,\n ...content,\n fromName: email.fromName,\n context: 'ai-insights-digest',\n priority: 'bulk',\n })\n if (result.sent) {\n await meterPlatformEmail().catch(() => undefined)\n return { sent: true, rateLimited: false }\n }\n return { sent: false, rateLimited: rateLimitedRetryAtMs(result) !== null }\n },\n // An email link must be absolute; with no console URL configured the\n // digest says where to look without one.\n consoleOrigin: (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, ''),\n }\n const report = await runAiInsightDigestSweep(deps, { cursor })\n return Response.json(report, { status: 200 })\n } catch (error) {\n console.error('ai insights digest run failed', error)\n return Response.json({ error: 'The weekly insights run failed' }, { status: 500 })\n }\n}\n"],"names":["writeCronBeat","rateLimitedRetryAtMs","sendEmail","withoutMailWithheldAccounts","filterSuppressedEmails","meterPlatformEmail","firebaseAdmin","featureLockdownRefusal","notifyUsers","renderSystemEmailContent","systemEmailBrand","listOrgMembers","memberHasPermissionOnHost","getServerReleaseFlagValues","safeEqual","runAiInsightDigestSweep","POST","request","method","Response","json","error","status","secret","process","env","CRON_SECRET","headers","get","firestore","app","cursor","body","raw","includes","feature","held","done","nextCursor","flags","deps","now","Date","flagValue","listMembers","orgId","members","reachable","Set","map","member","$id","filter","has","mayGenerate","hostId","paused","Boolean","notify","uid","payload","type","send","email","recipients","to","length","sent","rateLimited","content","siteName","text","merge","org","subject","result","fromName","context","priority","catch","undefined","consoleOrigin","NEXT_PUBLIC_CONSOLE_URL","trim","replace","report","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,2EAA2E;AAC3E,8EAA8E;AAC9E,kEAAkE;AAElE,SAASA,aAAa,QAAQ,uCAAsC;AACpE,SAASC,oBAAoB,EAAEC,SAAS,QAAQ,2BAA0B;AAC1E,SAASC,2BAA2B,QAAQ,+CAA8C;AAC1F,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,cAAc,EAAEC,yBAAyB,QAAQ,gDAA+C;AACzG,SAASC,0BAA0B,QAAQ,gDAA+C;AAC1F,SAASC,SAAS,QAAQ,6CAA4C;AACtE,SAEEC,uBAAuB,QAElB,mCAA+B;AAEtC;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,KAAKC,OAAgB;IACzC,IAAIA,QAAQC,MAAM,KAAK,QAAQ;QAC7B,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAqB,GAAG;YAAEC,QAAQ;QAAI;IACtE;IACA,MAAMC,SAASC,QAAQC,GAAG,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E,wBAAwByB,MAAM;YAAET;QAAO;QAC5D,OAAOZ,SAASC,IAAI,CAACiE,QAAQ;YAAE/D,QAAQ;QAAI;IAC7C,EAAE,OAAOD,OAAO;QACdiE,QAAQjE,KAAK,CAAC,iCAAiCA;QAC/C,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiC,GAAG;YAAEC,QAAQ;QAAI;IAClF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-insight-digest-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: exempt — server-internal cron (x-cron-secret) with no user\n// caller; it asks each workspace's ai-generate pause before it creates a job,\n// and the jobs it creates are held by the same pause on the beat.\n\nimport { writeCronBeat } from '@aglyn/aglyn/app-utils/health-report'\nimport { rateLimitedRetryAtMs, sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { featureLockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport { listOrgMembers, memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { getServerReleaseFlagValues } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { weeklySummaryEmailColors } from '@aglyn/tenant-data-admin/server/weekly-summary'\nimport { safeEqual } from '@aglyn/tenant-data-admin/server/safe-equal'\nimport {\n AI_INSIGHTS_DIGEST_CRON_ID,\n runAiInsightDigestSweep,\n type AiInsightDigestDeps,\n} from '../insights/ai-insight-digest'\n\n/**\n * The weekly insights' scheduled route (AGL-2915):\n * `POST /api/admin/ai-insights-digest`.\n *\n * Cloud Scheduler calls it at 06:00 and 14:00 UTC through\n * `consoleAiInsightsDigest` in `cloud/functions`, on the console's\n * `CRON_SECRET`: 501 while the secret is unset, 401 without it. Monday's\n * first run makes the week's digests, which the AI jobs beat then writes, and\n * every run after it delivers what is written — see `ai-insight-digest.ts`.\n * `/api/admin/` is the path because the console's edge lets the cron secret's\n * header through there. It stamps `ai-insights-digest` for\n * `/api/health/crons` on every authorized call.\n */\nexport async function POST(request: Request): Promise<Response> {\n if (request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const secret = process.env.CRON_SECRET\n if (!secret) {\n return Response.json({ error: 'The weekly insights are not configured (CRON_SECRET).' }, { status: 501 })\n }\n if (\n !safeEqual(request.headers.get('x-cron-secret'), secret) &&\n !safeEqual(request.headers.get('authorization'), `Bearer ${secret}`)\n ) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n const firestore = firebaseAdmin.app().firestore()\n // The inventory row's id, written out: `cron-beat-wiring.spec.ts` finds a\n // job's stamp by the quoted id beside the call.\n await writeCronBeat(firestore, 'ai-insights-digest' satisfies typeof AI_INSIGHTS_DIGEST_CRON_ID)\n\n let cursor: string | null = null\n try {\n const body = (await request.json()) as { cursor?: unknown } | null\n const raw = body?.cursor\n cursor = typeof raw === 'string' && raw && !raw.includes('/') ? raw : null\n } catch {\n // A bodyless POST is the first call of a run.\n }\n\n try {\n // The platform switch holds the whole run, as it holds the jobs beat.\n if (await featureLockdownRefusal({ feature: 'ai-generate' })) {\n return Response.json({ held: true, done: true, nextCursor: null }, { status: 200 })\n }\n const flags = await getServerReleaseFlagValues()\n const deps: AiInsightDigestDeps = {\n firestore,\n now: new Date(),\n flagValue: flags['release_ai_generative'],\n // The digest's audience: a locked or disabled account is not told\n // (AGL-3418).\n listMembers: async (orgId) => {\n const members = await listOrgMembers(orgId)\n const reachable = new Set(\n await withoutMailWithheldAccounts(members.map((member) => member.$id)),\n )\n return members.filter((member) => reachable.has(member.$id))\n },\n mayGenerate: (orgId, hostId, member) => memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'),\n paused: async (orgId) => Boolean(await featureLockdownRefusal({ feature: 'ai-generate', orgId })),\n notify: (uid, payload) => notifyUsers([uid], { type: 'content.insightsDigest', ...payload }),\n send: async (email) => {\n const recipients = await filterSuppressedEmails([email.to], firestore)\n if (!recipients.length) return { sent: false, rateLimited: false }\n // The `ai-insights-digest` system email (AGL-3367), in the org's brand.\n const content = await renderSystemEmailContent(\n 'ai-insights-digest',\n { 'site.name': email.siteName, 'digest.body': email.text, ...email.merge },\n systemEmailBrand(email.org),\n { subject: email.subject, text: email.text },\n )\n const result = await sendEmail({\n to: recipients,\n ...content,\n fromName: email.fromName,\n context: 'ai-insights-digest',\n priority: 'bulk',\n })\n if (result.sent) {\n await meterPlatformEmail().catch(() => undefined)\n return { sent: true, rateLimited: false }\n }\n return { sent: false, rateLimited: rateLimitedRetryAtMs(result) !== null }\n },\n // An email link must be absolute; with no console URL configured the\n // digest says where to look without one.\n consoleOrigin: (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, ''),\n colors: weeklySummaryEmailColors,\n }\n const report = await runAiInsightDigestSweep(deps, { cursor })\n return Response.json(report, { status: 200 })\n } catch (error) {\n console.error('ai insights digest run failed', error)\n return Response.json({ error: 'The weekly insights run failed' }, { status: 500 })\n }\n}\n"],"names":["writeCronBeat","rateLimitedRetryAtMs","sendEmail","withoutMailWithheldAccounts","filterSuppressedEmails","meterPlatformEmail","firebaseAdmin","featureLockdownRefusal","notifyUsers","renderSystemEmailContent","systemEmailBrand","listOrgMembers","memberHasPermissionOnHost","getServerReleaseFlagValues","weeklySummaryEmailColors","safeEqual","runAiInsightDigestSweep","POST","request","method","Response","json","error","status","secret","process","env","CRON_SECRET","headers","get","firestore","app","cursor","body","raw","includes","feature","held","done","nextCursor","flags","deps","now","Date","flagValue","listMembers","orgId","members","reachable","Set","map","member","$id","filter","has","mayGenerate","hostId","paused","Boolean","notify","uid","payload","type","send","email","recipients","to","length","sent","rateLimited","content","siteName","text","merge","org","subject","result","fromName","context","priority","catch","undefined","consoleOrigin","NEXT_PUBLIC_CONSOLE_URL","trim","replace","colors","report","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,2EAA2E;AAC3E,8EAA8E;AAC9E,kEAAkE;AAElE,SAASA,aAAa,QAAQ,uCAAsC;AACpE,SAASC,oBAAoB,EAAEC,SAAS,QAAQ,2BAA0B;AAC1E,SAASC,2BAA2B,QAAQ,+CAA8C;AAC1F,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,cAAc,EAAEC,yBAAyB,QAAQ,gDAA+C;AACzG,SAASC,0BAA0B,QAAQ,gDAA+C;AAC1F,SAASC,wBAAwB,QAAQ,iDAAgD;AACzF,SAASC,SAAS,QAAQ,6CAA4C;AACtE,SAEEC,uBAAuB,QAElB,mCAA+B;AAEtC;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,KAAKC,OAAgB;IACzC,IAAIA,QAAQC,MAAM,KAAK,QAAQ;QAC7B,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAqB,GAAG;YA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AAGC,OAAO,CAAC,QAAQ;YAClFC,QAAQxE;QACV;QACA,MAAMyE,SAAS,MAAMvE,wBAAwByB,MAAM;YAAET;QAAO;QAC5D,OAAOZ,SAASC,IAAI,CAACkE,QAAQ;YAAEhE,QAAQ;QAAI;IAC7C,EAAE,OAAOD,OAAO;QACdkE,QAAQlE,KAAK,CAAC,iCAAiCA;QAC/C,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiC,GAAG;YAAEC,QAAQ;QAAI;IAClF;AACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -13,7 +14,7 @@
|
|
|
13
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
15
|
* See the License for the specific language governing permissions and
|
|
15
16
|
* limitations under the License.
|
|
16
|
-
*/ import { AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_MAX_CHARS, AI_INSIGHT_MAX_CITED_ROWS, AI_INSIGHT_MAX_CITES, AI_INSIGHT_MAX_INSIGHTS, AI_INSIGHT_MAX_READS } from "../model/ai-insight.js";
|
|
17
|
+
*/ import { AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_HEADLINE_MAX_CHARS, AI_INSIGHT_MAX_CHARS, AI_INSIGHT_MAX_CITED_ROWS, AI_INSIGHT_MAX_CITES, AI_INSIGHT_MAX_INSIGHTS, AI_INSIGHT_MAX_READS } from "../model/ai-insight.js";
|
|
17
18
|
/**
|
|
18
19
|
* The two strict tools an insight job answers through (AGL-2915).
|
|
19
20
|
*
|
|
@@ -98,9 +99,13 @@ export function aiInsightAnswerTool() {
|
|
|
98
99
|
items: {
|
|
99
100
|
type: 'object',
|
|
100
101
|
properties: {
|
|
102
|
+
headline: {
|
|
103
|
+
type: 'string',
|
|
104
|
+
description: `What happened, in a few words, with no full stop; at most ${AI_INSIGHT_HEADLINE_MAX_CHARS} characters.`
|
|
105
|
+
},
|
|
101
106
|
text: {
|
|
102
107
|
type: 'string',
|
|
103
|
-
description: `
|
|
108
|
+
description: `Why it matters, in one or two plain sentences that do not repeat the headline; at most ${AI_INSIGHT_MAX_CHARS} characters.`
|
|
104
109
|
},
|
|
105
110
|
cites: {
|
|
106
111
|
type: 'array',
|
|
@@ -129,6 +134,7 @@ export function aiInsightAnswerTool() {
|
|
|
129
134
|
}
|
|
130
135
|
},
|
|
131
136
|
required: [
|
|
137
|
+
'headline',
|
|
132
138
|
'text',
|
|
133
139
|
'cites'
|
|
134
140
|
],
|
|
@@ -183,7 +189,9 @@ const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.
|
|
|
183
189
|
* — not this reader — decides what an unreadable citation costs.
|
|
184
190
|
*/ export function parseAiInsightAnswer(input) {
|
|
185
191
|
if (!isRecord(input) || !Array.isArray(input['insights'])) return null;
|
|
186
|
-
const insights = input['insights'].filter(isRecord).map((raw)=>({
|
|
192
|
+
const insights = input['insights'].filter(isRecord).map((raw)=>_extends({}, typeof raw['headline'] === 'string' ? {
|
|
193
|
+
headline: raw['headline']
|
|
194
|
+
} : {}, {
|
|
187
195
|
text: typeof raw['text'] === 'string' ? raw['text'] : '',
|
|
188
196
|
cites: (Array.isArray(raw['cites']) ? raw['cites'] : []).filter(isRecord).map((cite)=>({
|
|
189
197
|
table: typeof cite['table'] === 'string' ? cite['table'] : '',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/tools/ai-insight-tool.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AI_INSIGHT_GAP_MAX_CHARS,\n AI_INSIGHT_MAX_CHARS,\n AI_INSIGHT_MAX_CITED_ROWS,\n AI_INSIGHT_MAX_CITES,\n AI_INSIGHT_MAX_INSIGHTS,\n AI_INSIGHT_MAX_READS,\n type AiInsightAnswer,\n} from '../model/ai-insight'\nimport type { AiTool } from '../providers/contract'\n\n/**\n * The two strict tools an insight job answers through (AGL-2915).\n *\n * `read_figures` names readers — an id, a window and the reader's own\n * parameters — and nothing else: the model never writes a query, a field\n * path or a filter of its own, only a choice among the readers the request\n * lists. `submit_insights` is the answer, each insight citing the table rows\n * its figures come from. Lengths and counts are stated in the descriptions,\n * as the platform's other strict tools state them; the step holds every one.\n */\n\nexport const AI_INSIGHT_READ_TOOL_NAME = 'read_figures'\nexport const AI_INSIGHT_ANSWER_TOOL_NAME = 'submit_insights'\n\nexport function aiInsightReadTool(): AiTool {\n return {\n name: AI_INSIGHT_READ_TOOL_NAME,\n description:\n `Choose the readers whose tables answer the question: at most ${AI_INSIGHT_MAX_READS}, ` +\n 'each from the list the request gives. Every field is required.',\n strict: true,\n inputSchema: {\n type: 'object',\n properties: {\n reads: {\n type: 'array',\n description: `The readers to read, most useful first; at most ${AI_INSIGHT_MAX_READS}.`,\n items: {\n type: 'object',\n properties: {\n reader: { type: 'string', description: 'A reader id from the list, exactly as written.' },\n days: {\n type: 'integer',\n description: 'One of the windows that reader lists, in days; 0 for a reader that lists none.',\n },\n params: {\n type: 'array',\n description: 'The parameters that reader lists, by name; empty when it lists none.',\n items: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n value: { type: 'string' },\n },\n required: ['name', 'value'],\n additionalProperties: false,\n },\n },\n },\n required: ['reader', 'days', 'params'],\n additionalProperties: false,\n },\n },\n },\n required: ['reads'],\n additionalProperties: false,\n },\n }\n}\n\nexport function aiInsightAnswerTool(): AiTool {\n return {\n name: AI_INSIGHT_ANSWER_TOOL_NAME,\n description:\n `Answer with at most ${AI_INSIGHT_MAX_INSIGHTS} insights, each citing the table rows its figures come from. ` +\n 'Every field is required.',\n strict: true,\n inputSchema: {\n type: 'object',\n properties: {\n insights: {\n type: 'array',\n description: `Most useful first; at most ${AI_INSIGHT_MAX_INSIGHTS}.`,\n items: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: `One or two plain sentences; at most ${AI_INSIGHT_MAX_CHARS} characters.`,\n },\n cites: {\n type: 'array',\n description: `The tables and rows its figures come from; at most ${AI_INSIGHT_MAX_CITES} tables.`,\n items: {\n type: 'object',\n properties: {\n table: { type: 'string', description: 'The table handle: t1, t2, …' },\n rows: {\n type: 'array',\n description: `Row numbers as the table numbers them, from 0; at most ${AI_INSIGHT_MAX_CITED_ROWS}.`,\n items: { type: 'integer' },\n },\n },\n required: ['table', 'rows'],\n additionalProperties: false,\n },\n },\n },\n required: ['text', 'cites'],\n additionalProperties: false,\n },\n },\n gap: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: `What the tables cannot answer, in one sentence without numbers; at most ${AI_INSIGHT_GAP_MAX_CHARS} characters. null when nothing.`,\n },\n },\n required: ['insights', 'gap'],\n additionalProperties: false,\n },\n }\n}\n\n/** One reader the model asked for, as it asked. */\nexport interface AiInsightReadRequest {\n reader: string\n days: number\n params: Record<string, string>\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The reads a `read_figures` call names, shape-checked and bounded; the step decides which are real. */\nexport function parseAiInsightReads(input: unknown): AiInsightReadRequest[] {\n const reads = isRecord(input) && Array.isArray(input['reads']) ? input['reads'] : []\n const parsed: AiInsightReadRequest[] = []\n for (const raw of reads) {\n if (parsed.length === AI_INSIGHT_MAX_READS) break\n if (!isRecord(raw) || typeof raw['reader'] !== 'string') continue\n const params: Record<string, string> = {}\n for (const pair of Array.isArray(raw['params']) ? raw['params'] : []) {\n if (isRecord(pair) && typeof pair['name'] === 'string' && typeof pair['value'] === 'string') {\n params[pair['name']] = pair['value']\n }\n }\n const days = Number(raw['days'])\n parsed.push({\n reader: raw['reader'].trim(),\n days: Number.isInteger(days) && days >= 0 ? days : 0,\n params,\n })\n }\n return parsed\n}\n\n/**\n * A `submit_insights` call as the trace reads it, or `null` when the call is\n * not an answer at all. Values keep the types the model wrote, so the trace\n * — not this reader — decides what an unreadable citation costs.\n */\nexport function parseAiInsightAnswer(input: unknown): AiInsightAnswer | null {\n if (!isRecord(input) || !Array.isArray(input['insights'])) return null\n const insights = input['insights']\n .filter(isRecord)\n .map((raw) => ({\n text: typeof raw['text'] === 'string' ? raw['text'] : '',\n cites: (Array.isArray(raw['cites']) ? raw['cites'] : []).filter(isRecord).map((cite) => ({\n table: typeof cite['table'] === 'string' ? cite['table'] : '',\n rows: (Array.isArray(cite['rows']) ? cite['rows'] : []) as number[],\n })),\n }))\n const gap = typeof input['gap'] === 'string' ? input['gap'] : null\n return { insights, gap }\n}\n"],"names":["AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_INSIGHTS","AI_INSIGHT_MAX_READS","AI_INSIGHT_READ_TOOL_NAME","AI_INSIGHT_ANSWER_TOOL_NAME","aiInsightReadTool","name","description","strict","inputSchema","type","properties","reads","items","reader","days","params","value","required","additionalProperties","aiInsightAnswerTool","insights","text","cites","table","rows","gap","anyOf","isRecord","Array","isArray","parseAiInsightReads","input","parsed","raw","length","pair","Number","push","trim","isInteger","parseAiInsightAnswer","filter","map","cite"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,oBAAoB,EACpBC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,EACvBC,oBAAoB,QAEf,yBAAqB;AAG5B;;;;;;;;;CASC,GAED,OAAO,MAAMC,4BAA4B,eAAc;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copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AI_INSIGHT_GAP_MAX_CHARS,\n AI_INSIGHT_HEADLINE_MAX_CHARS,\n AI_INSIGHT_MAX_CHARS,\n AI_INSIGHT_MAX_CITED_ROWS,\n AI_INSIGHT_MAX_CITES,\n AI_INSIGHT_MAX_INSIGHTS,\n AI_INSIGHT_MAX_READS,\n type AiInsightAnswer,\n} from '../model/ai-insight'\nimport type { AiTool } from '../providers/contract'\n\n/**\n * The two strict tools an insight job answers through (AGL-2915).\n *\n * `read_figures` names readers — an id, a window and the reader's own\n * parameters — and nothing else: the model never writes a query, a field\n * path or a filter of its own, only a choice among the readers the request\n * lists. `submit_insights` is the answer, each insight citing the table rows\n * its figures come from. Lengths and counts are stated in the descriptions,\n * as the platform's other strict tools state them; the step holds every one.\n */\n\nexport const AI_INSIGHT_READ_TOOL_NAME = 'read_figures'\nexport const AI_INSIGHT_ANSWER_TOOL_NAME = 'submit_insights'\n\nexport function aiInsightReadTool(): AiTool {\n return {\n name: AI_INSIGHT_READ_TOOL_NAME,\n description:\n `Choose the readers whose tables answer the question: at most ${AI_INSIGHT_MAX_READS}, ` +\n 'each from the list the request gives. Every field is required.',\n strict: true,\n inputSchema: {\n type: 'object',\n properties: {\n reads: {\n type: 'array',\n description: `The readers to read, most useful first; at most ${AI_INSIGHT_MAX_READS}.`,\n items: {\n type: 'object',\n properties: {\n reader: { type: 'string', description: 'A reader id from the list, exactly as written.' },\n days: {\n type: 'integer',\n description: 'One of the windows that reader lists, in days; 0 for a reader that lists none.',\n },\n params: {\n type: 'array',\n description: 'The parameters that reader lists, by name; empty when it lists none.',\n items: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n value: { type: 'string' },\n },\n required: ['name', 'value'],\n additionalProperties: false,\n },\n },\n },\n required: ['reader', 'days', 'params'],\n additionalProperties: false,\n },\n },\n },\n required: ['reads'],\n additionalProperties: false,\n },\n }\n}\n\nexport function aiInsightAnswerTool(): AiTool {\n return {\n name: AI_INSIGHT_ANSWER_TOOL_NAME,\n description:\n `Answer with at most ${AI_INSIGHT_MAX_INSIGHTS} insights, each citing the table rows its figures come from. ` +\n 'Every field is required.',\n strict: true,\n inputSchema: {\n type: 'object',\n properties: {\n insights: {\n type: 'array',\n description: `Most useful first; at most ${AI_INSIGHT_MAX_INSIGHTS}.`,\n items: {\n type: 'object',\n properties: {\n headline: {\n type: 'string',\n description: `What happened, in a few words, with no full stop; at most ${AI_INSIGHT_HEADLINE_MAX_CHARS} characters.`,\n },\n text: {\n type: 'string',\n description: `Why it matters, in one or two plain sentences that do not repeat the headline; at most ${AI_INSIGHT_MAX_CHARS} characters.`,\n },\n cites: {\n type: 'array',\n description: `The tables and rows its figures come from; at most ${AI_INSIGHT_MAX_CITES} tables.`,\n items: {\n type: 'object',\n properties: {\n table: { type: 'string', description: 'The table handle: t1, t2, …' },\n rows: {\n type: 'array',\n description: `Row numbers as the table numbers them, from 0; at most ${AI_INSIGHT_MAX_CITED_ROWS}.`,\n items: { type: 'integer' },\n },\n },\n required: ['table', 'rows'],\n additionalProperties: false,\n },\n },\n },\n required: ['headline', 'text', 'cites'],\n additionalProperties: false,\n },\n },\n gap: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: `What the tables cannot answer, in one sentence without numbers; at most ${AI_INSIGHT_GAP_MAX_CHARS} characters. null when nothing.`,\n },\n },\n required: ['insights', 'gap'],\n additionalProperties: false,\n },\n }\n}\n\n/** One reader the model asked for, as it asked. */\nexport interface AiInsightReadRequest {\n reader: string\n days: number\n params: Record<string, string>\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The reads a `read_figures` call names, shape-checked and bounded; the step decides which are real. */\nexport function parseAiInsightReads(input: unknown): AiInsightReadRequest[] {\n const reads = isRecord(input) && Array.isArray(input['reads']) ? input['reads'] : []\n const parsed: AiInsightReadRequest[] = []\n for (const raw of reads) {\n if (parsed.length === AI_INSIGHT_MAX_READS) break\n if (!isRecord(raw) || typeof raw['reader'] !== 'string') continue\n const params: Record<string, string> = {}\n for (const pair of Array.isArray(raw['params']) ? raw['params'] : []) {\n if (isRecord(pair) && typeof pair['name'] === 'string' && typeof pair['value'] === 'string') {\n params[pair['name']] = pair['value']\n }\n }\n const days = Number(raw['days'])\n parsed.push({\n reader: raw['reader'].trim(),\n days: Number.isInteger(days) && days >= 0 ? days : 0,\n params,\n })\n }\n return parsed\n}\n\n/**\n * A `submit_insights` call as the trace reads it, or `null` when the call is\n * not an answer at all. Values keep the types the model wrote, so the trace\n * — not this reader — decides what an unreadable citation costs.\n */\nexport function parseAiInsightAnswer(input: unknown): AiInsightAnswer | null {\n if (!isRecord(input) || !Array.isArray(input['insights'])) return null\n const insights = input['insights']\n .filter(isRecord)\n .map((raw) => ({\n ...(typeof raw['headline'] === 'string' ? { headline: raw['headline'] } : {}),\n text: typeof raw['text'] === 'string' ? raw['text'] : '',\n cites: (Array.isArray(raw['cites']) ? raw['cites'] : []).filter(isRecord).map((cite) => ({\n table: typeof cite['table'] === 'string' ? cite['table'] : '',\n rows: (Array.isArray(cite['rows']) ? cite['rows'] : []) as number[],\n })),\n }))\n const gap = typeof input['gap'] === 'string' ? input['gap'] : null\n return { insights, gap }\n}\n"],"names":["AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_INSIGHTS","AI_INSIGHT_MAX_READS","AI_INSIGHT_READ_TOOL_NAME","AI_INSIGHT_ANSWER_TOOL_NAME","aiInsightReadTool","name","description","strict","inputSchema","type","properties","reads","items","reader","days","params","value","required","additionalProperties","aiInsightAnswerTool","insights","headline","text","cites","table","rows","gap","anyOf","isRecord","Array","isArray","parseAiInsightReads","input","parsed","raw","length","pair","Number","push","trim","isInteger","parseAiInsightAnswer","filter","map","cite"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,6BAA6B,EAC7BC,oBAAoB,EACpBC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,EACvBC,oBAAoB,QAEf,yBAAqB;AAG5B;;;;;;;;;CASC,GAED,OAAO,MAAMC,4BAA4B,eAAc;AACvD,OAAO,MAAMC,8BAA8B,kBAAiB;AAE5D,OAAO,SAASC;IACd,OAAO;QACLC,MAAMH;QACNI,aACE,CAAC,6DAA6D,EAAEL,qBAAqB,EAAE,CAAC,GACxF;QACFM,QAAQ;QACRC,aAAa;YACXC,MAAM;YACNC,YAAY;gBACVC,OAAO;oBACLF,MAAM;oBACNH,aAAa,CAAC,gDAAgD,EAAEL,qBAAqB,CAAC,CAAC;oBACvFW,OAAO;wBACLH,MAAM;wBACNC,YAAY;4BACVG,QAAQ;gCAAEJ,MAAM;gCAAUH,aAAa;4BAAiD;4BACxFQ,MAAM;gCACJL,MAAM;gCACNH,aAAa;4BACf;4BACAS,QAAQ;gCACNN,MAAM;gCACNH,aAAa;gCACbM,OAAO;oCACLH,MAAM;oCACNC,YAAY;wCACVL,MAAM;4CAAEI,MAAM;wCAAS;wCACvBO,OAAO;4CAAEP,MAAM;wCAAS;oCAC1B;oCACAQ,UAAU;wCAAC;wCAAQ;qCAAQ;oCAC3BC,sBAAsB;gCACxB;4BACF;wBACF;wBACAD,UAAU;4BAAC;4BAAU;4BAAQ;yBAAS;wBACtCC,sBAAsB;oBACxB;gBACF;YACF;YACAD,UAAU;gBAAC;aAAQ;YACnBC,sBAAsB;QACxB;IACF;AACF;AA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