@rudra-js/core 0.9.1 → 0.11.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.
Files changed (63) hide show
  1. package/README.md +175 -46
  2. package/dist/claim-screening.d.ts.map +1 -1
  3. package/dist/claim-screening.js +3 -9
  4. package/dist/claim-screening.js.map +1 -1
  5. package/dist/component-generator.d.ts +4 -1
  6. package/dist/component-generator.d.ts.map +1 -1
  7. package/dist/component-generator.js +95 -63
  8. package/dist/component-generator.js.map +1 -1
  9. package/dist/component-spec.d.ts +102 -12
  10. package/dist/component-spec.d.ts.map +1 -1
  11. package/dist/component-spec.js +4 -6
  12. package/dist/component-spec.js.map +1 -1
  13. package/dist/fallback-component.d.ts.map +1 -1
  14. package/dist/fallback-component.js +3 -3
  15. package/dist/fallback-component.js.map +1 -1
  16. package/dist/fit-to-shopper.d.ts +4 -1
  17. package/dist/fit-to-shopper.d.ts.map +1 -1
  18. package/dist/fit-to-shopper.js +8 -0
  19. package/dist/fit-to-shopper.js.map +1 -1
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/model-prompt.d.ts.map +1 -1
  25. package/dist/model-prompt.js +16 -3
  26. package/dist/model-prompt.js.map +1 -1
  27. package/dist/product-display.d.ts +6 -0
  28. package/dist/product-display.d.ts.map +1 -0
  29. package/dist/product-display.js +32 -0
  30. package/dist/product-display.js.map +1 -0
  31. package/dist/reconciliation.d.ts +2 -4
  32. package/dist/reconciliation.d.ts.map +1 -1
  33. package/dist/reconciliation.js +15 -21
  34. package/dist/reconciliation.js.map +1 -1
  35. package/dist/schemas.d.ts +1 -0
  36. package/dist/schemas.d.ts.map +1 -1
  37. package/dist/schemas.js +1 -0
  38. package/dist/schemas.js.map +1 -1
  39. package/dist/signal-digest.d.ts.map +1 -1
  40. package/dist/signal-digest.js +2 -10
  41. package/dist/signal-digest.js.map +1 -1
  42. package/dist/spec-cache.d.ts +87 -7
  43. package/dist/spec-cache.d.ts.map +1 -1
  44. package/dist/spec-cache.js +20 -32
  45. package/dist/spec-cache.js.map +1 -1
  46. package/dist/tracking-input.d.ts.map +1 -1
  47. package/dist/tracking-input.js +8 -2
  48. package/dist/tracking-input.js.map +1 -1
  49. package/package.json +5 -4
  50. package/schemas/package.json +4 -0
  51. package/src/claim-screening.ts +3 -9
  52. package/src/component-generator.ts +126 -84
  53. package/src/component-spec.ts +6 -18
  54. package/src/fallback-component.ts +4 -3
  55. package/src/fit-to-shopper.ts +16 -1
  56. package/src/index.ts +1 -2
  57. package/src/model-prompt.ts +24 -3
  58. package/src/product-display.ts +43 -0
  59. package/src/reconciliation.ts +16 -23
  60. package/src/schemas.ts +6 -0
  61. package/src/signal-digest.ts +2 -8
  62. package/src/spec-cache.ts +24 -40
  63. package/src/tracking-input.ts +11 -2
package/README.md CHANGED
@@ -1,26 +1,26 @@
1
1
  # @rudra-js/core
2
2
 
3
- This package is part of [rudra-js](https://rudrajs.com).
4
-
5
- rudra-js is an open-source TypeScript library (MIT) you install from npm. A
6
- language model designs one product-recommendation block for a page in your shop,
7
- rudra-js checks it against your catalog, and React renders it.
8
-
9
- It is not a hosted platform, a visual or low-code app builder, or a workspace
10
- you sign up for.
3
+ This package is part of [rudra-js](https://rudrajs.com), an open-source
4
+ TypeScript library (MIT) you install from npm. With rudra-js, a language model
5
+ designs one product-recommendation block for a page in your shop: the model
6
+ picks the layout and writes the words. After rudra-js checks the model's reply
7
+ against your products, React renders the block with your own titles and prices.
8
+ To be clear, rudra-js is not a hosted platform, a visual or low-code app
9
+ builder, or a workspace you sign up for.
11
10
 
12
11
  You give this package one page view:
13
12
 
14
- - the shopper and what they've been doing
13
+ - who the shopper is and what they've been doing
15
14
  - the page they're on
16
- - the products you're willing to show
15
+ - the products you're happy to show
17
16
 
18
- You will get back a spec, which is just data to describe the recommendations on
19
- that page. This can be written by your model or can be built by core without a
20
- model. Either way, it's checked against those products. There's no React in this
21
- package: the job of `@rudra-js/react` is to turn the spec into markup.
17
+ You get back a spec. It's just data describing the block. Your model can write
18
+ the spec, or core can build one without a model. This also happens if the model
19
+ fails. Either way, core checks the spec against those products.
22
20
 
23
- You can find the guides and the API reference at
21
+ There's no React here: `@rudra-js/react` turns the spec into markup.
22
+
23
+ For more, see the guides and API reference on
24
24
  [rudrajs.com](https://rudrajs.com).
25
25
 
26
26
  ## Install
@@ -68,6 +68,16 @@ install a single copy at the top of the tree. All `@rudra-js` packages are
68
68
  published to npm by a single tag at the same version. That's why these ranges
69
69
  will always move together.
70
70
 
71
+ In browser code, import values from `@rudra-js/core/schemas` instead of
72
+ `@rudra-js/core`. It has `productSchema`, `bundleSchema`, `renderContextSchema`,
73
+ `FIELD_LIMITS`, `parseComponentSpec`, and the defaults a block uses for product
74
+ links, prices and stock. The main entry loads `node:crypto` to hash cache keys,
75
+ so keep it on the server. Types are the exception:
76
+ `import type { Product } from '@rudra-js/core'` is removed at build time, so
77
+ it's fine in browser code. Keep the `type` before the braces. With
78
+ `verbatimModuleSyntax`, `import { type Product }` stays in the build as an
79
+ import of the main entry.
80
+
71
81
  ## Running without a model
72
82
 
73
83
  `createComponentGenerator` takes a `provider`. If you leave this out or pass
@@ -111,9 +121,11 @@ out.
111
121
  | `cache` | Where generated specs live between requests. Pass `createNullSpecCache()` to keep none. | `createMemorySpecCache()` |
112
122
  | `generation` | `'cohort'` shares one spec between shoppers who look alike. `'per-shopper'` generates for each shopper. | `'cohort'` |
113
123
  | `rank` | `'signals'` orders products by the shopper's signals. `'given'` keeps the order you sent. | `'signals'` |
114
- | `modelTimeoutMs` | How long the model gets. After that, core aborts the request and renders the fallback. | `1500` |
115
- | `cacheTimeoutMs` | How long a cache read gets. After that, the request generates as if the cache had nothing. | `50` |
116
- | `onEvent` | Called once per `generate` with a `GenerationEvent`. If your function throws, core ignores the error. | none |
124
+ | `modelTimeoutMs` | How long the model gets before core aborts the call. With `waitForModel: false` it's `30000`. | `1500` |
125
+ | `cacheTimeoutMs` | How long a cache read gets. Then a waiting page asks the model. With `waitForModel: false`, none does. | `50` |
126
+ | `waitForModel` | `false` keeps the model out of the page request. See [below](#keeping-the-model-off-the-page). | `true` |
127
+ | `waitUntil` | With `waitForModel: false`, core hands it the model call still running when the page is sent. | none |
128
+ | `onEvent` | Called once per `generate`, and once per call behind a page. If your function throws, core ignores it. | none |
117
129
 
118
130
  ## `tracking-input`
119
131
 
@@ -318,18 +330,18 @@ products and writes about them. In most shops the candidates come from the page
318
330
  and will be shared by all the people looking at it. If you pick candidates per
319
331
  shopper, you'll get smaller cohorts, because each prompt really is personal.
320
332
 
321
- For a cohort, the cache key holds the _set_ of candidate SKUs. This key will
322
- ignore the order they were sent in, which of them were in stock and where the
323
- 60-product cut fell. Two requests with the same SKUs in a different order are
324
- going to share a spec. Both of them will get the first spec to be generated. If
325
- your ranking is personal and you order your candidates per shopper, the products
326
- the copy talks about won't be the ones you put at the top.
333
+ The cache key is a hash of the exact prompt the model is sent. So it sees the
334
+ candidates the way the model does: the first 60 in stock, in the order you sent
335
+ them, each with its title, category, rating and tags. Two requests with the same
336
+ products in a different order get a spec each. A product that sells out or comes
337
+ back moves the key too, so the next request asks the model again. If your
338
+ ranking is personal and you order your candidates per shopper, each order makes
339
+ a cohort of its own. Send them in the same order to everyone who should share a
340
+ spec.
327
341
 
328
342
  Prices, titles and stock will always be read from your catalog at render time.
329
- This is to make sure a stale value never shows in those fields. If a product
330
- sold out, it's dropped as the page is served, but any sentence the model wrote
331
- about it will stay. You can also end up with copy written from an old title,
332
- rating or tag, because the cache key holds SKUs and none of those fields.
343
+ This is to make sure a stale value never shows in those fields. A price or an
344
+ image never reaches the model, so changing one keeps the spec you have.
333
345
 
334
346
  #### Who can create a cohort
335
347
 
@@ -357,8 +369,9 @@ your provider. The other cost will be the bill, plus a model round trip on a
357
369
  page that was being served from cache.
358
370
 
359
371
  To generate for each shopper instead, you can pass `generation: 'per-shopper'`.
360
- The model will then pick the products too and each shopper will cost a call of
361
- their own.
372
+ The model will then pick the products too. Most shoppers will cost a call of
373
+ their own. Two share an entry only when their prompts match exactly, as two
374
+ first-time visitors on the same page can.
362
375
 
363
376
  ```ts
364
377
  createComponentGenerator({ provider, generation: 'per-shopper' });
@@ -408,6 +421,10 @@ finding them out from a rejection.
408
421
  | `maxItems` | 12 | `context.maxItems`, which also needs at least 1 |
409
422
  | `reason` | 120 | `candidates[].reason`, your own phrase for a product |
410
423
 
424
+ A product's `sku` and each of `bundles[].skus` must also be well-formed Unicode.
425
+ Half of a UTF-16 surrogate pair on its own is refused, because the default
426
+ product link runs the SKU through `encodeURIComponent`, and that throws on one.
427
+
411
428
  Each cap bounds a single field on its own. Together they aren't a budget for the
412
429
  whole prompt. Core doesn't count tokens either. The digest, the short summary of
413
430
  the shopper and the page, trims signals instead of throwing. The prompt will
@@ -540,11 +557,12 @@ All of the above and also:
540
557
  The candidate list will be trimmed before it's sent. Out-of-stock products will
541
558
  be dropped and no more than 60 products will go, in the order you supplied.
542
559
 
543
- `spec-cache.test.ts` walks all the fields of the digest, to check that each
544
- field is either in the cache key or removed from the cohort prompt. If a field
545
- is left out of the key but still changes the prompt, that test will fail. It
546
- will also fail for a new field added to the digest, until someone says which
547
- side the field is on.
560
+ The cache key hashes the prompt itself, so nothing the model is shown can be
561
+ left out of it. `spec-cache.test.ts` walks all the fields of the digest, to
562
+ check that each one either reaches the cohort prompt or is removed from it. A
563
+ new field added to the digest fails the typecheck there until someone gives it
564
+ a test value, and the walk then fails if the field reaches the cohort prompt
565
+ without being listed as part of the cohort.
548
566
 
549
567
  ## What the model decides, by mode
550
568
 
@@ -593,7 +611,7 @@ tenancy or a recorded fixture. `@rudra-js/core` depends on no vendor SDK.
593
611
  `@rudra-js/anthropic` is just one adapter and you don't have to use it.
594
612
 
595
613
  An adapter takes its API key as an option. You can then choose where the key
596
- comes from. `ANTHROPIC_API_KEY` is just the name the example shop uses. No
614
+ comes from. `ANTHROPIC_API_KEY` is just the name the demo uses. No
597
615
  package here reads the environment.
598
616
 
599
617
  ## The cache
@@ -609,9 +627,9 @@ the spec). It doesn't hold a payload or a prompt.
609
627
 
610
628
  In cohort mode an entry holds no shopper id and it's shared by all the shoppers
611
629
  in the cohort. But there's an exception if the segment or candidates were picked
612
- for one shopper. In per-shopper mode the model wrote the entry from the signals
613
- of that shopper. Its text can then repeat them (a search term, for instance)
614
- and the entry will be personal data until it's gone.
630
+ or ordered for one shopper. In per-shopper mode the model wrote the entry from
631
+ the signals of that shopper. Its text can then repeat them (a search term, for
632
+ instance) and the entry will be personal data until it's gone.
615
633
 
616
634
  Expiry is checked when an entry is read. An expired entry will stay in memory
617
635
  until it's read again or pushed out by a newer entry.
@@ -643,6 +661,106 @@ Core can't drop all the entries of a shopper for you, because nothing maps a
643
661
  shopper to their keys. Per-shopper entries will end when they expire or when
644
662
  newer entries push them out. You can also delete an entry by a `key` you kept.
645
663
 
664
+ ## Keeping the model off the page
665
+
666
+ By default, a page that misses the cache waits for the model, for up to
667
+ `modelTimeoutMs`. Pass `waitForModel: false` and no page waits:
668
+
669
+ - On a hit, the page gets the cached spec, the same as before.
670
+ - On a miss, the page gets the fallback straight away and core asks the model
671
+ behind it. The answer goes into the cache, so the next shopper in that cohort
672
+ gets it.
673
+ - Pages on the same server that miss while that call runs share it. They don't
674
+ start one each. Each server starts its own.
675
+
676
+ ```ts
677
+ import { after } from 'next/server';
678
+
679
+ const generator = createComponentGenerator({
680
+ provider,
681
+ cache: sharedStore,
682
+ waitForModel: false,
683
+ waitUntil: after,
684
+ });
685
+ ```
686
+
687
+ `waitUntil` gets the call that's still running when the page is sent. Serverless
688
+ hosts stop work once the response is out unless you hand it over. In Next.js,
689
+ pass `after`. On other Vercel functions, pass `waitUntil` from
690
+ `@vercel/functions`. A long-running Node server doesn't need it.
691
+
692
+ A few things work differently in this mode:
693
+
694
+ - `modelTimeoutMs` defaults to 30,000. The 1,500 default is a budget for a page
695
+ that's waiting. A call cut off at 1.5 seconds never reaches the cache.
696
+ - Use a store all your servers share. The built-in store lives inside one
697
+ process, so each serverless instance would fill its own copy.
698
+ - If the store can't be read (it throws, or takes longer than
699
+ `cacheTimeoutMs`), the page gets the fallback and no call starts. A store that
700
+ can't be read can't hand the answer to the next page either. If your store is
701
+ only slow, raise `cacheTimeoutMs`.
702
+ - Pages that got the fallback this way say `degradedReason: 'not-cached'`.
703
+ - `generation: 'per-shopper'` throws. A per-shopper prompt changes with almost
704
+ every view, so almost no call would reach a page.
705
+ - `createNullSpecCache()` throws too. Pages only get the answer from the cache,
706
+ so with a store that keeps nothing no call would ever reach one.
707
+
708
+ ### Building specs ahead of time
709
+
710
+ To have specs ready before the first shopper arrives, run a job that fills the
711
+ same store. The job uses an ordinary generator, which waits, with a longer
712
+ timeout:
713
+
714
+ ```ts
715
+ const writes: Promise<void>[] = [];
716
+ const warmer = createComponentGenerator({
717
+ provider,
718
+ cache: {
719
+ get: (key) => sharedStore.get(key),
720
+ set: (key, cached) => {
721
+ const write = sharedStore.set(key, cached);
722
+ writes.push(write);
723
+ return write;
724
+ },
725
+ },
726
+ modelTimeoutMs: 60_000,
727
+ cacheTimeoutMs: 5_000,
728
+ });
729
+
730
+ for (const page of productPages) {
731
+ for (const segment of ['new', 'loyalty']) {
732
+ await warmer.generate({
733
+ user: { id: 'warm-up', segment },
734
+ context: { surface: 'pdp', currentCategory: page.category },
735
+ candidates: page.candidates,
736
+ });
737
+ }
738
+ }
739
+
740
+ await Promise.allSettled(writes);
741
+ ```
742
+
743
+ `generate` returns without waiting for the store to save the answer. That's why
744
+ the job keeps each write and waits for all of them before it ends. Without that,
745
+ a host that stops the job as soon as it returns can lose the last few.
746
+
747
+ An input with no signals fills the cohort of shoppers with no history on that
748
+ page. Shoppers with history fall into a cohort by the category they lean
749
+ towards, and those fill in on their first view. A cohort that's already in the
750
+ store is a cache hit, so running the job again only pays for what changed. That's
751
+ what the longer `cacheTimeoutMs` is for: a read that runs out of time counts as
752
+ a miss and pays for the cohort again.
753
+
754
+ Each input has to match what the page sends: the same surface, slot, locale,
755
+ item count, segment and category, and the same candidates in the same order. The
756
+ job also has to use the same provider and model as your pages, on the same
757
+ version of `@rudra-js/core`. Both are part of the key, so a job on another model
758
+ fills entries no page reads. A
759
+ product that sells out or comes back moves the key, as
760
+ [Cohorts](#cohorts) explains. Run the job after stock changes, or let pages
761
+ fill the new key behind them. Your store also has to keep entries for longer
762
+ than the time between runs.
763
+
646
764
  ## Watching it in production
647
765
 
648
766
  The generator never fails a render. If a provider has been down for a week, this
@@ -651,13 +769,24 @@ Each call to `generate` that gets past input validation reports exactly one
651
769
  `GenerationEvent`. If a payload fails `parseTrackingInput`, it will throw
652
770
  instead and report nothing.
653
771
 
772
+ With `waitForModel: false`, a call that starts behind a page reports one more
773
+ event when it ends, with `background: true`. That event rendered nothing. Its
774
+ `source` is `'llm'` if the answer went into the cache. Otherwise it's
775
+ `'fallback'`, with a `degradedReason` if the model failed, or with
776
+ `cache: 'error'` if the store refused the answer. After a timeout, a provider
777
+ error or a refused write, `error` has what was thrown. The page's own event has
778
+ `calledModel: false`.
779
+
654
780
  These are the numbers to keep:
655
781
 
656
782
  - **Fallback share.** This is the share of events with `source: 'fallback'`. Be
657
783
  sure to alert if it climbs. `degradedReason` will tell you which way the call
658
784
  failed. If the reason is `'provider-error'` or `'timeout'`, `error` has the
659
- value that was thrown.
785
+ value that was thrown. With `waitForModel: false`, count the page events and
786
+ the `background: true` events apart. A provider that's down shows up in the
787
+ second.
660
788
  - **Cache hit rate.** `cache: 'hit'` over the events that have a `cache` field.
789
+ Leave out events with `background: true`.
661
790
  A store that's down will show as `cache: 'error'` and a slow store as
662
791
  `cache: 'timeout'`. A broken store will then show up here and not just as a
663
792
  rising bill.
@@ -701,12 +830,12 @@ it will personalise.
701
830
  the cache. In cohort mode an entry holds no shopper id and it's shared by all
702
831
  the shoppers in the cohort. There's usually no single shopper's entry to delete.
703
832
  But there's an exception if a cohort entry has a segment or candidate list
704
- picked for one shopper. Like all per-shopper entries, it's about that shopper.
705
- Nothing maps a shopper to their entries. That's why you need to keep `ttlMs`
706
- short or pass `createNullSpecCache()`. `onEvent` sends no shopper id. But in
707
- per-shopper mode its `key` is derived from a shopper id. `violations` can also
708
- name SKUs from a shopper's basket or purchases. Treat logs of `onEvent` as
709
- personal data.
833
+ picked or ordered for one shopper. Like all per-shopper entries, it's about that
834
+ shopper. Nothing maps a shopper to their entries. That's why you need to keep
835
+ `ttlMs` short or pass `createNullSpecCache()`. `onEvent` sends no shopper id.
836
+ But in per-shopper mode its `key` is derived from the shopper's history.
837
+ `violations` can also name SKUs from a shopper's basket or purchases. Treat logs
838
+ of `onEvent` as personal data.
710
839
 
711
840
  **Caching pages.** In its HTML, a personalised page will say things like
712
841
  "Goes with your cart" and "You looked at this recently". Serve those pages with
@@ -1 +1 @@
1
- {"version":3,"file":"claim-screening.d.ts","sourceRoot":"","sources":["../src/claim-screening.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AA4EzD,eAAO,MAAM,eAAe,UAK3B,CAAC;AAKF,eAAO,MAAM,QAAQ,EAAE,SAAS,MAAM,EAAO,CAAC;AAE9C,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CAC9B;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,aAAa,GAAG,SAAS,CAWzD;AAqBD,wBAAgB,aAAa,CAC3B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,MAAM,GAAG,IAAI,CASf"}
1
+ {"version":3,"file":"claim-screening.d.ts","sourceRoot":"","sources":["../src/claim-screening.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AA4EzD,eAAO,MAAM,eAAe,UAK3B,CAAC;AAIF,eAAO,MAAM,QAAQ,EAAE,SAAS,MAAM,EAAO,CAAC;AAE9C,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;CAC9B;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,aAAa,GAAG,SAAS,CAWzD;AAiBD,wBAAgB,aAAa,CAC3B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,MAAM,GAAG,IAAI,CAQf"}
@@ -1,4 +1,4 @@
1
- import { foldLookalikes, verify } from '@rudra-js/attested';
1
+ import { listLookalikeReadings, verify } from '@rudra-js/attested';
2
2
  import { offeredCandidates } from './model-prompt.js';
3
3
  const CLAIM_PATTERNS = [
4
4
  {
@@ -80,7 +80,6 @@ export const ALLOWED_PHRASES = [
80
80
  'sustainable pace',
81
81
  ];
82
82
  const FACT_DIGIT = /\p{Nd}/u;
83
- const NUMERAL = /[\p{Nd}\p{No}\p{Nl}]/u;
84
83
  export const NO_FACTS = [];
85
84
  export function hostFacts(input) {
86
85
  const pooled = new Set();
@@ -101,11 +100,7 @@ function kindIn(reading) {
101
100
  return null;
102
101
  }
103
102
  function claimIn(text) {
104
- const readings = new Set([foldLookalikes(text), foldLookalikes(text, true)]);
105
- if (text.includes('\u04C0')) {
106
- readings.add(foldLookalikes(text.replaceAll('\u04C0', '\u04CF'), true));
107
- }
108
- for (const reading of readings) {
103
+ for (const reading of listLookalikeReadings(text)) {
109
104
  const kind = kindIn(reading);
110
105
  if (kind !== null)
111
106
  return kind;
@@ -116,8 +111,7 @@ export function unbackedClaim(raw, clamped, facts) {
116
111
  const kind = claimIn(raw) ?? claimIn(clamped);
117
112
  if (kind !== null)
118
113
  return kind;
119
- const values = NUMERAL.test(clamped) ? facts : NO_FACTS;
120
- const result = verify(clamped, { values, allowedPhrases: ALLOWED_PHRASES });
114
+ const result = verify(clamped, { values: facts, allowedPhrases: ALLOWED_PHRASES });
121
115
  if (!result.quantity.supported)
122
116
  return 'quantity';
123
117
  if (!result.wording.supported)
@@ -1 +1 @@
1
- {"version":3,"file":"claim-screening.js","sourceRoot":"","sources":["../src/claim-screening.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAGtD,MAAM,cAAc,GAA2C;IAC7D;QACE,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE;YACR,2BAA2B;YAC3B,mDAAmD;YACnD,0BAA0B;YAC1B,kEAAkE;YAClE,+BAA+B;YAC/B,0CAA0C;YAC1C,yDAAyD;YACzD,uBAAuB;YACvB,2DAA2D;YAC3D,kCAAkC;YAClC,6DAA6D;YAC7D,+CAA+C;SAChD;KACF;IACD;QACE,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE;YACR,SAAS;YACT,6DAA6D;YAC7D,yBAAyB;YACzB,wBAAwB;YACxB,qBAAqB;YACrB,yBAAyB;YACzB,6DAA6D;YAC7D,qBAAqB;YACrB,4BAA4B;YAC5B,2DAA2D;YAC3D,yBAAyB;YACzB,kDAAkD;SACnD;KACF;IACD;QACE,IAAI,EAAE,UAAU;QAChB,QAAQ,EAAE;YACR,qEAAqE;YACrE,iGAAiG;YACjG,uBAAuB;YACvB,sCAAsC;YACtC,6BAA6B;YAC7B,8BAA8B;YAC9B,4DAA4D;YAC5D,mBAAmB;YACnB,mBAAmB;YACnB,kCAAkC;YAClC,yCAAyC;SAC1C;KACF;IACD;QACE,IAAI,EAAE,UAAU;QAChB,QAAQ,EAAE;YACR,2BAA2B;YAC3B,iDAAiD;YACjD,kMAAkM;YAClM,qDAAqD;YACrD,iBAAiB;SAClB;KACF;IACD;QACE,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE;YACR,gCAAgC;YAChC,mBAAmB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,IAAI,CAAC;IACjC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,aAAa,CAC3B,GAAW,EACX,OAAe,EACf,KAAwB;IAExB,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9C,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE/B,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,CAAC,CAAC;IACnF,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS;QAAE,OAAO,UAAU,CAAC;IAClD,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IAChD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { type ComponentSpec, type DegradedReason, type SpecSource } from './component-spec.js';
2
2
  import type { ComponentProvider, TokenUsage } from './provider.js';
3
- import { type RankOrder } from './product-selection.js';
3
+ import type { RankOrder } from './product-selection.js';
4
4
  import { type SpecCache } from './spec-cache.js';
5
5
  import { type TrackingInputDraft } from './tracking-input.js';
6
6
  export interface GenerationEvent {
@@ -13,6 +13,7 @@ export interface GenerationEvent {
13
13
  degradedReason?: DegradedReason;
14
14
  error?: unknown;
15
15
  cache?: 'hit' | 'miss' | 'error' | 'timeout';
16
+ background?: true;
16
17
  }
17
18
  export interface ComponentGeneratorOptions {
18
19
  provider?: ComponentProvider | null;
@@ -21,6 +22,8 @@ export interface ComponentGeneratorOptions {
21
22
  cacheTimeoutMs?: number;
22
23
  generation?: 'cohort' | 'per-shopper';
23
24
  rank?: RankOrder;
25
+ waitForModel?: boolean;
26
+ waitUntil?: (work: Promise<unknown>) => void;
24
27
  onEvent?: (event: GenerationEvent) => void;
25
28
  }
26
29
  export interface ComponentGenerator {
@@ -1 +1 @@
1
- {"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AAc,CAAC,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,QAAQ,GAAG,aAAa,CAAC;IACtC,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC;IAC7C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,CAAC;CAC5C;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAC5D,qBAAqB,CAAC,KAAK,EAAE,kBAAkB,GAAG,aAAa,CAAC;CACjE;AAED,qBAAa,YAAa,SAAQ,KAAK;IACrC,YAAY,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAG9C;CACF;AAoED,wBAAgB,wBAAwB,CACtC,OAAO,GAAE,yBAA8B,GACtC,kBAAkB,CAsBpB"}
@@ -1,12 +1,10 @@
1
- import { z } from 'zod';
2
1
  import { SPEC_VERSION, generatedSpecSchema, } from './component-spec.js';
3
2
  import { buildFallbackSpec } from './fallback-component.js';
4
3
  import { buildPrompt } from './model-prompt.js';
5
- import { bundleForShopper, capBlocks, placeableHeroSkus, reconcileSpec } from './reconciliation.js';
6
- import { selectProducts } from './product-selection.js';
7
- import { fitToShopper } from './fit-to-shopper.js';
4
+ import { reconcileSpec } from './reconciliation.js';
5
+ import { fitCohortSpec } from './fit-to-shopper.js';
8
6
  import { buildDigest, toCohortDigest } from './signal-digest.js';
9
- import { createMemorySpecCache, specCacheKey, } from './spec-cache.js';
7
+ import { cachedSpecSchema, createMemorySpecCache, isNullSpecCache, specCacheKey, } from './spec-cache.js';
10
8
  import { parseTrackingInput, } from './tracking-input.js';
11
9
  export class TimeoutError extends Error {
12
10
  constructor(label, milliseconds) {
@@ -35,38 +33,21 @@ async function withinBudget(label, milliseconds, start) {
35
33
  clearTimeout(timer);
36
34
  }
37
35
  }
38
- const cachedSpecSchema = z.object({
39
- spec: generatedSpecSchema,
40
- generatedAt: z.number(),
41
- });
42
- function fitCohortSpec(spec, input, digest, rank) {
43
- const picks = selectProducts(input, digest, { rank });
44
- const blocks = capBlocks(spec.blocks);
45
- const bundleAt = blocks.findIndex((block) => block.kind === 'bundle');
46
- if (bundleAt === -1)
47
- return fitToShopper(spec, picks, digest.maxItems);
48
- const heroesAbove = placeableHeroSkus(blocks.slice(0, bundleAt), input);
49
- const bundle = bundleForShopper(input, digest, heroesAbove);
50
- if (!bundle)
51
- return fitToShopper(spec, picks, digest.maxItems);
52
- const spokenFor = new Set(bundle.skus);
53
- for (const sku of placeableHeroSkus(blocks, input))
54
- spokenFor.add(sku);
55
- const roomLeft = digest.maxItems - spokenFor.size;
56
- if (roomLeft <= 0)
57
- return fitToShopper(spec, picks, digest.maxItems);
58
- const forGrid = picks.filter((pick) => !spokenFor.has(pick.product.sku));
59
- return fitToShopper(spec, forGrid, roomLeft);
60
- }
61
36
  export function createComponentGenerator(options = {}) {
37
+ const generation = options.generation ?? 'cohort';
38
+ const waitForModel = options.waitForModel ?? true;
39
+ if (!waitForModel)
40
+ assertPagesCanBeServed(generation, options.cache);
62
41
  const settings = {
63
- options,
64
42
  provider: options.provider ?? null,
65
43
  cache: options.cache ?? createMemorySpecCache(),
66
- generation: options.generation ?? 'cohort',
44
+ generation,
67
45
  rank: options.rank ?? 'signals',
68
- modelTimeoutMs: options.modelTimeoutMs ?? 1_500,
46
+ modelTimeoutMs: options.modelTimeoutMs ?? (waitForModel ? 1_500 : 30_000),
69
47
  cacheTimeoutMs: options.cacheTimeoutMs ?? 50,
48
+ waitForModel,
49
+ waitUntil: options.waitUntil,
50
+ onEvent: options.onEvent,
70
51
  inFlight: new Map(),
71
52
  };
72
53
  return {
@@ -74,17 +55,29 @@ export function createComponentGenerator(options = {}) {
74
55
  generateDeterministic: (draft) => generateDeterministic(settings, draft),
75
56
  };
76
57
  }
58
+ function assertPagesCanBeServed(generation, cache) {
59
+ if (generation === 'per-shopper') {
60
+ throw new RangeError("waitForModel: false needs generation: 'cohort'. A per-shopper prompt changes with " +
61
+ 'almost every view, so the call it starts would almost never reach a page.');
62
+ }
63
+ if (cache && isNullSpecCache(cache)) {
64
+ throw new RangeError('waitForModel: false needs a cache that keeps entries. Pages only get the answer ' +
65
+ 'from the cache, so with createNullSpecCache() no call would ever reach one.');
66
+ }
67
+ }
77
68
  async function generate(settings, draft) {
78
69
  const run = startRun(settings, draft);
79
70
  const provider = settings.provider;
80
71
  if (!provider)
81
72
  return fallback(settings, run, null, 'no-provider');
82
- const key = cacheKeyFor(provider, run);
83
- const found = await findSpec(settings, provider, run, key);
73
+ const prompt = buildPrompt(run.input, run.promptDigest);
74
+ const key = specCacheKey(prompt, provider);
75
+ const found = await findSpec(settings, provider, prompt, key);
84
76
  if ('failed' in found)
85
- return fallback(settings, run, key, found.failed, eventDetails(found.trace));
77
+ return fallback(settings, run, key, found.failed, found.details);
86
78
  const reconciled = shapeForShopper(settings, run, found.spec);
87
- const details = eventDetails(found.trace, reconciled.violations);
79
+ const { usage, ...seen } = found.details;
80
+ const details = { ...seen, violations: reconciled.violations, ...(usage ? { usage } : {}) };
88
81
  if (!reconciled.isUsable)
89
82
  return fallback(settings, run, key, 'unusable-on-serve', details);
90
83
  const finishedAt = Date.now();
@@ -115,33 +108,35 @@ function startRun(settings, draft) {
115
108
  const promptDigest = settings.generation === 'cohort' ? toCohortDigest(digest) : digest;
116
109
  return { input, digest, promptDigest, startedAt };
117
110
  }
118
- function cacheKeyFor(provider, run) {
119
- const identity = { name: provider.name, model: provider.model };
120
- const skus = run.input.candidates.map((product) => product.sku);
121
- return specCacheKey(run.promptDigest, skus, identity);
122
- }
123
- async function findSpec(settings, provider, run, key) {
111
+ async function findSpec(settings, provider, prompt, key) {
124
112
  const read = await readCache(settings, key);
125
113
  if (read.entry) {
126
- const trace = { calledModel: false, cache: read.outcome, usage: undefined };
127
- return { spec: read.entry.spec, generatedAt: read.entry.generatedAt, source: 'cache', trace };
114
+ const details = { calledModel: false, cache: read.outcome };
115
+ return { spec: read.entry.spec, generatedAt: read.entry.generatedAt, source: 'cache', details };
116
+ }
117
+ if (!settings.waitForModel) {
118
+ if (read.outcome === 'miss')
119
+ fillInBackground(settings, provider, prompt, key);
120
+ return { failed: 'not-cached', details: { calledModel: false, cache: read.outcome } };
128
121
  }
129
122
  const calledModel = !settings.inFlight.has(key);
130
123
  let call;
131
124
  try {
132
- call = await sharedCall(settings, key, () => askModel(settings, provider, run));
125
+ call = await sharedCall(settings, key, () => askModel(settings, provider, prompt));
133
126
  }
134
127
  catch (error) {
135
128
  const failed = error instanceof TimeoutError ? 'timeout' : 'provider-error';
136
- return { failed, trace: { calledModel, cache: read.outcome, usage: undefined, error } };
129
+ return { failed, details: { calledModel, cache: read.outcome, error } };
137
130
  }
138
- const trace = { calledModel, cache: read.outcome, usage: call.usage };
131
+ const details = { calledModel, cache: read.outcome };
132
+ if (call.usage)
133
+ details.usage = call.usage;
139
134
  if (!call.spec)
140
- return { failed: 'invalid-generation', trace };
135
+ return { failed: 'invalid-generation', details };
141
136
  const generatedAt = Date.now();
142
137
  if (calledModel)
143
138
  storeInBackground(settings, key, { spec: call.spec, generatedAt });
144
- return { spec: call.spec, generatedAt, source: 'llm', trace };
139
+ return { spec: call.spec, generatedAt, source: 'llm', details };
145
140
  }
146
141
  async function readCache(settings, key) {
147
142
  try {
@@ -153,9 +148,13 @@ async function readCache(settings, key) {
153
148
  return { outcome: error instanceof TimeoutError ? 'timeout' : 'error' };
154
149
  }
155
150
  }
156
- async function askModel(settings, provider, run) {
157
- const { system, user } = buildPrompt(run.input, run.promptDigest);
158
- const result = await withinBudget('generation', settings.modelTimeoutMs, (signal) => provider.generate({ system, user, schema: generatedSpecSchema, signal }));
151
+ async function askModel(settings, provider, prompt) {
152
+ const result = await withinBudget('generation', settings.modelTimeoutMs, (signal) => provider.generate({
153
+ system: prompt.system,
154
+ user: prompt.user,
155
+ schema: generatedSpecSchema,
156
+ signal,
157
+ }));
159
158
  const parsed = generatedSpecSchema.safeParse(result.spec);
160
159
  return {
161
160
  spec: parsed.success ? parsed.data : null,
@@ -170,6 +169,50 @@ function sharedCall(settings, key, ask) {
170
169
  settings.inFlight.set(key, started);
171
170
  return started;
172
171
  }
172
+ function fillInBackground(settings, provider, prompt, key) {
173
+ if (settings.inFlight.has(key))
174
+ return;
175
+ const startedAt = Date.now();
176
+ const finished = (source, details) => report(settings, {
177
+ key,
178
+ source,
179
+ elapsedMs: Date.now() - startedAt,
180
+ calledModel: true,
181
+ ...details,
182
+ background: true,
183
+ });
184
+ const askAndStore = async () => {
185
+ const call = await askModel(settings, provider, prompt);
186
+ if (!call.spec)
187
+ return call;
188
+ try {
189
+ await settings.cache.set(key, { spec: call.spec, generatedAt: Date.now() });
190
+ return call;
191
+ }
192
+ catch (error) {
193
+ return { ...call, failedWrite: { error } };
194
+ }
195
+ };
196
+ const work = sharedCall(settings, key, askAndStore).then((call) => {
197
+ const usage = call.usage ? { usage: call.usage } : {};
198
+ if (!call.spec) {
199
+ finished('fallback', { ...usage, degradedReason: 'invalid-generation' });
200
+ }
201
+ else if (call.failedWrite) {
202
+ finished('fallback', { cache: 'error', error: call.failedWrite.error, ...usage });
203
+ }
204
+ else {
205
+ finished('llm', usage);
206
+ }
207
+ }, (error) => {
208
+ const degradedReason = error instanceof TimeoutError ? 'timeout' : 'provider-error';
209
+ finished('fallback', { error, degradedReason });
210
+ });
211
+ try {
212
+ settings.waitUntil?.(work);
213
+ }
214
+ catch { }
215
+ }
173
216
  function storeInBackground(settings, key, cached) {
174
217
  void Promise.resolve()
175
218
  .then(() => settings.cache.set(key, cached))
@@ -203,20 +246,9 @@ function fallback(settings, run, key, degradedReason, details = { calledModel: f
203
246
  degradedReason,
204
247
  };
205
248
  }
206
- function eventDetails(trace, violations) {
207
- return {
208
- calledModel: trace.calledModel,
209
- cache: trace.cache,
210
- ...(violations ? { violations } : {}),
211
- ...(trace.usage ? { usage: trace.usage } : {}),
212
- ...('error' in trace ? { error: trace.error } : {}),
213
- };
214
- }
215
249
  function report(settings, event) {
216
- if (!settings.options.onEvent)
217
- return;
218
250
  try {
219
- settings.options.onEvent(event);
251
+ settings.onEvent?.(event);
220
252
  }
221
253
  catch { }
222
254
  }