@aglyn/plugins-ai 1.5.0 → 1.7.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/README.md +2 -2
- package/package.json +17 -17
- package/src/lib/components/ai-insight-dialog.component.js +14 -0
- package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
- package/src/lib/components/ai-seo-audit-card.component.d.ts +7 -0
- package/src/lib/components/ai-seo-audit-card.component.js +32 -4
- package/src/lib/components/ai-seo-audit-card.component.js.map +1 -1
- package/src/lib/insights/ai-figure-readers.d.ts +13 -0
- package/src/lib/insights/ai-figure-readers.js +158 -11
- package/src/lib/insights/ai-figure-readers.js.map +1 -1
- package/src/lib/insights/ai-figure-summaries.js +4 -2
- package/src/lib/insights/ai-figure-summaries.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +27 -17
- package/src/lib/insights/ai-insight-digest.js +96 -107
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-budget.d.ts +19 -3
- package/src/lib/jobs/ai-job-insight-budget.js +18 -4
- package/src/lib/jobs/ai-job-insight-budget.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +2 -2
- package/src/lib/jobs/ai-job-insight-step.js +17 -7
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/jobs/ai-job-seo-step.d.ts +4 -0
- package/src/lib/jobs/ai-job-seo-step.js +9 -4
- package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
- package/src/lib/jobs/ai-job-settings-step.d.ts +6 -2
- package/src/lib/jobs/ai-job-settings-step.js +45 -6
- package/src/lib/jobs/ai-job-settings-step.js.map +1 -1
- package/src/lib/jobs/ai-site-publish.js +1 -1
- package/src/lib/jobs/ai-site-publish.js.map +1 -1
- package/src/lib/model/ai-insight.d.ts +23 -3
- package/src/lib/model/ai-insight.js +17 -3
- package/src/lib/model/ai-insight.js.map +1 -1
- package/src/lib/model/ai-site-entity.d.ts +4 -4
- package/src/lib/model/ai-site-entity.js +3 -3
- package/src/lib/model/ai-site-entity.js.map +1 -1
- package/src/lib/providers/routing.js +3 -1
- package/src/lib/providers/routing.js.map +1 -1
- package/src/lib/runtime/ai-insight-check.d.ts +7 -0
- package/src/lib/runtime/ai-insight-check.js +111 -27
- package/src/lib/runtime/ai-insight-check.js.map +1 -1
- package/src/lib/tools/ai-insight-tool.js +45 -2
- package/src/lib/tools/ai-insight-tool.js.map +1 -1
|
@@ -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_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,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,UAAY;QACjC,MAAMI,UAAUF,QAAQ,OAAQC,OAAOH,KAAK,CAAC,EAAE,IAAI,KAAKG,OAAOH,KAAK,CAAC,EAAE;QACvE,MAAMK,MAAKL,eAAAA,MAAMM,KAAK,YAAXN,eAAe;QAC1BD,QAAQQ,IAAI,CAAC;YAACF;YAAIA,KAAKL,KAAK,CAAC,E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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_CAUSE_READERS,\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_NEXT_MAX_CHARS,\n AI_INSIGHT_OVERVIEW_MAX_CHARS,\n AI_INSIGHT_WHY_MAX_CHARS,\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 * A digest's overview, and an insight's reason and next step (AGL-4131), are\n * held to the same rows and dropped alone when they fail: the insight stands.\n * A reason must also cite a row of a table that can hold a cause, and a row\n * whose change shows it held steady is not one.\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 /** A digest's read of the week, when it is one a person may read. */\n overview: string | null\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\ninterface CitedFigures {\n cells: CitedCell[]\n labels: string[]\n cited: AiInsightTable[]\n findings: string[]\n}\n\n/** The cells and labels a list of citations opens, and any citation that opens nothing. */\nfunction citedFigures(cites: readonly AiInsightCitation[], tables: readonly AiInsightTable[]): CitedFigures {\n const cells: CitedCell[] = []\n const labels: string[] = []\n const cited: AiInsightTable[] = []\n const findings: string[] = []\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 return { cells, labels, cited, findings }\n}\n\n/** What a piece of writing says that the rows it cites do not: a figure they do not hold, or a direction they deny. */\nfunction numberFindings(text: string, cites: readonly AiInsightCitation[], figures: CitedFigures): string[] {\n const { cells, labels, cited } = figures\n const findings: string[] = []\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\nconst insightCites = (insight: AiInsight): AiInsightCitation[] =>\n Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : []\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 = insightCites(insight)\n if (!cites.length || cites.every((cite) => !Array.isArray(cite?.rows) || !cite.rows.length)) {\n return [...findings, 'insight-no-citation']\n }\n const figures = citedFigures(cites, tables)\n findings.push(...figures.findings)\n if (findings.some((finding) => finding.startsWith('insight-unknown-'))) return findings\n return [...findings, ...numberFindings(text, cites, figures)]\n}\n\n/**\n * A line beside the insights, held to everything an insight is, or `''` with\n * why. It is only dropped: a reason or a next step that cannot be kept says\n * nothing about whether the figures are true (AGL-4131).\n */\nfunction checkedLine(\n value: unknown,\n name: string,\n maxChars: number,\n cites: readonly AiInsightCitation[],\n tables: readonly AiInsightTable[],\n): { line: string; findings: string[] } {\n const line = typeof value === 'string' ? value.replace(/\\s+/g, ' ').trim() : ''\n if (!line) return { line: '', findings: [] }\n const refused = [\n ...(line.length > maxChars ? [`insight-${name}-too-long`] : []),\n ...(MARKUP.test(line) ? [`insight-${name}-markup`] : []),\n ...(hasPersonalDetails(line) ? [`insight-${name}-personal-details`] : []),\n ...numberFindings(line, cites, citedFigures(cites, tables)),\n ]\n return refused.length ? { line: '', findings: refused } : { line, findings: [] }\n}\n\n/**\n * Whether an insight cites a row a reason can rest on: a row of a table that\n * can hold a cause, and one that moved. A source or campaign whose change is 0\n * sent the same traffic as the week before, so it cannot explain a move; a\n * dated change has no change column and always can.\n */\nfunction citesACause(cites: readonly AiInsightCitation[], tables: readonly AiInsightTable[]): boolean {\n return cites.some((cite) => {\n const table = tables.find((candidate) => candidate.ref === cite.table)\n if (!table || !AI_INSIGHT_CAUSE_READERS.includes(table.reader)) return false\n return cite.rows.some((index) => {\n const row = table.rows[index]\n return Boolean(row) && row.change !== 0\n })\n })\n}\n\n/** A next step that promises what it would do is left out: nothing here can know. */\nconst PROMISE = /\\b(?:guarantee[sd]?|sure to|will (?:increase|boost|double|grow|raise|improve|bring|get you|rank))\\b/i\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 const cites = insightCites(insight).map((cite) => ({\n table: cite.table,\n rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS),\n }))\n const why = checkedLine(insight.why, 'why', AI_INSIGHT_WHY_MAX_CHARS, cites, tables)\n const reasoned = why.line && citesACause(cites, tables)\n if (why.line && !reasoned) findings.push('insight-why-no-cause')\n const next = checkedLine(insight.next, 'next', AI_INSIGHT_NEXT_MAX_CHARS, cites, tables)\n const promised = PROMISE.test(next.line)\n if (promised) findings.push('insight-next-promise')\n findings.push(...why.findings, ...next.findings)\n kept.push({\n ...(headline ? { headline } : {}),\n text: insight.text.trim(),\n ...(reasoned ? { why: why.line } : {}),\n ...(next.line && !promised ? { next: next.line } : {}),\n cites,\n })\n }\n })\n const gap = aiInsightGap(answer?.gap)\n if (answer?.gap && !gap) findings.push('insight-gap-unreadable')\n // Held to the rows the kept insights cite: it has no citations of its own,\n // and a figure in it should be one a reader can open just below it.\n const overview = checkedLine(\n answer?.overview,\n 'overview',\n AI_INSIGHT_OVERVIEW_MAX_CHARS,\n kept.flatMap((insight) => insight.cites),\n tables,\n )\n findings.push(...overview.findings)\n return { overview: overview.line || null, kept, left, gap, findings }\n}\n"],"names":["hasPersonalDetails","AI_INSIGHT_CAUSE_READERS","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_NEXT_MAX_CHARS","AI_INSIGHT_OVERVIEW_MAX_CHARS","AI_INSIGHT_WHY_MAX_CHARS","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","citedFigures","cells","cited","findings","find","entry","ref","String","row","isInteger","undefined","column","columns","key","isFinite","part","numberFindings","figures","framing","matched","filter","framed","has","changes","direction","agrees","insightCites","Array","isArray","checkAiInsight","sentences","every","finding","startsWith","checkedLine","name","maxChars","line","refused","citesACause","candidate","includes","reader","Boolean","change","PROMISE","aiInsightGap","gap","checkAiInsightAnswer","answer","insights","kept","left","forEach","own","why","reasoned","next","promised","overview","flatMap"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,wBAAwB,EACxBC,wBAAwB,EACxBC,6BAA6B,EAC7BC,oBAAoB,EACpBC,yBAAyB,EACzBC,oBAAoB,EACpBC,uBAAuB,EACvBC,yBAAyB,EACzBC,6BAA6B,EAC7BC,wBAAwB,QAKnB,yBAAqB;AA2D5B,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,MAAM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IAAI,CAAC;YAC5BmE,SAASnE,IAAI,IAAIuH,IAAIpD,QAAQ,KAAKsD,KAAKtD,QAAQ;YAC/CgD,KAAKnH,IAAI,CAAC,aACJ8D,WAAW;gBAAEA;YAAS,IAAI,CAAC;gBAC/BxE,MAAMuE,QAAQvE,IAAI,CAACyE,IAAI;eACnByD,WAAW;gBAAED,KAAKA,IAAIlB,IAAI;YAAC,IAAI,CAAC,GAChCoB,KAAKpB,IAAI,IAAI,CAACqB,WAAW;gBAAED,MAAMA,KAAKpB,IAAI;YAAC,IAAI,CAAC;gBACpDzE;;QAEJ;IACF;IACA,MAAMmF,MAAMD,aAAaG,0BAAAA,OAAQF,GAAG;IACpC,IAAIE,CAAAA,0BAAAA,OAAQF,GAAG,KAAI,CAACA,KAAK5C,SAASnE,IAAI,CAAC;IACvC,2EAA2E;IAC3E,oEAAoE;IACpE,MAAM2H,WAAWzB,YACfe,0BAAAA,OAAQU,QAAQ,EAChB,YACAnJ,+BACA2I,KAAKS,OAAO,CAAC,CAAC/D,UAAYA,QAAQjC,KAAK,GACvCD;IAEFwC,SAASnE,IAAI,IAAI2H,SAASxD,QAAQ;IAClC,OAAO;QAAEwD,UAAUA,SAAStB,IAAI,IAAI;QAAMc;QAAMC;QAAML;QAAK5C;IAAS;AACtE"}
|
|
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
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
|
+
*/ import { AI_INSIGHT_GAP_MAX_CHARS, AI_INSIGHT_HEADLINE_MAX_CHARS, AI_INSIGHT_NEXT_MAX_CHARS, AI_INSIGHT_OVERVIEW_MAX_CHARS, AI_INSIGHT_WHY_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";
|
|
18
18
|
/**
|
|
19
19
|
* The two strict tools an insight job answers through (AGL-2915).
|
|
20
20
|
*
|
|
@@ -93,6 +93,17 @@ export function aiInsightAnswerTool() {
|
|
|
93
93
|
inputSchema: {
|
|
94
94
|
type: 'object',
|
|
95
95
|
properties: {
|
|
96
|
+
overview: {
|
|
97
|
+
anyOf: [
|
|
98
|
+
{
|
|
99
|
+
type: 'string'
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
type: 'null'
|
|
103
|
+
}
|
|
104
|
+
],
|
|
105
|
+
description: `A weekly digest only: what the week meant, in two or three sentences of your own; at most ${AI_INSIGHT_OVERVIEW_MAX_CHARS} characters. null on a question.`
|
|
106
|
+
},
|
|
96
107
|
insights: {
|
|
97
108
|
type: 'array',
|
|
98
109
|
description: `Most useful first; at most ${AI_INSIGHT_MAX_INSIGHTS}.`,
|
|
@@ -107,6 +118,28 @@ export function aiInsightAnswerTool() {
|
|
|
107
118
|
type: 'string',
|
|
108
119
|
description: `Why it matters, in one or two plain sentences that do not repeat the headline; at most ${AI_INSIGHT_MAX_CHARS} characters.`
|
|
109
120
|
},
|
|
121
|
+
why: {
|
|
122
|
+
anyOf: [
|
|
123
|
+
{
|
|
124
|
+
type: 'string'
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
type: 'null'
|
|
128
|
+
}
|
|
129
|
+
],
|
|
130
|
+
description: `What most likely drove it, resting on a row you cite from the changes, sources or campaigns table; at most ${AI_INSIGHT_WHY_MAX_CHARS} characters. null when nothing there explains it.`
|
|
131
|
+
},
|
|
132
|
+
next: {
|
|
133
|
+
anyOf: [
|
|
134
|
+
{
|
|
135
|
+
type: 'string'
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
type: 'null'
|
|
139
|
+
}
|
|
140
|
+
],
|
|
141
|
+
description: `One concrete step the owner can take; at most ${AI_INSIGHT_NEXT_MAX_CHARS} characters. null when none fits.`
|
|
142
|
+
},
|
|
110
143
|
cites: {
|
|
111
144
|
type: 'array',
|
|
112
145
|
description: `The tables and rows its figures come from; at most ${AI_INSIGHT_MAX_CITES} tables.`,
|
|
@@ -136,6 +169,8 @@ export function aiInsightAnswerTool() {
|
|
|
136
169
|
required: [
|
|
137
170
|
'headline',
|
|
138
171
|
'text',
|
|
172
|
+
'why',
|
|
173
|
+
'next',
|
|
139
174
|
'cites'
|
|
140
175
|
],
|
|
141
176
|
additionalProperties: false
|
|
@@ -154,6 +189,7 @@ export function aiInsightAnswerTool() {
|
|
|
154
189
|
}
|
|
155
190
|
},
|
|
156
191
|
required: [
|
|
192
|
+
'overview',
|
|
157
193
|
'insights',
|
|
158
194
|
'gap'
|
|
159
195
|
],
|
|
@@ -192,14 +228,21 @@ const isRecord = (value)=>typeof value === 'object' && value !== null && !Array.
|
|
|
192
228
|
const insights = input['insights'].filter(isRecord).map((raw)=>_extends({}, typeof raw['headline'] === 'string' ? {
|
|
193
229
|
headline: raw['headline']
|
|
194
230
|
} : {}, {
|
|
195
|
-
text: typeof raw['text'] === 'string' ? raw['text'] : ''
|
|
231
|
+
text: typeof raw['text'] === 'string' ? raw['text'] : ''
|
|
232
|
+
}, typeof raw['why'] === 'string' ? {
|
|
233
|
+
why: raw['why']
|
|
234
|
+
} : {}, typeof raw['next'] === 'string' ? {
|
|
235
|
+
next: raw['next']
|
|
236
|
+
} : {}, {
|
|
196
237
|
cites: (Array.isArray(raw['cites']) ? raw['cites'] : []).filter(isRecord).map((cite)=>({
|
|
197
238
|
table: typeof cite['table'] === 'string' ? cite['table'] : '',
|
|
198
239
|
rows: Array.isArray(cite['rows']) ? cite['rows'] : []
|
|
199
240
|
}))
|
|
200
241
|
}));
|
|
201
242
|
const gap = typeof input['gap'] === 'string' ? input['gap'] : null;
|
|
243
|
+
const overview = typeof input['overview'] === 'string' ? input['overview'] : null;
|
|
202
244
|
return {
|
|
245
|
+
overview,
|
|
203
246
|
insights,
|
|
204
247
|
gap
|
|
205
248
|
};
|
|
@@ -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_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,aA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;;CAIC,GACD,OAAO,SAASQ,qBAAqBT,KAAc;IACjD,IAAI,CAACJ,SAASI,UAAU,CAACH,MAAMC,OAAO,CAACE,KAAK,CAAC,WAAW,GAAG,OAAO;IAClE,MAAMZ,WAAWY,KAAK,CAAC,WAAW,CAC/BU,MAAM,CAACd,UACPe,GAAG,CAAC,CAACT,MAAS,aACT,OAAOA,GAAG,CAAC,WAAW,KAAK,WAAW;YAAEb,UAAUa,GAAG,CAAC,WAAW;QAAC,IAAI,CAAC;YAC3EZ,MAAM,OAAOY,GAAG,CAAC,OAAO,KAAK,WAAWA,GAAG,CAAC,OAAO,GAAG;YACtDX,OAAO,AAACM,CAAAA,MAAMC,OAAO,CAACI,GAAG,CAAC,QAAQ,IAAIA,GAAG,CAAC,QAAQ,GAAG,EAAE,AAAD,EAAGQ,MAAM,CAACd,UAAUe,GAAG,CAAC,CAACC,OAAU,CAAA;oBACvFpB,OAAO,OAAOoB,IAAI,CAAC,QAAQ,KAAK,WAAWA,IAAI,CAAC,QAAQ,GAAG;oBAC3DnB,MAAOI,MAAMC,OAAO,CAACc,IAAI,CAAC,OAAO,IAAIA,IAAI,CAAC,OAAO,GAAG,EAAE;gBACxD,CAAA;;IAEJ,MAAMlB,MAAM,OAAOM,KAAK,CAAC,MAAM,KAAK,WAAWA,KAAK,CAAC,MAAM,GAAG;IAC9D,OAAO;QAAEZ;QAAUM;IAAI;AACzB"}
|
|
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_HEADLINE_MAX_CHARS,\n AI_INSIGHT_NEXT_MAX_CHARS,\n AI_INSIGHT_OVERVIEW_MAX_CHARS,\n AI_INSIGHT_WHY_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 overview: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: `A weekly digest only: what the week meant, in two or three sentences of your own; at most ${AI_INSIGHT_OVERVIEW_MAX_CHARS} characters. null on a question.`,\n },\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 why: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: `What most likely drove it, resting on a row you cite from the changes, sources or campaigns table; at most ${AI_INSIGHT_WHY_MAX_CHARS} characters. null when nothing there explains it.`,\n },\n next: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: `One concrete step the owner can take; at most ${AI_INSIGHT_NEXT_MAX_CHARS} characters. null when none fits.`,\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', 'why', 'next', '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: ['overview', '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 ...(typeof raw['why'] === 'string' ? { why: raw['why'] } : {}),\n ...(typeof raw['next'] === 'string' ? { next: raw['next'] } : {}),\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 const overview = typeof input['overview'] === 'string' ? input['overview'] : null\n return { overview, insights, gap }\n}\n"],"names":["AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_NEXT_MAX_CHARS","AI_INSIGHT_OVERVIEW_MAX_CHARS","AI_INSIGHT_WHY_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","overview","anyOf","insights","headline","text","why","next","cites","table","rows","gap","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,yBAAyB,EACzBC,6BAA6B,EAC7BC,wBAAwB,EACxBC,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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