@aglyn/plugins-ai 1.6.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/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/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/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/providers/routing.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 { AI_SETTING_PLATFORM, AI_STEP_MODEL_SETTING } from '../plugin-config'\nimport {\n AI_MODEL_CATALOG,\n AI_STEP_TIERS,\n aiCatalogEntry,\n aiDefaultModelFor,\n type AiCatalogEntry,\n type AiStepKind,\n} from './catalog'\nimport type { AiEvalKind } from '../runtime/ai-eval'\nimport type { AiEffort, AiProvider, AiThinking } from './contract'\nimport { aiProviderById, defaultAiProvider } from './registry'\n\n/**\n * The routing table (AGL-2937, AGL-2939): step kind → provider and model,\n * through the catalog and never a vendor literal.\n *\n * Precedence, dearest override first:\n *\n * 1. the org's `pluginSettings/ai` — a provider, and a model per step kind\n * that must be one the provider serves;\n * 2. the deployment's environment — `AI_PROVIDER` for the provider,\n * `AI_DEFAULT_MODEL` for every step, and `ASSIST_MODEL` for the\n * assistant alone (the incident-response override the chat door has\n * always honored);\n * 3. the catalog's tier for the step kind on the resolved provider.\n */\n\n/** The environment override for every step kind. */\nexport const AI_DEFAULT_MODEL_ENV = 'AI_DEFAULT_MODEL'\n/** The assistant's own override, honored before the general one. */\nexport const ASSIST_MODEL_ENV = 'ASSIST_MODEL'\n\n/** The org's resolved `pluginSettings/ai` values, as `getPluginConfig` merges them. */\nexport type AiPluginSettings = Record<string, unknown>\n\n/**\n * The model that serves a catalog id (AGL-3781): the id itself, or for a\n * retired row the successor it names, followed to a current row. An id the\n * catalog does not know is returned as it is, for the caller to refuse.\n */\nexport function aiServingModelId(modelId: string): string {\n let current = modelId\n for (let hops = 0; hops < AI_MODEL_CATALOG.length; hops += 1) {\n const successor = aiCatalogEntry(current)?.successor\n if (!successor) return current\n current = successor\n }\n return current\n}\n\nexport interface AiRoute {\n provider: AiProvider\n model: string\n}\n\n/** A settings value that names a real choice, or `undefined` for the platform default. */\nfunction chosen(settings: AiPluginSettings | undefined, key: string): string | undefined {\n const value = settings?.[key]\n return typeof value === 'string' && value && value !== AI_SETTING_PLATFORM\n ? value\n : undefined\n}\n\n/** The provider a workspace runs on: its own choice when registered, else the platform's. */\nexport function resolveAiProvider(settings?: AiPluginSettings): AiProvider | undefined {\n const wanted = chosen(settings, 'provider')\n if (wanted) {\n const named = aiProviderById(wanted)\n if (named) return named\n }\n return defaultAiProvider()\n}\n\n/**\n * The model a step kind runs on for a workspace, on the resolved provider.\n * A chosen model on another provider is not served — the provider decides\n * what it can run — and falls back to the provider's default for the tier.\n */\nexport function resolveAiRoute(\n kind: AiStepKind,\n settings?: AiPluginSettings,\n): AiRoute | undefined {\n const provider = resolveAiProvider(settings)\n if (!provider) return undefined\n // A setting or an override that names a retired model is served by its\n // successor, never by the retired model itself.\n const servedBy = (modelId: string | undefined): string | undefined => {\n const serving = modelId ? aiServingModelId(modelId) : undefined\n return serving && aiCatalogEntry(serving)?.provider === provider.id ? serving : undefined\n }\n const model =\n servedBy(chosen(settings, AI_STEP_MODEL_SETTING[kind])) ??\n (kind === 'assist.chat' ? servedBy(process.env[ASSIST_MODEL_ENV]?.trim()) : undefined) ??\n servedBy(process.env[AI_DEFAULT_MODEL_ENV]?.trim()) ??\n aiDefaultModelFor(provider.id, AI_STEP_TIERS[kind])\n return model ? { provider, model } : undefined\n}\n\n/**\n * What one step kind asks of its model, beside the tier it is served from\n * (`AI_STEP_TIERS` in the catalog): whether it thinks and how hard, its\n * answer ceiling, and the eval score that tier holds on the step's golden\n * briefs (AGL-2937).\n */\nexport interface AiRoutingRow {\n /**\n * `null` sends no setting: the model's own default, which on every current\n * model is adaptive thinking. A row whose ceiling holds the answer alone\n * says `off` (AGL-3781).\n */\n thinking: AiThinking | null\n effort: AiEffort | null\n /** The answer ceiling, thinking included. */\n maxTokens: number\n /** What the ceiling is sized from. */\n maxTokensBasis: string\n eval: AiRoutingEval\n /**\n * How long the step's prompt cache lives (AGL-3830): `1h` on every step a\n * site job runs, in production as in a live run, and the provider's five\n * minutes on a row that leaves it out. A guided start's routes each write\n * their prefix once and read it only inside the job, a beat or more apart,\n * so a five-minute entry is gone before the next job could read it; at an\n * hour the next site job reads what the last one wrote. The write costs 2x\n * the input price instead of 1.25x, so a step no job runs leaves it out.\n * The hour is the SHARED markers' alone (AGL-4050): a site's block and the\n * plan's own conversation are read by one job only, so they keep five\n * minutes on every row (`aiCacheMarkerTtls` in `providers/contract.ts`).\n * Read by `runValidatedGeneration` into the request's `cacheTtl`; a door\n * that sends its own request on the same step (the copy assistant's blog\n * draft) keeps five minutes.\n */\n cacheTtl?: '1h'\n}\n\n/**\n * The cache lifetime every step a site job runs asks for its shared prompt\n * (AGL-3830, AGL-4050): the plan, the look, the header and footer, every page\n * and its listing, the creations, the first posts and products, and the\n * welcome email.\n */\nconst AI_SITE_JOB_CACHE_TTL = '1h' as const\n\nexport interface AiRoutingEval {\n /** The golden-brief kinds the step answers. */\n kinds: readonly AiEvalKind[]\n /** `answers` scores the step's answers; `plans` scores the plans those kinds' answers carry. */\n scores: 'answers' | 'plans'\n /** `authored` while the score is the hand-written references'; `recorded` once a live run records answers. */\n source: 'authored' | 'recorded'\n passRate: number\n /** The mean answer score; `null` for a plan score, which passes or fails. */\n meanScore: number | null\n}\n\n/**\n * THE ROUTING TABLE (AGL-2937): what each step kind asks of the model, in one\n * place, with the evidence beside it.\n *\n * A step runs on the smallest tier that holds its eval floor. A row moves to a\n * cheaper tier, or a lower effort, only when a recorded eval\n * (`npm run eval:ai-live`) holds the floor there; while a row's score is the\n * authored references', it says so, and the row stays where production has\n * run it. `runtime/ai-eval.spec.ts` recomputes every row's score from the\n * harness, so a row cannot claim a score its briefs do not hold.\n *\n * A ceiling is sized from the p95 output the staff signals page reports for\n * the kind once production has served it; until then `maxTokensBasis` names\n * what it is sized from. The same spec holds every reference answer under its\n * row's ceiling at three characters a token, a reading that errs high for a\n * tokenizer that splits finer than four.\n */\nexport const AI_ROUTING_TABLE: Readonly<Record<AiStepKind, AiRoutingRow>> = {\n 'assist.chat': {\n // A scoped, latency-sensitive chat turn: no thinking, the low effort rung.\n thinking: 'off',\n effort: 'low',\n // 2,048 since AGL-4075: a non-Latin script spends two to four times the\n // tokens per character, and 5 of 17 non-English answers stopped at 1,024\n // against 1 of 33 English ones. Output is billed only as it is written.\n maxTokens: 2048,\n maxTokensBasis:\n 'a docs-grounded answer of a few short paragraphs in any language; the edit rung raises it for its tool call',\n eval: { kinds: ['chat'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'copy.element': {\n // One element's copy on the fast tier, whose model thinks unless told not\n // to (AGL-3781): the ceiling holds the copy alone, as it always has, and\n // the effort is the model's own.\n thinking: 'off',\n effort: null,\n maxTokens: 1024,\n maxTokensBasis: 'one element of copy, about the length of the text it replaces',\n eval: { kinds: ['element'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'copy.section': {\n thinking: null,\n effort: null,\n maxTokens: 3000,\n maxTokensBasis: 'a section of four to twelve nodes written as JSON',\n eval: { kinds: ['section'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'copy.blog': {\n thinking: null,\n effort: null,\n maxTokens: 2048,\n maxTokensBasis: 'one blog post body in markdown-lite',\n eval: { kinds: ['blog'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'generate.section': {\n thinking: null,\n effort: null,\n maxTokens: 3000,\n maxTokensBasis: 'a section of four to twelve nodes written as JSON',\n eval: { kinds: ['section'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.layout': {\n // The plan was reasoned out and confirmed before the step, so it writes without thinking.\n // A site's header and footer in the layout language think adaptively, at\n // low since AGL-3781 (`AI_LAYOUT_LANGUAGE_THINKING`): the live round of\n // 2026-10-14 built 13 of 13 frames at low, none cut off.\n thinking: 'off',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis:\n \"tighter than the doctrine's default for a layout, so one step and its re-ask fit the job beat's budget; the tree is held to its rule 17 budget either way\",\n eval: { kinds: ['layout'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.template': {\n // Medium since the golden A/B of 2026-10-14 (AGL-3781): both template\n // briefs passed at medium as at the default, with about a third fewer\n // output tokens.\n thinking: 'off',\n effort: 'medium',\n maxTokens: 8000,\n maxTokensBasis:\n \"tighter than the doctrine's default for a template, so one step and its re-ask fit the job beat's budget; the tree is held to its rule 17 budget either way\",\n eval: { kinds: ['template'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.component': {\n // A component's tree and the properties it declares, in one answer, from a\n // plan reasoned out and confirmed before the step (AGL-2908).\n thinking: 'off',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis:\n \"the ceiling the layout and template steps keep, so one step and its re-ask fit the job beat's budget; the tree is held to its rule 17 budget either way\",\n eval: { kinds: ['component'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.crm': {\n // CRM by AI (AGL-2917): short answers through a strict tool, written from\n // the facts the CRM reports about the record the member opened, with no\n // thinking. The ceiling fits an inline door, so a member is answered in\n // the request that asked, and has no room for thinking: the fast tier's\n // model thinks unless told not to, so the row says off, and its effort\n // is the low one a short answer read off given facts needs (AGL-3781).\n thinking: 'off',\n effort: 'low',\n maxTokens: 700,\n maxTokensBasis:\n \"the largest answer a CRM tool accepts: sixty columns matched to fields by number, or an email draft at its length limits, at three characters a token with room, as ai-job-crm-step.spec.ts measures it\",\n eval: { kinds: ['crm'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9938 },\n },\n 'job.experiment': {\n // Variants of one piece of copy, or a result explained against a verdict\n // code reached before the request was made (AGL-2914). The judgment is\n // already made either way, so it writes without thinking.\n thinking: 'off',\n effort: null,\n maxTokens: 1500,\n maxTokensBasis:\n \"four variants at the tool's own lengths — a name, a headline, a body and a rationale each — written as JSON, about 3,000 characters at three characters a token with room; an explanation is a headline, four sentences and a next step, well under it, as ai-job-experiment-step.spec.ts measures both\",\n eval: { kinds: ['experiment'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.form': {\n // A form's two halves in one answer: the field declaration and the design\n // that renders it, as JSON, with no extended thinking (AGL-2913). The step\n // asks this ceiling, which is the doctrine's own for a form, and registers\n // the time it takes (AGL-3035).\n thinking: 'off',\n effort: null,\n maxTokens: 6000,\n maxTokensBasis:\n \"the largest form the doctrine's output budget admits, a form's fields, its consent and routing declaration and the design that renders them written as JSON at the wordiest golden's characters a stored byte, under it with room; ai-job-form-step.spec.ts measures it\",\n eval: { kinds: ['form'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.insight': {\n // Readers chosen, then their tables phrased (AGL-2915): short sentences\n // over figures code computed, each held to the rows it cites, so no\n // extended thinking. The read call before the answer asks for at most\n // `AI_INSIGHT_READ_MAX_TOKENS` of the same allowance.\n thinking: 'off',\n effort: null,\n maxTokens: 1500,\n maxTokensBasis:\n 'five insights at their 280-character bound, each citing three tables of ten rows, and the gap sentence, written as JSON: about 2,700 characters, under 1,000 tokens at three characters a token, with room',\n eval: { kinds: ['insight'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.page': {\n // One section of a page, written against a plan a member already\n // confirmed, so it writes without thinking (AGL-2907). The ceiling here\n // is the MOST a pass may ask for; each pass sizes its own down from it to\n // what fits the time the job beat can give the step, which on the\n // balanced tier is about half of this. A page in the layout language\n // thinks adaptively, at low since AGL-3781 (`AI_LAYOUT_LANGUAGE_THINKING`):\n // the live round of 2026-10-14 built 39 of 39 pages at low, 64 of 65\n // answers held their rules on the first ask, none cut off.\n thinking: 'off',\n effort: null,\n maxTokens: 2000,\n maxTokensBasis:\n \"a section of a page written as JSON, about forty elements at the step's measured 45 tokens an element; a pass lowers it to the worst case that fits AI_JOB_PAGE_STEP_MINIMUM_MS on the model it runs\",\n eval: { kinds: ['page'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.products': {\n // A product's copy from its name, text and photo, or a store's first\n // products, categories and discounts from a brief (AGL-2916): answers held\n // to the storefront claim rules, written with no extended thinking.\n thinking: 'off',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis:\n \"the largest catalog the tool accepts, twelve proposed products at every bound written as JSON, which the balanced tier asks as much of as fits a beat; one product's copy asks 1,500 and categories with discounts 2,000, as ai-job-products-step.spec.ts measures them\",\n eval: {\n kinds: ['product', 'catalog', 'categories'],\n scores: 'answers',\n source: 'authored',\n passRate: 1,\n meanScore: 0.9922,\n },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.email': {\n // One email design from the email palette, written against the brief with\n // no extended thinking (AGL-2912). A campaign job runs the same\n // generation, so it carries the same ceiling.\n thinking: 'off',\n effort: null,\n maxTokens: 6000,\n maxTokensBasis:\n \"an email's node map written as JSON, with three subject lines and three preheaders beside it\",\n eval: { kinds: ['email'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.campaign': {\n // The campaign job generates its email through the email step, so it is\n // routed identically; the draft campaign it also writes asks nothing of\n // the model (AGL-2912).\n thinking: 'off',\n effort: null,\n maxTokens: 6000,\n maxTokensBasis:\n \"an email's node map written as JSON, with three subject lines and three preheaders beside it\",\n eval: { kinds: ['email'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.workflow': {\n // An automation drafted from a description, or one explained (AGL-2919):\n // which trigger and which steps a description means is the judgment the\n // step sells, so it thinks before it answers.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 4000,\n maxTokensBasis:\n 'the largest automation the tool accepts, 6,000 characters written out as JSON, at three characters a token with as much again to think in, as ai-job-workflow-step.spec.ts measures it',\n eval: { kinds: ['workflow'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.logic': {\n // A site function or variable proposed, or a function explained\n // (AGL-3603): which conditions and arithmetic a description means is the\n // judgment the step sells, so it thinks before it answers.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 3000,\n maxTokensBasis:\n 'the largest function the tool accepts — twelve parameters, twenty-four operations — is far past any description; a function of eight operations is about 2,400 characters of JSON, at three characters a token with as much again to think in, as ai-job-logic-step.spec.ts measures it',\n eval: { kinds: ['logic'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.edit': {\n // A change to a page or a layout the site has (AGL-3616): which elements\n // a request means, on an outline with no selection, is the judgment the\n // step sells, so it thinks before it answers.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 6144,\n maxTokensBasis:\n \"the Assist edit rung's own ceiling for the proposal's tool call (ASSIST_EDIT_MAX_OUTPUT_TOKENS, 4,096: forty new elements written as name/value pairs), with half as much again to think in, as ai-job-edit-step.spec.ts holds it; the whole of it twice, as a re-ask may, still fits one beat on the balanced tier\",\n eval: { kinds: ['edit'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.seo': {\n // A listing written from the page's own text to fixed lengths, sized for\n // the answer alone: no thinking, which the fast tier's model does unless\n // told not to, at the low effort a short bounded answer needs (AGL-3781).\n // The audit's site proposal and fix batches run on the same row.\n thinking: 'off',\n effort: 'low',\n maxTokens: 1024,\n maxTokensBasis:\n \"the largest listing the tool accepts, at three characters a token with a quarter again, as ai-job-seo-step.spec.ts measures it; an audit's site proposal and fix batches keep ceilings of their own, measured the same way\",\n eval: { kinds: ['seo'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.text': {\n // Low since the golden A/B of 2026-10-14 (AGL-3781): the tagline brief\n // passed at low, its copy scored higher than at the default.\n thinking: 'adaptive',\n effort: 'low',\n maxTokens: 1024,\n maxTokensBasis: 'a few paragraphs of copy; a brief asking for more gets a draft to extend',\n eval: { kinds: ['text'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.theme': {\n // Medium since the golden A/B of 2026-10-14 (AGL-3781): the theme brief\n // passed at medium with the default's scores and half its output tokens.\n // A site start's look runs its own setting (`ai-job-site-look.ts`).\n thinking: 'adaptive',\n effort: 'medium',\n maxTokens: 8000,\n maxTokensBasis:\n 'the largest answer the theme tool accepts, about 2,500 tokens of JSON as ai-job-theme-step.spec.ts measures it, with as much again to think in',\n eval: { kinds: ['theme'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.plan': {\n // A site's plan is an outline written without thinking (AGL-3594), and a\n // paid site's asks medium (`AI_PAID_SITE_PLAN_EFFORT`, AGL-3781): the live\n // round of 2026-10-14 planned 11 of 11 paid site briefs at medium in 16\n // attempts to the default's 22, $0.129 to $0.164, with no refusal and no\n // rule broken. Every other plan, and a Free site's on the fast tier, asks\n // this row's effort — the model's default — until a round holds it lower.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis: 'a plan of up to twelve screens with sixteen sections each, with room to think',\n eval: {\n kinds: ['page', 'template', 'component', 'layout', 'form'],\n scores: 'plans',\n source: 'authored',\n passRate: 1,\n meanScore: null,\n },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n}\n\n/**\n * What a step kind's row asks of its model, as the fields a request carries:\n * only those the row names, so a row that names none sends none and the\n * model's own default stands.\n */\nexport function aiRouteSettings(kind: AiStepKind): { thinking?: AiThinking; effort?: AiEffort } {\n const row = AI_ROUTING_TABLE[kind]\n return {\n ...(row.thinking ? { thinking: row.thinking } : {}),\n ...(row.effort ? { effort: row.effort } : {}),\n }\n}\n\nconst TIER_RANK: Readonly<Record<AiCatalogEntry['tier'], number>> = { fast: 0, balanced: 1, deep: 2 }\n\n/**\n * The model a step runs on held to at least the step's own tier (AGL-4107):\n * `chosen`, the model the job's switch picked, where it serves the step's\n * tier or a higher one; else the provider's own model of that tier. The\n * deployment's `AI_DEFAULT_MODEL` names a model for EVERY step, so a smaller\n * one named there served the balanced step a page brought in asks its design\n * of, and laid the 10/29 import out wrong. A step this holds keeps its tier\n * whatever the environment says; one the catalog does not know is the\n * provider's own model of the tier.\n */\nexport function aiModelAtLeastStepTier(kind: AiStepKind, chosen: string | undefined, settings?: AiPluginSettings): string {\n const tier = AI_STEP_TIERS[kind]\n const provider = resolveAiProvider(settings)\n const serving = chosen ? aiCatalogEntry(aiServingModelId(chosen)) : undefined\n if (serving && (!provider || serving.provider === provider.id) && TIER_RANK[serving.tier] >= TIER_RANK[tier]) return serving.id\n const floor = provider ? aiDefaultModelFor(provider.id, tier) : undefined\n return floor ?? chosen ?? aiModelForStep(kind, settings)\n}\n\n/** The model id alone — what a door records on the meter and the job. */\nexport function aiModelForStep(kind: AiStepKind, settings?: AiPluginSettings): string {\n const route = resolveAiRoute(kind, settings)\n if (!route) {\n // Every door gates on the provider being configured before it asks\n // for a model, so this is a wiring fault rather than a customer path.\n throw new Error('no AI provider is registered')\n }\n return route.model\n}\n"],"names":["AI_SETTING_PLATFORM","AI_STEP_MODEL_SETTING","AI_MODEL_CATALOG","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","aiProviderById","defaultAiProvider","AI_DEFAULT_MODEL_ENV","ASSIST_MODEL_ENV","aiServingModelId","modelId","current","hops","length","successor","chosen","settings","key","value","undefined","resolveAiProvider","wanted","named","resolveAiRoute","kind","servedBy","process","provider","serving","id","model","env","trim","AI_SITE_JOB_CACHE_TTL","AI_ROUTING_TABLE","thinking","effort","maxTokens","maxTokensBasis","eval","kinds","scores","source","passRate","meanScore","cacheTtl","aiRouteSettings","row","TIER_RANK","fast","balanced","deep","aiModelAtLeastStepTier","floor","tier","aiModelForStep","route","Error"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,EAAEC,qBAAqB,QAAQ,sBAAkB;AAC7E,SACEC,gBAAgB,EAChBC,aAAa,EACbC,cAAc,EACdC,iBAAiB,QAGZ,eAAW;AAGlB,SAASC,cAAc,EAAEC,iBAAiB,QAAQ,gBAAY;AAE9D;;;;;;;;;;;;;CAaC,GAED,kDAAkD,GAClD,OAAO,MAAMC,uBAAuB,mBAAkB;AACtD,kEAAkE,GAClE,OAAO,MAAMC,mBAAmB,eAAc;AAK9C;;;;CAIC,GACD,OAAO,SAASC,iBAAiBC,OAAe;IAC9C,IAAIC,UAAUD;IACd,IAAK,IAAIE,OAAO,GAAGA,OAAOX,iBAAiBY,MAAM,EAAED,QAAQ,EAAG;YAC1CT;QAAlB,MAAMW,aAAYX,kBAAAA,eAAeQ,6BAAfR,gBAAyBW,SAAS;QACpD,IAAI,CAACA,WAAW,OAAOH;QACvBA,UAAUG;IACZ;IACA,OAAOH;AACT;AAOA,wFAAwF,GACxF,SAASI,OAAOC,QAAsC,EAAEC,GAAW;IACjE,MAAMC,QAAQF,4BAAAA,QAAU,CAACC,IAAI;IAC7B,OAAO,OAAOC,UAAU,YAAYA,SAASA,UAAUnB,sBACnDmB,QACAC;AACN;AAEA,2FAA2F,GAC3F,OAAO,SAASC,kBAAkBJ,QAA2B;IAC3D,MAAMK,SAASN,OAAOC,UAAU;IAChC,IAAIK,QAAQ;QACV,MAAMC,QAAQjB,eAAegB;QAC7B,IAAIC,OAAO,OAAOA;IACpB;IACA,OAAOhB;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASiB,eACdC,IAAgB,EAChBR,QAA2B;QAWzBS,MAAAA,OAAAA;QACmCC,+BAC1BA;IAXX,MAAMC,WAAWP,kBAAkBJ;IACnC,IAAI,CAACW,UAAU,OAAOR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;AAE/C;AAEA,MAAMY,YAA8D;IAAEC,MAAM;IAAGC,UAAU;IAAGC,MAAM;AAAE;AAEpG;;;;;;;;;CASC,GACD,OAAO,SAASC,uBAAuB5B,IAAgB,EAAET,MAA0B,EAAEC,QAA2B;QAMvGqC;IALP,MAAMC,OAAOpD,aAAa,CAACsB,KAAK;IAChC,MAAMG,WAAWP,kBAAkBJ;IACnC,MAAMY,UAAUb,SAASZ,eAAeM,iBAAiBM,WAAWI;IACpE,IAAIS,WAAY,CAAA,CAACD,YAAYC,QAAQD,QAAQ,KAAKA,SAASE,EAAE,AAAD,KAAMmB,SAAS,CAACpB,QAAQ0B,IAAI,CAAC,IAAIN,SAAS,CAACM,KAAK,EAAE,OAAO1B,QAAQC,EAAE;IAC/H,MAAMwB,QAAQ1B,WAAWvB,kBAAkBuB,SAASE,EAAE,EAAEyB,QAAQnC;IAChE,QAAOkC,OAAAA,gBAAAA,QAAStC,kBAATsC,OAAmBE,eAAe/B,MAAMR;AACjD;AAEA,uEAAuE,GACvE,OAAO,SAASuC,eAAe/B,IAAgB,EAAER,QAA2B;IAC1E,MAAMwC,QAAQjC,eAAeC,MAAMR;IACnC,IAAI,CAACwC,OAAO;QACV,mEAAmE;QACnE,sEAAsE;QACtE,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD,MAAM1B,KAAK;AACpB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/providers/routing.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 { AI_SETTING_PLATFORM, AI_STEP_MODEL_SETTING } from '../plugin-config'\nimport {\n AI_MODEL_CATALOG,\n AI_STEP_TIERS,\n aiCatalogEntry,\n aiDefaultModelFor,\n type AiCatalogEntry,\n type AiStepKind,\n} from './catalog'\nimport type { AiEvalKind } from '../runtime/ai-eval'\nimport type { AiEffort, AiProvider, AiThinking } from './contract'\nimport { aiProviderById, defaultAiProvider } from './registry'\n\n/**\n * The routing table (AGL-2937, AGL-2939): step kind → provider and model,\n * through the catalog and never a vendor literal.\n *\n * Precedence, dearest override first:\n *\n * 1. the org's `pluginSettings/ai` — a provider, and a model per step kind\n * that must be one the provider serves;\n * 2. the deployment's environment — `AI_PROVIDER` for the provider,\n * `AI_DEFAULT_MODEL` for every step, and `ASSIST_MODEL` for the\n * assistant alone (the incident-response override the chat door has\n * always honored);\n * 3. the catalog's tier for the step kind on the resolved provider.\n */\n\n/** The environment override for every step kind. */\nexport const AI_DEFAULT_MODEL_ENV = 'AI_DEFAULT_MODEL'\n/** The assistant's own override, honored before the general one. */\nexport const ASSIST_MODEL_ENV = 'ASSIST_MODEL'\n\n/** The org's resolved `pluginSettings/ai` values, as `getPluginConfig` merges them. */\nexport type AiPluginSettings = Record<string, unknown>\n\n/**\n * The model that serves a catalog id (AGL-3781): the id itself, or for a\n * retired row the successor it names, followed to a current row. An id the\n * catalog does not know is returned as it is, for the caller to refuse.\n */\nexport function aiServingModelId(modelId: string): string {\n let current = modelId\n for (let hops = 0; hops < AI_MODEL_CATALOG.length; hops += 1) {\n const successor = aiCatalogEntry(current)?.successor\n if (!successor) return current\n current = successor\n }\n return current\n}\n\nexport interface AiRoute {\n provider: AiProvider\n model: string\n}\n\n/** A settings value that names a real choice, or `undefined` for the platform default. */\nfunction chosen(settings: AiPluginSettings | undefined, key: string): string | undefined {\n const value = settings?.[key]\n return typeof value === 'string' && value && value !== AI_SETTING_PLATFORM\n ? value\n : undefined\n}\n\n/** The provider a workspace runs on: its own choice when registered, else the platform's. */\nexport function resolveAiProvider(settings?: AiPluginSettings): AiProvider | undefined {\n const wanted = chosen(settings, 'provider')\n if (wanted) {\n const named = aiProviderById(wanted)\n if (named) return named\n }\n return defaultAiProvider()\n}\n\n/**\n * The model a step kind runs on for a workspace, on the resolved provider.\n * A chosen model on another provider is not served — the provider decides\n * what it can run — and falls back to the provider's default for the tier.\n */\nexport function resolveAiRoute(\n kind: AiStepKind,\n settings?: AiPluginSettings,\n): AiRoute | undefined {\n const provider = resolveAiProvider(settings)\n if (!provider) return undefined\n // A setting or an override that names a retired model is served by its\n // successor, never by the retired model itself.\n const servedBy = (modelId: string | undefined): string | undefined => {\n const serving = modelId ? aiServingModelId(modelId) : undefined\n return serving && aiCatalogEntry(serving)?.provider === provider.id ? serving : undefined\n }\n const model =\n servedBy(chosen(settings, AI_STEP_MODEL_SETTING[kind])) ??\n (kind === 'assist.chat' ? servedBy(process.env[ASSIST_MODEL_ENV]?.trim()) : undefined) ??\n servedBy(process.env[AI_DEFAULT_MODEL_ENV]?.trim()) ??\n aiDefaultModelFor(provider.id, AI_STEP_TIERS[kind])\n return model ? { provider, model } : undefined\n}\n\n/**\n * What one step kind asks of its model, beside the tier it is served from\n * (`AI_STEP_TIERS` in the catalog): whether it thinks and how hard, its\n * answer ceiling, and the eval score that tier holds on the step's golden\n * briefs (AGL-2937).\n */\nexport interface AiRoutingRow {\n /**\n * `null` sends no setting: the model's own default, which on every current\n * model is adaptive thinking. A row whose ceiling holds the answer alone\n * says `off` (AGL-3781).\n */\n thinking: AiThinking | null\n effort: AiEffort | null\n /** The answer ceiling, thinking included. */\n maxTokens: number\n /** What the ceiling is sized from. */\n maxTokensBasis: string\n eval: AiRoutingEval\n /**\n * How long the step's prompt cache lives (AGL-3830): `1h` on every step a\n * site job runs, in production as in a live run, and the provider's five\n * minutes on a row that leaves it out. A guided start's routes each write\n * their prefix once and read it only inside the job, a beat or more apart,\n * so a five-minute entry is gone before the next job could read it; at an\n * hour the next site job reads what the last one wrote. The write costs 2x\n * the input price instead of 1.25x, so a step no job runs leaves it out.\n * The hour is the SHARED markers' alone (AGL-4050): a site's block and the\n * plan's own conversation are read by one job only, so they keep five\n * minutes on every row (`aiCacheMarkerTtls` in `providers/contract.ts`).\n * Read by `runValidatedGeneration` into the request's `cacheTtl`; a door\n * that sends its own request on the same step (the copy assistant's blog\n * draft) keeps five minutes.\n */\n cacheTtl?: '1h'\n}\n\n/**\n * The cache lifetime every step a site job runs asks for its shared prompt\n * (AGL-3830, AGL-4050): the plan, the look, the header and footer, every page\n * and its listing, the creations, the first posts and products, and the\n * welcome email.\n */\nconst AI_SITE_JOB_CACHE_TTL = '1h' as const\n\nexport interface AiRoutingEval {\n /** The golden-brief kinds the step answers. */\n kinds: readonly AiEvalKind[]\n /** `answers` scores the step's answers; `plans` scores the plans those kinds' answers carry. */\n scores: 'answers' | 'plans'\n /** `authored` while the score is the hand-written references'; `recorded` once a live run records answers. */\n source: 'authored' | 'recorded'\n passRate: number\n /** The mean answer score; `null` for a plan score, which passes or fails. */\n meanScore: number | null\n}\n\n/**\n * THE ROUTING TABLE (AGL-2937): what each step kind asks of the model, in one\n * place, with the evidence beside it.\n *\n * A step runs on the smallest tier that holds its eval floor. A row moves to a\n * cheaper tier, or a lower effort, only when a recorded eval\n * (`npm run eval:ai-live`) holds the floor there; while a row's score is the\n * authored references', it says so, and the row stays where production has\n * run it. `runtime/ai-eval.spec.ts` recomputes every row's score from the\n * harness, so a row cannot claim a score its briefs do not hold.\n *\n * A ceiling is sized from the p95 output the staff signals page reports for\n * the kind once production has served it; until then `maxTokensBasis` names\n * what it is sized from. The same spec holds every reference answer under its\n * row's ceiling at three characters a token, a reading that errs high for a\n * tokenizer that splits finer than four.\n */\nexport const AI_ROUTING_TABLE: Readonly<Record<AiStepKind, AiRoutingRow>> = {\n 'assist.chat': {\n // A scoped, latency-sensitive chat turn: no thinking, the low effort rung.\n thinking: 'off',\n effort: 'low',\n // 2,048 since AGL-4075: a non-Latin script spends two to four times the\n // tokens per character, and 5 of 17 non-English answers stopped at 1,024\n // against 1 of 33 English ones. Output is billed only as it is written.\n maxTokens: 2048,\n maxTokensBasis:\n 'a docs-grounded answer of a few short paragraphs in any language; the edit rung raises it for its tool call',\n eval: { kinds: ['chat'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'copy.element': {\n // One element's copy on the fast tier, whose model thinks unless told not\n // to (AGL-3781): the ceiling holds the copy alone, as it always has, and\n // the effort is the model's own.\n thinking: 'off',\n effort: null,\n maxTokens: 1024,\n maxTokensBasis: 'one element of copy, about the length of the text it replaces',\n eval: { kinds: ['element'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'copy.section': {\n thinking: null,\n effort: null,\n maxTokens: 3000,\n maxTokensBasis: 'a section of four to twelve nodes written as JSON',\n eval: { kinds: ['section'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'copy.blog': {\n thinking: null,\n effort: null,\n maxTokens: 2048,\n maxTokensBasis: 'one blog post body in markdown-lite',\n eval: { kinds: ['blog'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'generate.section': {\n thinking: null,\n effort: null,\n maxTokens: 3000,\n maxTokensBasis: 'a section of four to twelve nodes written as JSON',\n eval: { kinds: ['section'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.layout': {\n // The plan was reasoned out and confirmed before the step, so it writes without thinking.\n // A site's header and footer in the layout language think adaptively, at\n // low since AGL-3781 (`AI_LAYOUT_LANGUAGE_THINKING`): the live round of\n // 2026-10-14 built 13 of 13 frames at low, none cut off.\n thinking: 'off',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis:\n \"tighter than the doctrine's default for a layout, so one step and its re-ask fit the job beat's budget; the tree is held to its rule 17 budget either way\",\n eval: { kinds: ['layout'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.template': {\n // Medium since the golden A/B of 2026-10-14 (AGL-3781): both template\n // briefs passed at medium as at the default, with about a third fewer\n // output tokens.\n thinking: 'off',\n effort: 'medium',\n maxTokens: 8000,\n maxTokensBasis:\n \"tighter than the doctrine's default for a template, so one step and its re-ask fit the job beat's budget; the tree is held to its rule 17 budget either way\",\n eval: { kinds: ['template'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.component': {\n // A component's tree and the properties it declares, in one answer, from a\n // plan reasoned out and confirmed before the step (AGL-2908).\n thinking: 'off',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis:\n \"the ceiling the layout and template steps keep, so one step and its re-ask fit the job beat's budget; the tree is held to its rule 17 budget either way\",\n eval: { kinds: ['component'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.crm': {\n // CRM by AI (AGL-2917): short answers through a strict tool, written from\n // the facts the CRM reports about the record the member opened, with no\n // thinking. The ceiling fits an inline door, so a member is answered in\n // the request that asked, and has no room for thinking: the fast tier's\n // model thinks unless told not to, so the row says off, and its effort\n // is the low one a short answer read off given facts needs (AGL-3781).\n thinking: 'off',\n effort: 'low',\n maxTokens: 700,\n maxTokensBasis:\n \"the largest answer a CRM tool accepts: sixty columns matched to fields by number, or an email draft at its length limits, at three characters a token with room, as ai-job-crm-step.spec.ts measures it\",\n eval: { kinds: ['crm'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9938 },\n },\n 'job.experiment': {\n // Variants of one piece of copy, or a result explained against a verdict\n // code reached before the request was made (AGL-2914). The judgment is\n // already made either way, so it writes without thinking.\n thinking: 'off',\n effort: null,\n maxTokens: 1500,\n maxTokensBasis:\n \"four variants at the tool's own lengths — a name, a headline, a body and a rationale each — written as JSON, about 3,000 characters at three characters a token with room; an explanation is a headline, four sentences and a next step, well under it, as ai-job-experiment-step.spec.ts measures both\",\n eval: { kinds: ['experiment'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.form': {\n // A form's two halves in one answer: the field declaration and the design\n // that renders it, as JSON, with no extended thinking (AGL-2913). The step\n // asks this ceiling, which is the doctrine's own for a form, and registers\n // the time it takes (AGL-3035).\n thinking: 'off',\n effort: null,\n maxTokens: 6000,\n maxTokensBasis:\n \"the largest form the doctrine's output budget admits, a form's fields, its consent and routing declaration and the design that renders them written as JSON at the wordiest golden's characters a stored byte, under it with room; ai-job-form-step.spec.ts measures it\",\n eval: { kinds: ['form'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.insight': {\n // Readers chosen, then their tables phrased (AGL-2915): short sentences\n // over figures code computed, each held to the rows it cites, so no\n // extended thinking. The read call before the answer asks for at most\n // `AI_INSIGHT_READ_MAX_TOKENS` of the same allowance. A weekly digest is the\n // exception (AGL-4131): it reasons about why a week moved, so it thinks on\n // a ceiling of its own (`AI_INSIGHT_DIGEST_THINKING` in the insight budget).\n thinking: 'off',\n effort: null,\n maxTokens: 1500,\n maxTokensBasis:\n 'five insights at their 280-character bound, each citing three tables of ten rows, and the gap sentence, written as JSON: about 2,700 characters, under 1,000 tokens at three characters a token, with room',\n eval: { kinds: ['insight'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.page': {\n // One section of a page, written against a plan a member already\n // confirmed, so it writes without thinking (AGL-2907). The ceiling here\n // is the MOST a pass may ask for; each pass sizes its own down from it to\n // what fits the time the job beat can give the step, which on the\n // balanced tier is about half of this. A page in the layout language\n // thinks adaptively, at low since AGL-3781 (`AI_LAYOUT_LANGUAGE_THINKING`):\n // the live round of 2026-10-14 built 39 of 39 pages at low, 64 of 65\n // answers held their rules on the first ask, none cut off.\n thinking: 'off',\n effort: null,\n maxTokens: 2000,\n maxTokensBasis:\n \"a section of a page written as JSON, about forty elements at the step's measured 45 tokens an element; a pass lowers it to the worst case that fits AI_JOB_PAGE_STEP_MINIMUM_MS on the model it runs\",\n eval: { kinds: ['page'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9833 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.products': {\n // A product's copy from its name, text and photo, or a store's first\n // products, categories and discounts from a brief (AGL-2916): answers held\n // to the storefront claim rules, written with no extended thinking.\n thinking: 'off',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis:\n \"the largest catalog the tool accepts, twelve proposed products at every bound written as JSON, which the balanced tier asks as much of as fits a beat; one product's copy asks 1,500 and categories with discounts 2,000, as ai-job-products-step.spec.ts measures them\",\n eval: {\n kinds: ['product', 'catalog', 'categories'],\n scores: 'answers',\n source: 'authored',\n passRate: 1,\n meanScore: 0.9922,\n },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.email': {\n // One email design from the email palette, written against the brief with\n // no extended thinking (AGL-2912). A campaign job runs the same\n // generation, so it carries the same ceiling.\n thinking: 'off',\n effort: null,\n maxTokens: 6000,\n maxTokensBasis:\n \"an email's node map written as JSON, with three subject lines and three preheaders beside it\",\n eval: { kinds: ['email'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.campaign': {\n // The campaign job generates its email through the email step, so it is\n // routed identically; the draft campaign it also writes asks nothing of\n // the model (AGL-2912).\n thinking: 'off',\n effort: null,\n maxTokens: 6000,\n maxTokensBasis:\n \"an email's node map written as JSON, with three subject lines and three preheaders beside it\",\n eval: { kinds: ['email'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.workflow': {\n // An automation drafted from a description, or one explained (AGL-2919):\n // which trigger and which steps a description means is the judgment the\n // step sells, so it thinks before it answers.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 4000,\n maxTokensBasis:\n 'the largest automation the tool accepts, 6,000 characters written out as JSON, at three characters a token with as much again to think in, as ai-job-workflow-step.spec.ts measures it',\n eval: { kinds: ['workflow'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n },\n 'job.logic': {\n // A site function or variable proposed, or a function explained\n // (AGL-3603): which conditions and arithmetic a description means is the\n // judgment the step sells, so it thinks before it answers.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 3000,\n maxTokensBasis:\n 'the largest function the tool accepts — twelve parameters, twenty-four operations — is far past any description; a function of eight operations is about 2,400 characters of JSON, at three characters a token with as much again to think in, as ai-job-logic-step.spec.ts measures it',\n eval: { kinds: ['logic'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.edit': {\n // A change to a page or a layout the site has (AGL-3616): which elements\n // a request means, on an outline with no selection, is the judgment the\n // step sells, so it thinks before it answers.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 6144,\n maxTokensBasis:\n \"the Assist edit rung's own ceiling for the proposal's tool call (ASSIST_EDIT_MAX_OUTPUT_TOKENS, 4,096: forty new elements written as name/value pairs), with half as much again to think in, as ai-job-edit-step.spec.ts holds it; the whole of it twice, as a re-ask may, still fits one beat on the balanced tier\",\n eval: { kinds: ['edit'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.seo': {\n // A listing written from the page's own text to fixed lengths, sized for\n // the answer alone: no thinking, which the fast tier's model does unless\n // told not to, at the low effort a short bounded answer needs (AGL-3781).\n // The audit's site proposal and fix batches run on the same row.\n thinking: 'off',\n effort: 'low',\n maxTokens: 1024,\n maxTokensBasis:\n \"the largest listing the tool accepts, at three characters a token with a quarter again, as ai-job-seo-step.spec.ts measures it; an audit's site proposal and fix batches keep ceilings of their own, measured the same way\",\n eval: { kinds: ['seo'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.text': {\n // Low since the golden A/B of 2026-10-14 (AGL-3781): the tagline brief\n // passed at low, its copy scored higher than at the default.\n thinking: 'adaptive',\n effort: 'low',\n maxTokens: 1024,\n maxTokensBasis: 'a few paragraphs of copy; a brief asking for more gets a draft to extend',\n eval: { kinds: ['text'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 1 },\n },\n 'job.theme': {\n // Medium since the golden A/B of 2026-10-14 (AGL-3781): the theme brief\n // passed at medium with the default's scores and half its output tokens.\n // A site start's look runs its own setting (`ai-job-site-look.ts`).\n thinking: 'adaptive',\n effort: 'medium',\n maxTokens: 8000,\n maxTokensBasis:\n 'the largest answer the theme tool accepts, about 2,500 tokens of JSON as ai-job-theme-step.spec.ts measures it, with as much again to think in',\n eval: { kinds: ['theme'], scores: 'answers', source: 'authored', passRate: 1, meanScore: 0.9688 },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n 'job.plan': {\n // A site's plan is an outline written without thinking (AGL-3594), and a\n // paid site's asks medium (`AI_PAID_SITE_PLAN_EFFORT`, AGL-3781): the live\n // round of 2026-10-14 planned 11 of 11 paid site briefs at medium in 16\n // attempts to the default's 22, $0.129 to $0.164, with no refusal and no\n // rule broken. Every other plan, and a Free site's on the fast tier, asks\n // this row's effort — the model's default — until a round holds it lower.\n thinking: 'adaptive',\n effort: null,\n maxTokens: 8000,\n maxTokensBasis: 'a plan of up to twelve screens with sixteen sections each, with room to think',\n eval: {\n kinds: ['page', 'template', 'component', 'layout', 'form'],\n scores: 'plans',\n source: 'authored',\n passRate: 1,\n meanScore: null,\n },\n cacheTtl: AI_SITE_JOB_CACHE_TTL,\n },\n}\n\n/**\n * What a step kind's row asks of its model, as the fields a request carries:\n * only those the row names, so a row that names none sends none and the\n * model's own default stands.\n */\nexport function aiRouteSettings(kind: AiStepKind): { thinking?: AiThinking; effort?: AiEffort } {\n const row = AI_ROUTING_TABLE[kind]\n return {\n ...(row.thinking ? { thinking: row.thinking } : {}),\n ...(row.effort ? { effort: row.effort } : {}),\n }\n}\n\nconst TIER_RANK: Readonly<Record<AiCatalogEntry['tier'], number>> = { fast: 0, balanced: 1, deep: 2 }\n\n/**\n * The model a step runs on held to at least the step's own tier (AGL-4107):\n * `chosen`, the model the job's switch picked, where it serves the step's\n * tier or a higher one; else the provider's own model of that tier. The\n * deployment's `AI_DEFAULT_MODEL` names a model for EVERY step, so a smaller\n * one named there served the balanced step a page brought in asks its design\n * of, and laid the 10/29 import out wrong. A step this holds keeps its tier\n * whatever the environment says; one the catalog does not know is the\n * provider's own model of the tier.\n */\nexport function aiModelAtLeastStepTier(kind: AiStepKind, chosen: string | undefined, settings?: AiPluginSettings): string {\n const tier = AI_STEP_TIERS[kind]\n const provider = resolveAiProvider(settings)\n const serving = chosen ? aiCatalogEntry(aiServingModelId(chosen)) : undefined\n if (serving && (!provider || serving.provider === provider.id) && TIER_RANK[serving.tier] >= TIER_RANK[tier]) return serving.id\n const floor = provider ? aiDefaultModelFor(provider.id, tier) : undefined\n return floor ?? chosen ?? aiModelForStep(kind, settings)\n}\n\n/** The model id alone — what a door records on the meter and the job. */\nexport function aiModelForStep(kind: AiStepKind, settings?: AiPluginSettings): string {\n const route = resolveAiRoute(kind, settings)\n if (!route) {\n // Every door gates on the provider being configured before it asks\n // for a model, so this is a wiring fault rather than a customer path.\n throw new Error('no AI provider is registered')\n }\n return route.model\n}\n"],"names":["AI_SETTING_PLATFORM","AI_STEP_MODEL_SETTING","AI_MODEL_CATALOG","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","aiProviderById","defaultAiProvider","AI_DEFAULT_MODEL_ENV","ASSIST_MODEL_ENV","aiServingModelId","modelId","current","hops","length","successor","chosen","settings","key","value","undefined","resolveAiProvider","wanted","named","resolveAiRoute","kind","servedBy","process","provider","serving","id","model","env","trim","AI_SITE_JOB_CACHE_TTL","AI_ROUTING_TABLE","thinking","effort","maxTokens","maxTokensBasis","eval","kinds","scores","source","passRate","meanScore","cacheTtl","aiRouteSettings","row","TIER_RANK","fast","balanced","deep","aiModelAtLeastStepTier","floor","tier","aiModelForStep","route","Error"],"mappings":";AAAA;;;;;;;;;;;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;;;CASC,GACD,OAAO,SAASC,uBAAuB5B,IAAgB,EAAET,MAA0B,EAAEC,QAA2B;QAMvGqC;IALP,MAAMC,OAAOpD,aAAa,CAACsB,KAAK;IAChC,MAAMG,WAAWP,kBAAkBJ;IACnC,MAAMY,UAAUb,SAASZ,eAAeM,iBAAiBM,WAAWI;IACpE,IAAIS,WAAY,CAAA,CAACD,YAAYC,QAAQD,QAAQ,KAAKA,SAASE,EAAE,AAAD,KAAMmB,SAAS,CAACpB,QAAQ0B,IAAI,CAAC,IAAIN,SAAS,CAACM,KAAK,EAAE,OAAO1B,QAAQC,EAAE;IAC/H,MAAMwB,QAAQ1B,WAAWvB,kBAAkBuB,SAASE,EAAE,EAAEyB,QAAQnC;IAChE,QAAOkC,OAAAA,gBAAAA,QAAStC,kBAATsC,OAAmBE,eAAe/B,MAAMR;AACjD;AAEA,uEAAuE,GACvE,OAAO,SAASuC,eAAe/B,IAAgB,EAAER,QAA2B;IAC1E,MAAMwC,QAAQjC,eAAeC,MAAMR;IACnC,IAAI,CAACwC,OAAO;QACV,mEAAmE;QACnE,sEAAsE;QACtE,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD,MAAM1B,KAAK;AACpB"}
|
|
@@ -34,6 +34,11 @@ import { type AiInsight, type AiInsightAnswer, type AiInsightTable } from '../mo
|
|
|
34
34
|
* whose number cannot be found is exactly the sentence a person must not act
|
|
35
35
|
* on, and rewriting it would be the model's guess again. The rest of the
|
|
36
36
|
* answer stands. What is left out is counted, so the console can say so.
|
|
37
|
+
*
|
|
38
|
+
* A digest's overview, and an insight's reason and next step (AGL-4131), are
|
|
39
|
+
* held to the same rows and dropped alone when they fail: the insight stands.
|
|
40
|
+
* A reason must also cite a row of a table that can hold a cause, and a row
|
|
41
|
+
* whose change shows it held steady is not one.
|
|
37
42
|
*/
|
|
38
43
|
/** Why an insight was left out, as a finding code. */
|
|
39
44
|
export type AiInsightFinding = 'insight-empty' | 'insight-too-long' | 'insight-markup' | 'insight-personal-details' | 'insight-no-citation' | 'insight-unknown-table' | 'insight-unknown-row' | 'insight-number-untraced' | 'insight-direction' | 'insight-too-many';
|
|
@@ -42,6 +47,8 @@ export interface AiInsightVerdict {
|
|
|
42
47
|
findings: string[];
|
|
43
48
|
}
|
|
44
49
|
export interface AiInsightCheck {
|
|
50
|
+
/** A digest's read of the week, when it is one a person may read. */
|
|
51
|
+
overview: string | null;
|
|
45
52
|
/** The insights a person may read, in the order written. */
|
|
46
53
|
kept: AiInsight[];
|
|
47
54
|
/** The insights left out, each with why. */
|
|
@@ -15,7 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { hasPersonalDetails } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
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
|
+
import { 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 } from "../model/ai-insight.js";
|
|
19
19
|
const MARKUP = /<\/?[a-z][^>]*>|```|^#{1,6}\s|\*\*/im;
|
|
20
20
|
/**
|
|
21
21
|
* A number as a sentence writes it: an optional sign and currency symbol, the
|
|
@@ -166,29 +166,11 @@ const truncate = (value, decimals)=>{
|
|
|
166
166
|
const headline = typeof (insight == null ? void 0 : insight.headline) === 'string' ? insight.headline.trim() : '';
|
|
167
167
|
return headline.length <= AI_INSIGHT_HEADLINE_MAX_CHARS ? headline : '';
|
|
168
168
|
}
|
|
169
|
-
/**
|
|
170
|
-
const sentences = typeof (insight == null ? void 0 : insight.text) === 'string' ? insight.text.trim() : '';
|
|
171
|
-
if (!sentences) return [
|
|
172
|
-
'insight-empty'
|
|
173
|
-
];
|
|
174
|
-
const findings = [];
|
|
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;
|
|
180
|
-
if (MARKUP.test(text)) findings.push('insight-markup');
|
|
181
|
-
if (hasPersonalDetails(text)) findings.push('insight-personal-details');
|
|
182
|
-
const cites = Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : [];
|
|
183
|
-
if (!cites.length || cites.every((cite)=>!Array.isArray(cite == null ? void 0 : cite.rows) || !cite.rows.length)) {
|
|
184
|
-
return [
|
|
185
|
-
...findings,
|
|
186
|
-
'insight-no-citation'
|
|
187
|
-
];
|
|
188
|
-
}
|
|
169
|
+
/** The cells and labels a list of citations opens, and any citation that opens nothing. */ function citedFigures(cites, tables) {
|
|
189
170
|
const cells = [];
|
|
190
171
|
const labels = [];
|
|
191
172
|
const cited = [];
|
|
173
|
+
const findings = [];
|
|
192
174
|
for (const cite of cites){
|
|
193
175
|
var _cite_rows;
|
|
194
176
|
const table = tables.find((entry)=>entry.ref === (cite == null ? void 0 : cite.table));
|
|
@@ -226,7 +208,16 @@ const truncate = (value, decimals)=>{
|
|
|
226
208
|
}
|
|
227
209
|
}
|
|
228
210
|
}
|
|
229
|
-
|
|
211
|
+
return {
|
|
212
|
+
cells,
|
|
213
|
+
labels,
|
|
214
|
+
cited,
|
|
215
|
+
findings
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/** What a piece of writing says that the rows it cites do not: a figure they do not hold, or a direction they deny. */ function numberFindings(text, cites, figures) {
|
|
219
|
+
const { cells, labels, cited } = figures;
|
|
220
|
+
const findings = [];
|
|
230
221
|
const framing = framingNumbers(cited, cites);
|
|
231
222
|
for (const written of aiInsightNumbers(text)){
|
|
232
223
|
const matched = cells.filter((cell)=>scalesFor(written, cell.kind).some((scale)=>reads(written, cell.value, scale)));
|
|
@@ -246,6 +237,81 @@ const truncate = (value, decimals)=>{
|
|
|
246
237
|
}
|
|
247
238
|
return findings;
|
|
248
239
|
}
|
|
240
|
+
const insightCites = (insight)=>Array.isArray(insight.cites) ? insight.cites.slice(0, AI_INSIGHT_MAX_CITES) : [];
|
|
241
|
+
/** One insight's findings against the tables the job read; empty when it traces. */ export function checkAiInsight(insight, tables) {
|
|
242
|
+
const sentences = typeof (insight == null ? void 0 : insight.text) === 'string' ? insight.text.trim() : '';
|
|
243
|
+
if (!sentences) return [
|
|
244
|
+
'insight-empty'
|
|
245
|
+
];
|
|
246
|
+
const findings = [];
|
|
247
|
+
if (sentences.length > AI_INSIGHT_MAX_CHARS) findings.push('insight-too-long');
|
|
248
|
+
// The headline is held to everything the sentence is: it is the part a
|
|
249
|
+
// person reads first, and often the only part.
|
|
250
|
+
const headline = insightHeadline(insight);
|
|
251
|
+
const text = headline ? `${headline}. ${sentences}` : sentences;
|
|
252
|
+
if (MARKUP.test(text)) findings.push('insight-markup');
|
|
253
|
+
if (hasPersonalDetails(text)) findings.push('insight-personal-details');
|
|
254
|
+
const cites = insightCites(insight);
|
|
255
|
+
if (!cites.length || cites.every((cite)=>!Array.isArray(cite == null ? void 0 : cite.rows) || !cite.rows.length)) {
|
|
256
|
+
return [
|
|
257
|
+
...findings,
|
|
258
|
+
'insight-no-citation'
|
|
259
|
+
];
|
|
260
|
+
}
|
|
261
|
+
const figures = citedFigures(cites, tables);
|
|
262
|
+
findings.push(...figures.findings);
|
|
263
|
+
if (findings.some((finding)=>finding.startsWith('insight-unknown-'))) return findings;
|
|
264
|
+
return [
|
|
265
|
+
...findings,
|
|
266
|
+
...numberFindings(text, cites, figures)
|
|
267
|
+
];
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* A line beside the insights, held to everything an insight is, or `''` with
|
|
271
|
+
* why. It is only dropped: a reason or a next step that cannot be kept says
|
|
272
|
+
* nothing about whether the figures are true (AGL-4131).
|
|
273
|
+
*/ function checkedLine(value, name, maxChars, cites, tables) {
|
|
274
|
+
const line = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
275
|
+
if (!line) return {
|
|
276
|
+
line: '',
|
|
277
|
+
findings: []
|
|
278
|
+
};
|
|
279
|
+
const refused = [
|
|
280
|
+
...line.length > maxChars ? [
|
|
281
|
+
`insight-${name}-too-long`
|
|
282
|
+
] : [],
|
|
283
|
+
...MARKUP.test(line) ? [
|
|
284
|
+
`insight-${name}-markup`
|
|
285
|
+
] : [],
|
|
286
|
+
...hasPersonalDetails(line) ? [
|
|
287
|
+
`insight-${name}-personal-details`
|
|
288
|
+
] : [],
|
|
289
|
+
...numberFindings(line, cites, citedFigures(cites, tables))
|
|
290
|
+
];
|
|
291
|
+
return refused.length ? {
|
|
292
|
+
line: '',
|
|
293
|
+
findings: refused
|
|
294
|
+
} : {
|
|
295
|
+
line,
|
|
296
|
+
findings: []
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Whether an insight cites a row a reason can rest on: a row of a table that
|
|
301
|
+
* can hold a cause, and one that moved. A source or campaign whose change is 0
|
|
302
|
+
* sent the same traffic as the week before, so it cannot explain a move; a
|
|
303
|
+
* dated change has no change column and always can.
|
|
304
|
+
*/ function citesACause(cites, tables) {
|
|
305
|
+
return cites.some((cite)=>{
|
|
306
|
+
const table = tables.find((candidate)=>candidate.ref === cite.table);
|
|
307
|
+
if (!table || !AI_INSIGHT_CAUSE_READERS.includes(table.reader)) return false;
|
|
308
|
+
return cite.rows.some((index)=>{
|
|
309
|
+
const row = table.rows[index];
|
|
310
|
+
return Boolean(row) && row.change !== 0;
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
/** A next step that promises what it would do is left out: nothing here can know. */ const PROMISE = /\b(?:guarantee[sd]?|sure to|will (?:increase|boost|double|grow|raise|improve|bring|get you|rank))\b/i;
|
|
249
315
|
/** The gap sentence a person may read: short, without figures and naming nobody; `null` otherwise. */ export function aiInsightGap(gap) {
|
|
250
316
|
if (typeof gap !== 'string') return null;
|
|
251
317
|
const text = gap.replace(/\s+/g, ' ').trim();
|
|
@@ -273,20 +339,38 @@ const truncate = (value, decimals)=>{
|
|
|
273
339
|
findings.push(...own);
|
|
274
340
|
} else {
|
|
275
341
|
const headline = insightHeadline(insight);
|
|
342
|
+
const cites = insightCites(insight).map((cite)=>({
|
|
343
|
+
table: cite.table,
|
|
344
|
+
rows: cite.rows.slice(0, AI_INSIGHT_MAX_CITED_ROWS)
|
|
345
|
+
}));
|
|
346
|
+
const why = checkedLine(insight.why, 'why', AI_INSIGHT_WHY_MAX_CHARS, cites, tables);
|
|
347
|
+
const reasoned = why.line && citesACause(cites, tables);
|
|
348
|
+
if (why.line && !reasoned) findings.push('insight-why-no-cause');
|
|
349
|
+
const next = checkedLine(insight.next, 'next', AI_INSIGHT_NEXT_MAX_CHARS, cites, tables);
|
|
350
|
+
const promised = PROMISE.test(next.line);
|
|
351
|
+
if (promised) findings.push('insight-next-promise');
|
|
352
|
+
findings.push(...why.findings, ...next.findings);
|
|
276
353
|
kept.push(_extends({}, headline ? {
|
|
277
354
|
headline
|
|
278
355
|
} : {}, {
|
|
279
|
-
text: insight.text.trim()
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
356
|
+
text: insight.text.trim()
|
|
357
|
+
}, reasoned ? {
|
|
358
|
+
why: why.line
|
|
359
|
+
} : {}, next.line && !promised ? {
|
|
360
|
+
next: next.line
|
|
361
|
+
} : {}, {
|
|
362
|
+
cites
|
|
284
363
|
}));
|
|
285
364
|
}
|
|
286
365
|
});
|
|
287
366
|
const gap = aiInsightGap(answer == null ? void 0 : answer.gap);
|
|
288
367
|
if ((answer == null ? void 0 : answer.gap) && !gap) findings.push('insight-gap-unreadable');
|
|
368
|
+
// Held to the rows the kept insights cite: it has no citations of its own,
|
|
369
|
+
// and a figure in it should be one a reader can open just below it.
|
|
370
|
+
const overview = checkedLine(answer == null ? void 0 : answer.overview, 'overview', AI_INSIGHT_OVERVIEW_MAX_CHARS, kept.flatMap((insight)=>insight.cites), tables);
|
|
371
|
+
findings.push(...overview.findings);
|
|
289
372
|
return {
|
|
373
|
+
overview: overview.line || null,
|
|
290
374
|
kept,
|
|
291
375
|
left,
|
|
292
376
|
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_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,K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AAK7B,SAASlE,IAAI,CAAC;IACvC,OAAO;QAAEmG;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_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;AA2D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AC;YACzC,MAAMyH,OAAOvB,YAAYrC,QAAQ4D,IAAI,EAAE,QAAQlJ,2BAA2BqD,OAAOD;YACjF,MAAM+F,WAAWb,QAAQzH,IAAI,CAACqI,KAAKpB,IAAI;YACvC,IAAIqB,UAAUvD,SAASnE,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
|
};
|