@bivelio/savings-layer 0.5.1 → 0.5.2

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 CHANGED
@@ -933,10 +933,11 @@ const { data, text } = await layer.generate<{ answer: number }>({
933
933
  console.log(data.answer); // 8
934
934
  ```
935
935
 
936
- A question the layer answers on its own (the arithmetic of the first example)
937
- never reaches the model, so its `data` is the resolver's `{ value: 8 }`, not
938
- your schema's shape: `report.qualityLedger` says the contract was not met.
939
- Ask the model for anything you want in your contract's shape.
936
+ A question the layer can answer on its own (the arithmetic of the first
937
+ example) is only served without the model when that answer meets your schema.
938
+ The arithmetic resolver returns `{ value: 8 }`: with a `{ answer: number }`
939
+ contract it steps aside and the request goes to the model, which answers in
940
+ your contract's shape.
940
941
 
941
942
  </details>
942
943
 
@@ -79,7 +79,7 @@ ld.test(n.betas))return null;let r=ht(e,t);if(r===null||ud(r))return null;let o=
79
79
  let r=Object.entries(Ts).map(([o,i])=>`${o}\u2192${i}`).join(", ");return e!=="1"?{linea:"sibling model routing: OFF (BVSALA_GATEWAY_SIBLING_MODEL=1 turns it on)",aviso:false}:n?{linea:`sibling model r\
80
80
  outing: ARMED (${r}; ON if your licence includes sibling_model_routing; fail-closed). Changes the model you see in the response; cache reads cost 0.025\xD7 instead of 0.1\xD7 (list price). Turning it on mid\
81
81
  -conversation pays one cold prefix write, once. If the provider rejects the rewritten request (400), it is re-sent unchanged once`,aviso:false}:{linea:"sibling model routing: NOT ARMED - BVSALA_GATEWAY_E\
82
- LISION=0 turns off the levers",aviso:true}}var As=new Set;function Q(e,t){As.has(e)||(As.add(e),console.warn(t));}var Se="0.5.1",ko="x-bvsala-version";var Gt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(t){this.options=t,this.now=t.now??(()=>Date.now()),this.flushIntervalMs=
82
+ LISION=0 turns off the levers",aviso:true}}var As=new Set;function Q(e,t){As.has(e)||(As.add(e),console.warn(t));}var Se="0.5.2",ko="x-bvsala-version";var Gt=class{options;now;flushIntervalMs;maxBatch;maxBuffer;buffer=[];seatId;ci;timer;inflight=null;fallosSeguidos=0;constructor(t){this.options=t,this.now=t.now??(()=>Date.now()),this.flushIntervalMs=
83
83
  t.flushIntervalMs??15e3,this.maxBatch=t.maxBatch??50,this.maxBuffer=t.maxBuffer??1e3,this.ci=t.ci??false;}setSeat(t,n){t&&(this.seatId=t),this.ci=n;}record(t){let n=this.now();this.buffer.push({report:t,at:n});
84
84
  let r=dd(t);r&&this.buffer.push({report:r,at:n}),this.buffer.length>this.maxBuffer&&this.buffer.splice(0,this.buffer.length-this.maxBuffer),this.buffer.length>=this.maxBatch&&this.flush();}start(){this.
85
85
  timer||(this.timer=setInterval(()=>{this.flush();},this.flushIntervalMs),this.timer.unref?.());}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0),this.flush();}async stopAndDrain(t){this.timer&&
package/dist/index.d.ts CHANGED
@@ -154,7 +154,7 @@ declare function precioDeLista(model: string, at?: Date | number): CostModel | u
154
154
  * on the customer's machine. `test/version-declarada.test.ts` ties this
155
155
  * constant to package.json so the two can never drift.
156
156
  */
157
- declare const BV_SALA_VERSION = "0.5.1";
157
+ declare const BV_SALA_VERSION = "0.5.2";
158
158
 
159
159
  /** How the layer served a request that is eligible for a verification check. */
160
160
  type VerificationStratum =
@@ -1664,13 +1664,10 @@ interface SavingsReport {
1664
1664
  interface LicenseGate {
1665
1665
  isEntitled(feature: string): boolean;
1666
1666
  /**
1667
- * Whether there is an overall active (or in-grace) license. La consulta la
1668
- * puerta de entrada fail-closed del pipeline.
1667
+ * Whether there is an overall active (or in-grace) license. The pipeline's
1668
+ * fail-closed entry check reads it.
1669
1669
  *
1670
- * OBLIGATORIO. Fue opcional "por compatibilidad", y esa opcionalidad era el
1671
- * bypass: un gate al que le faltara el método dejaba pasar todas las
1672
- * peticiones con solo un aviso por consola. Para desarrollo local está
1673
- * `devUnlicensed: true`, que es explícito y no se cuela sin querer.
1670
+ * Required: a gate without it would let every request through.
1674
1671
  */
1675
1672
  isActive(): boolean;
1676
1673
  /**
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ for(let n of Yp[t]??[])if(!(n.vigenteDesde!==void 0&&e<n.vigenteDesde)&&!(n.vige
28
28
  p-research","o4-mini-deep-research","gpt-5.5-pro","gpt-5.4-pro","gpt-5.2-pro","gpt-5-pro","gpt-5.5-cyber","gemini-3.8-flash-tts","gemini-3.8-flash-lite-tts","gemini-3.1-flash-lite-image"],Xo={...qt,...Object.
29
29
  fromEntries(Qp.map(t=>[t,null]))},Xp=ti(Xo);function gn(t,e){let n=Ut(t);return n===void 0?void 0:Ka(n,Ja(e))}var ef=Object.fromEntries(Object.keys(Xo).map(t=>[t,Xo[t]===null?null:t]));function Ut(t){
30
30
  return ei(ef,Xp,t)??void 0}var tf=/^\d{4}-?\d{2}-?\d{2}$/;function st(t,e){let n=Ut(t);if(n===void 0)return;let r=t.lastIndexOf("/"),o=r>=0?t.slice(r+1):t;if(!(n!==t&&n!==o&&!tf.test(o.slice(n.length+
31
- 1))))return Ka(n,Ja(e))}var He="0.5.1",fr="x-bvsala-version";var nf=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function rf(t){return {v:1,task:t.task,goal:t.goal,rules:t.rules??[],facts:t.facts??[],refs:t.refs??[],...t.delta?{delta:t.delta}:{},outputContract:t.outputContract}}var mr=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
31
+ 1))))return Ka(n,Ja(e))}var He="0.5.2",fr="x-bvsala-version";var nf=["exact","task_equivalent","not_verified","bounded_degradation","rejected"];function rf(t){return {v:1,task:t.task,goal:t.goal,rules:t.rules??[],facts:t.facts??[],refs:t.refs??[],...t.delta?{delta:t.delta}:{},outputContract:t.outputContract}}var mr=class{id;exact=false;constructor(e="heuristic"){this.id=e;}count(e){if(e.length===0)return 0;let n=e.match(/[A-Za-z]+|\d+|\s+|[^\sA-Za-z\d]/g)??[],r=0;for(let o of n){let i=o[0];if(/\s/.test(i)){let s=(o.
32
32
  match(/\n/g)??[]).length;r+=s+Math.floor(Math.max(0,o.length-1)/2);}else /[A-Za-z]/.test(i)?r+=Math.max(1,Math.ceil(o.length/4)):/\d/.test(i)?r+=Math.max(1,Math.ceil(o.length/2)):r+=1;}return Math.max(r,
33
33
  Math.ceil(e.length/4))}},St=new mr;var hr=class{estimators=new Map;modelToTokenizer=new Map;fallbackId;constructor(e=St){this.fallbackId=e.id,this.estimators.set(e.id,e);}register(e){return this.estimators.set(e.id,e),this}mapModel(e,n){
34
34
  return this.modelToTokenizer.set(e,n),this}resolve(e){let n=e.tokenizer?this.estimators.get(e.tokenizer):void 0;if(n)return n;if(e.model){let r=this.modelToTokenizer.get(e.model);if(r){let o=this.estimators.
@@ -285,7 +285,7 @@ ulted to JSON"}}let a=i,c="json baseline (no challenger cleared thresholds)";for
285
285
  d>=this.minSavingsRatio&&l.total<a.total&&(a=l,c=`${l.format} saved ${u} tokens (${(d*100).toFixed(1)}%) vs json`);}return yc(a,s,c)}};function em(t,e,n){if(!t.decode)return false;try{return Ai(t.decode(e),
286
286
  n)}catch{return false}}function Ai(t,e){if(t===e)return true;if(t===null||e===null||typeof t!="object"||typeof e!="object")return false;let n=Array.isArray(t),r=Array.isArray(e);if(n||r){if(!n||!r||t.length!==e.
287
287
  length)return false;for(let s=0;s<t.length;s++)if(!Ai(t[s],e[s]))return false;return true}let o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)return false;for(let s of o)if(!Object.prototype.hasOwnProperty.
288
- call(e,s)||!Ai(t[s],e[s]))return false;return true}function yc(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function fe(t,e,n="$"){let r=[];return Oi(t,e,n,r),{valid:r.length===0,errors:r}}function tm(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
288
+ call(e,s)||!Ai(t[s],e[s]))return false;return true}function yc(t,e,n){return {chosen:t.format,encoded:t.encoded,instruction:t.instruction,candidateTokens:e,instructionOverheadTokens:t.instructionTokens,reason:n}}function de(t,e,n="$"){let r=[];return Oi(t,e,n,r),{valid:r.length===0,errors:r}}function tm(t){if(Array.isArray(t))return "array";if(t===null)return "null";switch(typeof t){case "object":return "object";case "\
289
289
  string":return "string";case "number":return "number";case "boolean":return "boolean";default:return}}function Oi(t,e,n,r){switch(e.enum&&!e.enum.some(i=>sm(i,t))&&r.push({path:n,message:"value not in enum"}),
290
290
  e.type??tm(t)){case "object":nm(t,e,n,r);break;case "array":rm(t,e,n,r);break;case "string":om(t,e,n,r);break;case "number":case "integer":im(t,e,n,r);break;case "boolean":typeof t!="boolean"&&r.push({path:n,
291
291
  message:"expected boolean"});break;case "null":t!==null&&r.push({path:n,message:"expected null"});break;}}function nm(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t)){r.push({path:n,
@@ -965,7 +965,7 @@ content has somewhere to fall":"output contract checks shape only: a well-formed
965
965
  motivo:"the cheap model returned an empty answer",comprobaciones:e};if(e.push("final-answer"),t.pidioHerramientas)return {acepta:false,motivo:"the cheap model asked to run tools: that is an action, not a \
966
966
  final answer, and the output contract cannot check it",comprobaciones:e};if(e.push("not-truncated"),t.finishReason==="length")return {acepta:false,motivo:"the cheap model's answer was cut off by maxOutput\
967
967
  Tokens",comprobaciones:e};if(e.push("output-contract"),!t.schema)return {acepta:false,motivo:"no output contract to verify against",comprobaciones:e};let n;try{n=JSON.parse(t.texto);}catch{return {acepta:false,
968
- motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=fe(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
968
+ motivo:"the cheap model's answer is not valid JSON",comprobaciones:e}}let r=de(n,t.schema);return r.valid?{acepta:true,motivo:"the cheap model's answer satisfies the output contract",comprobaciones:e}:{
969
969
  acepta:false,motivo:`the cheap model's answer does not satisfy the output contract (${r.errors.slice(0,3).map(i=>`${i.path}: ${i.message}`).join("; ")})`,comprobaciones:e}}function Yu(t,e){let n,r;try{n=
970
970
  JSON.parse(t),r=JSON.parse(e);}catch{return {divergen:false,motivo:"not comparable (at least one answer is not JSON)"}}let o=Eo(n),i=Eo(r);return o.length===0&&i.length===0?{divergen:false,motivo:"no comparab\
971
971
  le facts (free prose only)"}:vg(o,i)?{divergen:false,motivo:"the hard values agree"}:{divergen:true,motivo:"both answers satisfy the contract but disagree on at least one hard value; this is the signature \
@@ -1039,7 +1039,7 @@ n.inputPer1k:h,E=`+${S} tokens (${S>0?"the model wrote LESS":"no measured change
1039
1039
  ut tokens ($${b.toFixed(9)}): the compact contract saves ${h} input tokens and the measured output delta is ${E}; break-even at ${v}`}:{applied:true,reason:`net saving $${T.toFixed(9)}/request (${M.toFixed(
1040
1040
  1)} input tokens equivalent): the compact contract saves ${h} input tokens and the measured output delta is ${E}; break-even at ${v}`,plan:{compactSchema:i.compact,expand:c,compact:a,renamedKeys:i.renamed,
1041
1041
  codedEnumValues:i.coded,schemaTokensOriginal:d,schemaTokensCompact:p,modelledShapeSavingTokens:f,measuredOutputDeltaTokens:S,outputDeltaProvenance:C.procedencia,breakEvenOutputDeltaTokens:y,netSavingUsd:T}}}
1042
- function Lg(t,e,n,r){for(let o of r){if(!fe(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=sn(o,n,true);if(!fe(i,e).valid)return {
1042
+ function Lg(t,e,n,r){for(let o of r){if(!de(o,t).valid)return {ok:false,reason:"synthesised witness does not satisfy the caller's own schema; nothing can be proven"};let i=sn(o,n,true);if(!de(i,e).valid)return {
1043
1043
  ok:false,reason:"compact witness does not validate against the compact schema"};if(!ia(sn(i,n,false),o))return {ok:false,reason:"round trip is not the identity"}}return {ok:true}}function nd(t){return t.type==="ob\
1044
1044
  ject"||t.type==null&&t.properties!=null}function rd(t){return t.type==="array"||t.type==null&&t.items!=null}function $g(t){let e=t.enum;return !e||e.length===0||e.length>ed||!e.every(n=>typeof n=="stri\
1045
1045
  ng")?null:e}function sa(t,e){if(e>Ro)throw new RangeError("schema too deep");let n=$g(t);if(n){if(t.minLength!=null)return {compact:t,renamed:0,coded:0};let r=od(n,true);if(!r)return {compact:t,renamed:0,
@@ -1416,33 +1416,34 @@ neither consulted nor written for it. That is the default: two runs of an agent
1416
1416
  is unaffected. To include agentic requests, set `savings.semanticCache: "include-agentic"` after measuring it on your own traffic.');let l=this.now(),u=this.decidirCascada(e,s,c,o,l),d=this.costModelFor(
1417
1417
  u.modeloServido,l);o.record("canonicalize","done",{tenant:s.tenantId,contract:s.contractId}),o.record("policy",a.reasons.join("; ")||"no restrictions",{allowExactCache:a.allowExactCache,allowSemanticCache:a.
1418
1418
  allowSemanticCache,...a.sensitiveTopic!==null?{skipReason:"sensitive_topic",sensitiveTopic:a.sensitiveTopic}:{}});let p=this.tokensFor(this.assembleBaselinePrompt(e),e),h=$s(e),f,m=()=>f??=la(e);if(i.
1419
- baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let v=this.deps.resolvers.try(s);if(v)return i.avoidCall(p,this.tokensFor(v.text,e)),o.record("reso\
1420
- lver",v.resolver,{avoided:true}),this.finish(e,s,{text:v.text,data:v.data,storedAtMs:this.now()},"deterministic",i,d,o,Kn(),Yn(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(u,{servedModel:e.
1421
- model}))}let g=ko(s,{servedModel:u.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let v=await this.deps.exactCache.get(g),x=v?Gn(v.text):null;x!==null&&o.record("exact-cache","ignored: the s\
1422
- tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:x});let C=x===null?v:null;if(C){let S=this.creditoPorReferencia(bd(C.meta),{request:e,
1423
- cascada:u,toggles:c,huella:m,texto:C.text,claveLeida:g,calidad:()=>{let T=e.response?.schema;return !T||fe(C.data,T).valid}});return S.ok?i.avoidCallByReference(S.credit):(i.avoidCall(p,this.tokensFor(
1424
- C.text,e)),i.referenceRejected=S.reason),o.record("exact-cache","hit",{ageMs:this.now()-C.storedAtMs,basis:S.ok?"reference":"estimated",...S.ok?{}:{referenceRejected:S.reason},...S.ok&&S.outputNotCredited?
1425
- {outputNotCredited:S.outputNotCredited}:{}}),this.finish(e,s,C,"exact",i,d,o,Kn(),Yn(),this.now()-C.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(u))}o.record("exact-cache","miss");}let b=js(
1426
- s,{servedModel:u.modeloServido,deferrable:c.deferrable===true,toolDiscovery:c.toolDiscovery===true,...G(e)!=null?{maxOutputTokens:G(e)}:{}}),y=async()=>{try{return await this.expensivePath(n,e,s,a,c,i,d,o,
1427
- g,p,u,r,l)}catch(v){throw (n.falloDelProveedor||n.llamadas>0)&&Hb(v),v}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let C=this.deps.singleflight,S=typeof C.join=="function"?C.join(b):void 0;if(S){
1428
- let T=await S;return this.noReproducibles.has(T)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y()):(o.record("singleflight","coalesced",{key:b}),this.asCoalescedFollower(
1429
- T,p,this.tokensFor(T.text??"",e),d,e))}return o.record("singleflight","skipped (streaming: a streamed request never leads)"),y()}let{value:v,coalesced:x}=await this.deps.singleflight.run(b,y);if(x&&this.
1430
- noReproducibles.has(v))return o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y();if(x){o.record("singleflight","coalesced",{key:b});let C=this.creditoPorReferencia(this.
1431
- referenciasDeLider.get(v)??"absent",{request:e,cascada:u,toggles:c,huella:m,texto:v.text??"",claveLeida:void 0,calidad:()=>v.report.constraints.structurallyValid!==false&&v.report.qualityStatus!=="reject\
1432
- ed"});return this.asCoalescedFollower(v,p,this.tokensFor(v.text??"",e),d,e,C)}return v}return y()}async expensivePath(e,n,r,o,i,s,a,c,l,u,d,p,h){let f=this.entitled("semantic_cache"),m=null;if(i.semanticCache&&
1433
- i.semanticCache!=="include-agentic"&&this.deps.semanticCache&&ep(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&
1434
- i.semanticCache&&this.deps.semanticCache&&!f&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&f){let _=this.
1435
- deps.semanticCache,O=_.calibrated?await _.lookup(r,{agentic:o.isAgentic}):{hit:await _.find(r),probe:null},U=O.hit?Gn(O.hit.record.answer.text):null;U!==null&&c.record("semantic-cache","ignored: the s\
1436
- tored answer reads as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:U});let H=U===null?O.hit:null;if(m=O.probe,H)return s.avoidCall(u,this.tokensFor(H.record.
1437
- answer.text,n)),c.record("semantic-cache","hit",{confidence:H.confidence,similarity:H.similarity}),this.finish(n,r,H.record.answer,"semantic",s,a,c,Kn(),Yn(),H.ageMs,H.confidence,void 0,void 0,void 0,
1438
- this.informeDeCascada(d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:H});c.record("semantic-cache","miss",m?{calibration:m.reason,score:m.score}:void 0);}let g=i.router===false,b=g?Kn():this.deps.
1439
- router.classify(r);c.record("router",b.executionClass,{confidence:b.confidence,reason:b.reason});let y=this.planearBusquedaNativa(n,i,b.executionClass,g,d,a,c),v=y?y.seleccion:g?this.deps.toolSelector.
1440
- passthrough(n.tools):this.deps.toolSelector.select(r.normalizedText,n.tools,b.executionClass,r.toolsetHash);if(y||(this.avisarDeHerramientasPodadas(n,i,v,b.executionClass,g,d,a),this.avisarDeCatalogoGrande(
1441
- n,i,v,d,a)),s.actualTools=v.tools.length,v.droppedIds.length){let _=new Set(v.droppedIds),O=(n.tools??[]).filter(U=>_.has(U.id)).reduce((U,H)=>U+this.tokensFor(Qn(H),n),0);s.eliminate(O),c.record("too\
1442
- l-selector",v.reason,{dropped:v.droppedIds,eliminatedTokens:O});}s.baselineRetrieval=this.config.retriever?b.rounds:0;let x=await sd({execution:b.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.
1443
- maxRounds??b.rounds,maxDocuments:n.retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=
1444
- x.rounds,x.retrievedCount>0&&c.record("retrieval",`kept ${x.keptCount}/${x.retrievedCount}`,{rounds:x.rounds});let C=Yn(),S=[...n.messages],T=Ta(n.messages),M=false,E=x.docs.length>0?{role:"system",content:`\
1445
- Retrieved context \u2014 answer using only this evidence and cite sources by [id]:
1419
+ baselineInput=p,i.baselineOutput=h,i.baselineTools=e.tools?.length??0,c.deterministicResolvers!==false){let v=this.deps.resolvers.try(s),x=e.response?.schema,C=v&&x&&!de(v.data,x).valid?(o.record("resolv\
1420
+ er","skipped: its answer does not meet the output contract",{resolver:v.resolver,skipReason:"contract_mismatch"}),null):v;if(C)return i.avoidCall(p,this.tokensFor(C.text,e)),o.record("resolver",C.resolver,
1421
+ {avoided:true}),this.finish(e,s,{text:C.text,data:C.data,storedAtMs:this.now()},"deterministic",i,d,o,Kn(),Yn(),void 0,void 0,void 0,void 0,void 0,this.informeDeCascada(u,{servedModel:e.model}))}let g=ko(
1422
+ s,{servedModel:u.modeloServido});if(a.allowExactCache&&c.exactCache!==false){let v=await this.deps.exactCache.get(g),x=v?Gn(v.text):null;x!==null&&o.record("exact-cache","ignored: the stored answer reads\
1423
+ as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:x});let C=x===null?v:null;if(C){let S=this.creditoPorReferencia(bd(C.meta),{request:e,cascada:u,toggles:c,
1424
+ huella:m,texto:C.text,claveLeida:g,calidad:()=>{let T=e.response?.schema;return !T||de(C.data,T).valid}});return S.ok?i.avoidCallByReference(S.credit):(i.avoidCall(p,this.tokensFor(C.text,e)),i.referenceRejected=
1425
+ S.reason),o.record("exact-cache","hit",{ageMs:this.now()-C.storedAtMs,basis:S.ok?"reference":"estimated",...S.ok?{}:{referenceRejected:S.reason},...S.ok&&S.outputNotCredited?{outputNotCredited:S.outputNotCredited}:
1426
+ {}}),this.finish(e,s,C,"exact",i,d,o,Kn(),Yn(),this.now()-C.storedAtMs,void 0,void 0,void 0,void 0,this.informeDeCascada(u))}o.record("exact-cache","miss");}let b=js(s,{servedModel:u.modeloServido,deferrable:c.
1427
+ deferrable===true,toolDiscovery:c.toolDiscovery===true,...G(e)!=null?{maxOutputTokens:G(e)}:{}}),y=async()=>{try{return await this.expensivePath(n,e,s,a,c,i,d,o,g,p,u,r,l)}catch(v){throw (n.falloDelProveedor||
1428
+ n.llamadas>0)&&Hb(v),v}};if(a.allowSingleflight&&c.singleflight!==false){if(r){let C=this.deps.singleflight,S=typeof C.join=="function"?C.join(b):void 0;if(S){let T=await S;return this.noReproducibles.has(
1429
+ T)?(o.record("singleflight","not coalesced: the answer in flight cannot be replayed"),y()):(o.record("singleflight","coalesced",{key:b}),this.asCoalescedFollower(T,p,this.tokensFor(T.text??"",e),d,e))}
1430
+ return o.record("singleflight","skipped (streaming: a streamed request never leads)"),y()}let{value:v,coalesced:x}=await this.deps.singleflight.run(b,y);if(x&&this.noReproducibles.has(v))return o.record(
1431
+ "singleflight","not coalesced: the answer in flight cannot be replayed"),y();if(x){o.record("singleflight","coalesced",{key:b});let C=this.creditoPorReferencia(this.referenciasDeLider.get(v)??"absent",
1432
+ {request:e,cascada:u,toggles:c,huella:m,texto:v.text??"",claveLeida:void 0,calidad:()=>v.report.constraints.structurallyValid!==false&&v.report.qualityStatus!=="rejected"});return this.asCoalescedFollower(
1433
+ v,p,this.tokensFor(v.text??"",e),d,e,C)}return v}return y()}async expensivePath(e,n,r,o,i,s,a,c,l,u,d,p,h){let f=this.entitled("semantic_cache"),m=null;if(i.semanticCache&&i.semanticCache!=="include-a\
1434
+ gentic"&&this.deps.semanticCache&&ep(r,o)&&c.record("semantic-cache",'skipped: agentic traffic (default); set savings.semanticCache: "include-agentic" to include it'),o.allowSemanticCache&&i.semanticCache&&
1435
+ this.deps.semanticCache&&!f&&c.record("semantic-cache","degraded: feature not included in this license"),o.allowSemanticCache&&i.semanticCache&&this.deps.semanticCache&&f){let _=this.deps.semanticCache,
1436
+ O=_.calibrated?await _.lookup(r,{agentic:o.isAgentic}):{hit:await _.find(r),probe:null},U=O.hit?Gn(O.hit.record.answer.text):null;U!==null&&c.record("semantic-cache","ignored: the stored answer reads \
1437
+ as a refusal written as text (text_refusal); it is not replayed",{skipReason:"text_refusal",rule:U});let H=U===null?O.hit:null;if(m=O.probe,H)return s.avoidCall(u,this.tokensFor(H.record.answer.text,n)),
1438
+ c.record("semantic-cache","hit",{confidence:H.confidence,similarity:H.similarity}),this.finish(n,r,H.record.answer,"semantic",s,a,c,Kn(),Yn(),H.ageMs,H.confidence,void 0,void 0,void 0,this.informeDeCascada(
1439
+ d,{servedModel:n.model}),void 0,void 0,void 0,{semantico:H});c.record("semantic-cache","miss",m?{calibration:m.reason,score:m.score}:void 0);}let g=i.router===false,b=g?Kn():this.deps.router.classify(r);c.
1440
+ record("router",b.executionClass,{confidence:b.confidence,reason:b.reason});let y=this.planearBusquedaNativa(n,i,b.executionClass,g,d,a,c),v=y?y.seleccion:g?this.deps.toolSelector.passthrough(n.tools):
1441
+ this.deps.toolSelector.select(r.normalizedText,n.tools,b.executionClass,r.toolsetHash);if(y||(this.avisarDeHerramientasPodadas(n,i,v,b.executionClass,g,d,a),this.avisarDeCatalogoGrande(n,i,v,d,a)),s.actualTools=
1442
+ v.tools.length,v.droppedIds.length){let _=new Set(v.droppedIds),O=(n.tools??[]).filter(U=>_.has(U.id)).reduce((U,H)=>U+this.tokensFor(Qn(H),n),0);s.eliminate(O),c.record("tool-selector",v.reason,{dropped:v.
1443
+ droppedIds,eliminatedTokens:O});}s.baselineRetrieval=this.config.retriever?b.rounds:0;let x=await sd({execution:b.executionClass,query:r.normalizedText,maxRounds:n.retrieval?.maxRounds??b.rounds,maxDocuments:n.
1444
+ retrieval?.maxDocuments??5},{...this.config.retriever?{retriever:this.config.retriever}:{},...this.config.reranker?{reranker:this.config.reranker}:{}});s.actualRetrieval=x.rounds,x.retrievedCount>0&&c.
1445
+ record("retrieval",`kept ${x.keptCount}/${x.retrievedCount}`,{rounds:x.rounds});let C=Yn(),S=[...n.messages],T=Ta(n.messages),M=false,E=x.docs.length>0?{role:"system",content:`Retrieved context \u2014 answer \
1446
+ using only this evidence and cite sources by [id]:
1446
1447
 
1447
1448
  `+x.docs.map((_,O)=>`[${_.source??_.id??`doc${O+1}`}]
1448
1449
  ${_.text}`).join(`
@@ -1453,21 +1454,21 @@ tokenizer}:{}});let U=this.tokensFor(C.encoded+C.instruction,n);s.compress(O,U),
1453
1454
  `:"")+C.encoded}),c.record("serialization",C.chosen,{reason:C.reason,jsonTokens:O,chosenTokens:U});}else Xn(S,{role:"system",content:_}),c.record("serialization","json-compact",{reason:"format selector\
1454
1455
  disabled; sent compact JSON"});}if(E&&Xn(S,E),(i.compression===true||i.compression==="auto")&&o.allowCompression&&this.config.compressor&&this.entitled("long_context_compression")){let _=this.config.compressionEconomics??
1455
1456
  {},O=_o(n.model,_),U={compressorCostTokens:_.compressorCostTokens??0,..._.minimumContextTokens!=null?{minimumContextTokens:_.minimumContextTokens}:{},..._.minimumNetTokens!=null?{minimumNetTokens:_.minimumNetTokens}:
1456
- {}},H=0,re=0;for(let pe of S)pe.role==="system"?H+=1:re+=this.tokensFor(pe.content,n);let ot=this.tokensFor(this.assemblePromptText(S,v.tools),n),de=Li({...U,contextTokens:re,projectedEliminable:re}),
1457
- ue=0,Z=0,$e=false,Ie=de.reason;if(de.compress){let pe=[];for(let ee of S){if(ee.role==="system"){pe.push(ee);continue}let mn=this.tokensFor(ee.content,n),hn=await this.config.compressor.compress({text:ee.
1458
- content}),Wa=!hn.skipped&&hn.fidelityPassed&&xc(ee.content,hn.compressed),Ga=Wa?this.tokensFor(hn.compressed,n):mn;Wa&&Ga<mn?(pe.push({...ee,content:hn.compressed}),ue+=mn,Z+=Ga):pe.push(ee);}let it=this.
1459
- tokensFor(this.assemblePromptText(pe,v.tools),n),Te=Li({...U,contextTokens:re,projectedEliminable:ue-Z}),dr=ld({originalTokens:ot,compressedTokens:it,tier:O,..._.prefix?{prefix:_.prefix}:{},compressorCostTokens:U.
1460
- compressorCostTokens});Z>=ue?Ie="no fidelity-passed net reduction":Te.compress?dr.comprimir?($e=true,Ie=dr.razon,M=pe.slice(0,T).some((ee,mn)=>ee.content!==S[mn]?.content),S=pe,s.compress(ue,Z)):Ie=dr.razon:
1457
+ {}},H=0,re=0;for(let fe of S)fe.role==="system"?H+=1:re+=this.tokensFor(fe.content,n);let ot=this.tokensFor(this.assemblePromptText(S,v.tools),n),pe=Li({...U,contextTokens:re,projectedEliminable:re}),
1458
+ ue=0,Z=0,$e=false,Ie=pe.reason;if(pe.compress){let fe=[];for(let ee of S){if(ee.role==="system"){fe.push(ee);continue}let mn=this.tokensFor(ee.content,n),hn=await this.config.compressor.compress({text:ee.
1459
+ content}),Wa=!hn.skipped&&hn.fidelityPassed&&xc(ee.content,hn.compressed),Ga=Wa?this.tokensFor(hn.compressed,n):mn;Wa&&Ga<mn?(fe.push({...ee,content:hn.compressed}),ue+=mn,Z+=Ga):fe.push(ee);}let it=this.
1460
+ tokensFor(this.assemblePromptText(fe,v.tools),n),Te=Li({...U,contextTokens:re,projectedEliminable:ue-Z}),dr=ld({originalTokens:ot,compressedTokens:it,tier:O,..._.prefix?{prefix:_.prefix}:{},compressorCostTokens:U.
1461
+ compressorCostTokens});Z>=ue?Ie="no fidelity-passed net reduction":Te.compress?dr.comprimir?($e=true,Ie=dr.razon,M=fe.slice(0,T).some((ee,mn)=>ee.content!==S[mn]?.content),S=fe,s.compress(ue,Z)):Ie=dr.razon:
1461
1462
  Ie=Te.reason;}$e||(ue=0,Z=0),c.record("compression",$e?"applied":"skipped",{reason:Ie,before:ue,after:Z,contextTokens:re,promptTokens:ot,cacheTierMinimum:O.minimumCacheTokens,protectedSystemMessages:H,
1462
1463
  prefixRewritten:M}),s.compressionReport={originalTokens:ue,compressedTokens:Z,protectedSpans:H,fidelityPassed:true};}if(i.elision!==false&&o.allowElision&&this.entitled("tool_result_elision")){let _=ad(S);if(_.
1463
1464
  indices.length>0){let O=this.tokensFor(ca,n),U=0;for(let H of _.indices){let re=this.tokensFor(S[H].content,n);U+=Math.max(0,re-O);}(_.indices.some(H=>H<T)&&(M=true),S=cd(S,_.indices),s.eliminate(U),
1464
1465
  s.elididoLocal+=U),c.record("elision","applied",{elided:_.indices.length,eliminatedTokens:U,grossBytes:_.bytesOriginales,live:ka});}else c.record("elision","skipped",{reason:"no old/large t\
1465
1466
  ool_result over the age\xD7size threshold"});}let $=rv(this.config.toolOutputCompaction,i.toolOutputCompaction);if($&&!this.entitled("long_context_compression")&&c.record("tool-output-compaction","degr\
1466
1467
  aded: feature not included in this license"),$&&o.allowCompression&&this.entitled("long_context_compression")){let _=Ec(S,$),O=0,U=0,H=0,re=0,ot={};if(_.compactados.length>0){let ue=S.slice();for(let Z of _.
1467
- compactados){let $e=S[Z.indice],Ie=this.tokensFor($e.content,n),pe=this.tokensFor(Z.texto,n);ue[Z.indice]={...$e,content:Z.texto},O+=Ie,U+=pe,Z.enLaCola?H+=Math.max(0,Ie-pe):re+=Math.max(0,Ie-pe);for(let it of Z.
1468
- aplicadas)ot[it]=(ot[it]??0)+1;}S=ue,s.compress(O,U),s.compactedLocal+=Math.max(0,O-U);}let de=_o(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",_.compactados.length>0?"appl\
1469
- ied":"skipped",{compacted:_.compactados.length,before:O,after:U,tailSavedTokens:H,replayedSavedTokens:re,transforms:ot,fileViewsKeptVerbatim:_.vistasDeFichero,exceptedTools:_.exceptuados,cacheWriteMultiplier:de.
1470
- cacheWriteMultiplier,cacheReadMultiplier:de.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written \
1468
+ compactados){let $e=S[Z.indice],Ie=this.tokensFor($e.content,n),fe=this.tokensFor(Z.texto,n);ue[Z.indice]={...$e,content:Z.texto},O+=Ie,U+=fe,Z.enLaCola?H+=Math.max(0,Ie-fe):re+=Math.max(0,Ie-fe);for(let it of Z.
1469
+ aplicadas)ot[it]=(ot[it]??0)+1;}S=ue,s.compress(O,U),s.compactedLocal+=Math.max(0,O-U);}let pe=_o(n.model,this.config.compressionEconomics);c.record("tool-output-compaction",_.compactados.length>0?"appl\
1470
+ ied":"skipped",{compacted:_.compactados.length,before:O,after:U,tailSavedTokens:H,replayedSavedTokens:re,transforms:ot,fileViewsKeptVerbatim:_.vistasDeFichero,exceptedTools:_.exceptuados,cacheWriteMultiplier:pe.
1471
+ cacheWriteMultiplier,cacheReadMultiplier:pe.cacheReadMultiplier,note:"counted in tokens.compressedInput only; never priced into savings or commission. each tail token saved is one token fewer written \
1471
1472
  now and re-read on every later turn"});}let A=n.response?.schema,I=A&&i.outputCodebook===true?td(A,_=>this.tokensFor(_,n),a,{evidencia:this.memoriaDelCodebook.resolver(d.modeloServido,Zn(n),i.outputCodebookMeasuredOutputDeltaTokens)}):
1472
1473
  null;I&&c.record("output-codebook",I.applied?"applied":"skipped",{reason:I.reason,...I.applied?{renamedKeys:I.plan.renamedKeys,codedEnumValues:I.plan.codedEnumValues,schemaTokensOriginal:I.plan.schemaTokensOriginal,
1473
1474
  schemaTokensCompact:I.plan.schemaTokensCompact,modelledShapeSavingTokens:I.plan.modelledShapeSavingTokens,measuredOutputDeltaTokens:I.plan.measuredOutputDeltaTokens,outputDeltaProvenance:I.plan.outputDeltaProvenance,
@@ -1505,33 +1506,33 @@ toolCalls?.length??0)>0});this.verjaDeCascada.registrar(d.bucket,!H.acepta);let
1505
1506
  mple accepted":"sample escalated",{candidateModel:d.candidato,reason:H.motivo,sampleCost:Bt.coste,...re?{diverged:re.divergen,divergence:re.motivo}:{},note:"measurement only: this answer was NEVER ser\
1506
1507
  ved. The escalation rate it feeds is a money figure, not a quality one"});}catch(_){c.record("model-cascade","sample failed (measurement only; the answer is unaffected)",{error:_ instanceof Error?_.message:
1507
1508
  String(_)});}let ar=ge,xt=true,Ve={},wt=(D.toolCalls?.length??0)>0;if(wt&&(xt=null,A&&c.record("validation","n/a: model requested tool calls (the output contract applies to the final answer)")),A&&!wt){let _=et(
1508
- ge),O=_.ok?fe(_.value,A):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},U=false;_.ok&&_.rescatado!=null&&O.valid&&(ge=_.rescatado,U=true,c.record("validation","rescued-locally",{reason:"the model \
1509
+ ge),O=_.ok?de(_.value,A):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},U=false;_.ok&&_.rescatado!=null&&O.valid&&(ge=_.rescatado,U=true,c.record("validation","rescued-locally",{reason:"the model \
1509
1510
  wrapped valid JSON in prose or a markdown fence; it was extracted locally instead of paying a repair call"})),!O.valid&&nv(O.errors)&&this.contratosQueIncumplen.add(Zn(n));let H=D.finishReason==="leng\
1510
- th",re=xa(D),ot=!O.valid&&O.errors.some(de=>/not a valid regular expression/.test(de.message));if(!O.valid&&ot)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no \
1511
+ th",re=xa(D),ot=!O.valid&&O.errors.some(pe=>/not a valid regular expression/.test(pe.message));if(!O.valid&&ot)c.record("validation","repair-skipped",{reason:"schema defect (uncompilable pattern); no \
1511
1512
  output can satisfy it, a retry is a wasted call",errors:O.errors}),this.avisar("esquema-roto","[bvsala] The response contract has a `pattern` that is not a valid regex, so no response can satisfy it. \
1512
1513
  NOT retried (it would be a paid call for the same failure). Fix the schema's `pattern`."),Ve.reparacion={outcome:"skipped",skipReason:"schema_defect"};else if(!O.valid&&re)c.record("validation","repai\
1513
1514
  r-skipped",{reason:(D.refusal!==void 0?"the provider refused the request (a refusal message instead of an answer)":"the provider refused the request (finish reason content_filter)")+"; a repair on the\
1514
- same model would be refused, and may be billed, again",model:Le}),Ve.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!O.valid&&H){let de=Xu(A,$e=>this.tokensFor($e,n)),ue=G(n)??null,
1515
- Z=de!==null&&ue!=null&&de<=ue;Z&&this.contratosQueIncumplen.add(Zn(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate aga\
1516
- in",maxOutputTokens:G(n)??null,outputTokens:D.usage.outputTokens,model:Le,...de!==null?{schemaAllowsTokens:de}:{},learnedValueLimits:Z}),this.avisarDeTruncado(n,Le,D.usage.outputTokens,de,Z),Ve.reparacion=
1517
- {outcome:"skipped",skipReason:"output_truncated"};}else if(!O.valid&&j.backend==="none"){let de=O.errors.slice(0,5).map(ee=>`- ${ee.path}: ${ee.message}`).join(`
1515
+ same model would be refused, and may be billed, again",model:Le}),Ve.reparacion={outcome:"skipped",skipReason:"provider_refusal"};else if(!O.valid&&H){let pe=Xu(A,$e=>this.tokensFor($e,n)),ue=G(n)??null,
1516
+ Z=pe!==null&&ue!=null&&pe<=ue;Z&&this.contratosQueIncumplen.add(Zn(n)),c.record("validation","repair-skipped",{reason:"output truncated by maxOutputTokens; a retry with the same cap would truncate aga\
1517
+ in",maxOutputTokens:G(n)??null,outputTokens:D.usage.outputTokens,model:Le,...pe!==null?{schemaAllowsTokens:pe}:{},learnedValueLimits:Z}),this.avisarDeTruncado(n,Le,D.usage.outputTokens,pe,Z),Ve.reparacion=
1518
+ {outcome:"skipped",skipReason:"output_truncated"};}else if(!O.valid&&j.backend==="none"){let pe=O.errors.slice(0,5).map(ee=>`- ${ee.path}: ${ee.message}`).join(`
1518
1519
  `),ue=[{role:"user",content:`Your previous reply did not satisfy the required JSON contract.
1519
1520
 
1520
1521
  Previous reply:
1521
1522
  ${ge}
1522
1523
 
1523
1524
  Problems found:
1524
- ${de}
1525
+ ${pe}
1525
1526
 
1526
1527
  Return ONLY the corrected JSON object. Keep the same content; fix only what is listed.`}],Z=this.tokensFor(this.assemblePromptText(ue),n),$e=s.sentInputLocal>0?s.actualInput/s.sentInputLocal:1,Ie=Math.
1527
- round($e*Z),pe=Math.min(D.usage.outputTokens,G(n)??Number.POSITIVE_INFINITY),it=Ie/1e3*un.inputPer1k+pe/1e3*un.outputPer1k,Te=this.config.skipRepairAboveBaseline?s.estimateCost(un):void 0;if(Te!=null&&
1528
+ round($e*Z),fe=Math.min(D.usage.outputTokens,G(n)??Number.POSITIVE_INFINITY),it=Ie/1e3*un.inputPer1k+fe/1e3*un.outputPer1k,Te=this.config.skipRepairAboveBaseline?s.estimateCost(un):void 0;if(Te!=null&&
1528
1529
  Te.baselineEstimate>0&&Te.actual+it>Te.baselineEstimate&&Te!=null)c.record("validation","repair-skipped",{reason:"repairing would cost more than not using the layer at all; the invalid answer is serve\
1529
1530
  d as-is and reported as invalid",errors:O.errors,baselineUsd:Te.baselineEstimate,actualUsd:Te.actual,repairEstimateUsd:it}),this.avisar("reparacion-mas-cara-que-el-baseline",`[bvsala] The answer did n\
1530
1531
  ot satisfy the output contract, and repairing it would have cost MORE than sending this request without the layer at all (baseline ~$${Te.baselineEstimate}, already spent ~$${Te.actual}, repair ~$${it.
1531
1532
  toFixed(6)}). The repair was skipped and the invalid answer is returned with \`constraints.structurallyValid: false\` \u2014 check it before using it. This combination is usually a request carrying both tool\
1532
1533
  s and an output contract; see the adapter warning for the cheaper shapes.`),Ve.reparacion={outcome:"skipped",skipReason:"would_cost_more_than_no_layer"};else {s.retries=1,c.record("validation","repair-\
1533
1534
  attempt",{errors:O.errors}),D=await this.llamarProveedor({model:Le,messages:ue,schema:A,...G(n)!=null?{maxOutputTokens:G(n)}:{}},e),qa=D.usage,s.actualLlm+=1,s.actualInput+=D.usage.inputTokens,s.actualOutput+=
1534
- D.usage.outputTokens,s.repairOutput+=D.usage.outputTokens,s.repairInput+=D.usage.inputTokens,D.unbilledRefusal===true&&s.unbilledCall(D.usage),s.sentInputLocal+=Z,ge=D.text;let ee=et(ge);O=ee.ok?fe(ee.value,
1535
+ D.usage.outputTokens,s.repairOutput+=D.usage.outputTokens,s.repairInput+=D.usage.inputTokens,D.unbilledRefusal===true&&s.unbilledCall(D.usage),s.sentInputLocal+=Z,ge=D.text;let ee=et(ge);O=ee.ok?de(ee.value,
1535
1536
  A):{valid:false,errors:[{path:"$",message:"not valid JSON"}]},ee.ok&&(ar=ee.value,ee.rescatado!=null&&O.valid&&(ge=ee.rescatado)),Ve.reparacion={outcome:O.valid?"repaired":"still_invalid"};}}else _.ok&&(ar=
1536
1537
  _.value);xt=O.valid,!O.valid&&Ve.reparacion===void 0&&(Ve.reparacion={outcome:"skipped",skipReason:"decode_time_constraint"}),Ve.validacion={resultado:O.valid?"passed":"failed",errores:O.errors.length,
1537
1538
  desenvuelto:U},c.record("validation",xt?"valid":"invalid");}let Up=this.now()-_e,Vp=Zb(ar),zt={text:ge,data:ar,rendered:Vp,storedAtMs:this.now()},be=this.informeDeDiferido(i,D,Le,za),De=this.informeDeEscrituras(
@@ -1624,7 +1625,7 @@ ther"},reason:d}}escriturasSinLlamada(e){if(e.savings?.standalone===true)return
1624
1625
  er's prompt cache for this request"}}respaldaFaltaDeCapacidad(e,n,r){return e.deferrable!==true||r!==null||this.config.priceLevers?.onCapacityError!=="standard"||Rt(this.config.provider)===void 0?false:n instanceof
1625
1626
  Error&&/^provider (429|503)\b/.test(n.message)}diferidoSinLlamada(e){if(e.savings?.deferrable===true)return {credited:false,creditedLedger:"none",latency:"not applicable: no provider call was made for this \
1626
1627
  request.",reason:"no provider call was made, so no processing tier was served and none is credited; the call was avoided outright, which is worth more than any tier discount on it"}}finish(e,n,r,o,i,s,a,c,l,u,d,p,h="\
1627
- none",f=0,m,g,b,y,v){let x=e.response?.schema,C,S=p===null?null:p??(x?(()=>{let E=fe(r.data,x);return C={resultado:E.valid?"passed":"failed",errores:E.errors.length,desenvuelto:false},E.valid})():true),T=C&&
1628
+ none",f=0,m,g,b,y,v){let x=e.response?.schema,C,S=p===null?null:p??(x?(()=>{let E=de(r.data,x);return C={resultado:E.valid?"passed":"failed",errores:E.errors.length,desenvuelto:false},E.valid})():true),T=C&&
1628
1629
  !v?.validacion?{...v,validacion:C}:v,M=this.buildReport(e,n,o,i,s,a,c,l,u,d,S,h,f,m,g??this.diferidoSinLlamada(e),b,y??this.escriturasSinLlamada(e),T);return {requestId:M.requestId,data:r.data,text:r.text,
1629
1630
  ...r.rendered!==void 0?{rendered:r.rendered}:{},report:M}}buildReport(e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g,b,y){let v=o.estimateCost(i),x=o.avoidedLlm===0&&o.actualLlm>0&&!o.servedUnbilledRefusal?ju(f?.servedModel??
1630
1631
  e.model,i,{leidos:Math.max(0,o.providerCachedInput-o.unbilledCachedInput),escritos:o.nativeCacheWriteInput,escritos1h:o.nativeCacheWrite1hInput,...o.nativeCacheMarkedByLayer!==null?{marcadoPorLaCapa:o.
@@ -1646,7 +1647,7 @@ i.actualInput=p.usage.inputTokens,i.actualOutput=p.usage.outputTokens,i.baseline
1646
1647
  p.unbilledRefusal===true?(i.unbilledCall(p.usage),i.servedUnbilledRefusal=true):(i.nativeCacheWrite(p.usage.cacheWriteInputTokens??0,p.usage.cacheWrite1hInputTokens??0),i.nativeCacheMarkedByLayer=false);let f=In(
1647
1648
  e.model);f>1&&p.unbilledRefusal!==true&&(p.usage.cacheWriteInputTokens??0)>0&&i.providerCacheWritePremium(p.usage.cacheWriteInputTokens??0,f,s),p.usage.complete===false&&(i.callsWithoutUsage=1);let m=p.text,
1648
1649
  g=true,b={...o?{}:{origen:"fail_open"},final:{...me(p.finishReason,p.finishReasonDetail),...G(e)!=null?{topeDelLlamante:G(e)}:{}}},y=(p.toolCalls?.length??0)>0;if(y&&(g=null),c&&!y){let x=et(p.text),C=x.
1649
- ok?fe(x.value,c).errors.length:1;g=C===0,b.validacion={resultado:g?"passed":"failed",errores:C,desenvuelto:false},x.ok&&(m=x.value);}let v=this.buildReport(e,a,"miss",i,s,n,Kn(),Yn(),void 0,void 0,g,"none",
1650
+ ok?de(x.value,c).errors.length:1;g=C===0,b.validacion={resultado:g?"passed":"failed",errores:C,desenvuelto:false},x.ok&&(m=x.value);}let v=this.buildReport(e,a,"miss",i,s,n,Kn(),Yn(),void 0,void 0,g,"none",
1650
1651
  h,void 0,e.savings?.deferrable===true?{credited:false,creditedLedger:"none",latency:o?"unchanged: on the Measure license (shadow mode) no processing tier is requested, so this request was scheduled exactly\
1651
1652
  as an ordinary one.":"unchanged: the fail-open path asks for no processing tier, so this request was scheduled exactly as an ordinary one.",reason:o?"the Measure license runs the layer in shadow mode\
1652
1653
  : the request goes to the provider unchanged, so no cheaper tier is asked for; upgrade to a paid plan to turn the lever on":"the optimizer failed and this request went out on the direct fail-open path\
@@ -1677,7 +1678,7 @@ try{return n.resolve({...e.tokenizer?{tokenizer:e.tokenizer}:{},model:e.model}).
1677
1678
  e)}precioConocido(e,n=this.now()){return this.precioDelCliente(e)??gn(e,n)}precioDelCliente(e){let n=this.config.costModels;if(!n)return;let r=n[e];if(r)return r;let o=e.indexOf("/");if(o>=0){let i=n[e.
1678
1679
  slice(o+1)];if(i)return i}}precioDocumentado(e){return this.precioDelCliente(e)??st(e,this.now())}costModelFor(e,n=this.now()){let r=this.precioConocido(e,n);return r||(this.config.defaultCostModel?this.
1679
1680
  config.defaultCostModel:(this.avisar(`precio-ilustrativo:${e}`,`[bv-sala] no cost model configured for "${e}"; falling back to the ILLUSTRATIVE default price. Dollar figures will not match your bill. \
1680
- Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Ls))}};function Jb(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=et(typeof e.text=="string"?e.text:"");return n.ok&&fe(
1681
+ Pass { costModels: { "${e}": { inputPer1k, outputPer1k } } }.`),Ls))}};function Jb(t,e){if((e.toolCalls?.length??0)>0||!t.schema)return "none";let n=et(typeof e.text=="string"?e.text:"");return n.ok&&de(
1681
1682
  n.value,t.schema).valid?"met":"missed"}function et(t){try{return {ok:!0,value:JSON.parse(t)}}catch{}for(let e of Kb(t))try{return {ok:!0,value:JSON.parse(e),rescatado:e}}catch{continue}return {ok:false}}function Kb(t){
1682
1683
  let e=[],n=/```[ \t]*[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g;for(let r of t.matchAll(n)){let o=r[1]?.trim();o&&e.push(o);}for(let r of ["{","["]){let o=t.indexOf(r);if(o===-1)continue;let i=Yb(t,o);i&&
1683
1684
  e.push(i);}return e}function Yb(t,e){let n=t[e],r=n==="{"?"}":"]",o=0,i=false,s=false;for(let a=e;a<t.length;a+=1){let c=t[a];if(i){s?s=false:c==="\\"?s=true:c==='"'&&(i=false);continue}if(c==='"'){i=true;continue}if(c===
@@ -1764,7 +1765,7 @@ m=Br({modelo:n.model,uso:u.usage,tierServido:p,origen:h,tierLeidoDe:c?"cuerpo":"
1764
1765
  length>0?{toolCalls:u.toolCalls}:{},...me(u.finishReason,u.finishReasonDetail),usage:u.usage,...p?{servedTier:p}:{}};if(!m.ok)return {...g,reason:Sv(m.motivo,p)};let b={amount:m.importe,basis:m.basis,standardCost:Bo(
1765
1766
  m.costeEstandar),appliedCost:Bo(m.costeAplicado),pricesCheckedOn:m.consultado,basisReason:m.motivoBasis};return {...g,tierSaving:b,reason:`billed at the "${p}" tier; this request's usage was priced at \
1766
1767
  the standard and at the batch published rate cards, component by component (${(m.factorEfectivo*100).toFixed(1)}% of standard)`}}function wv(t,e){if(!e||(t.toolCalls?.length??0)>0)return {};let n=et(typeof t.
1767
- text=="string"?t.text:"");return n.ok?fe(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function Sv(t,e){switch(t){case "no-served-tier":return "the provider repo\
1768
+ text=="string"?t.text:"");return n.ok?de(n.value,e).valid?{data:n.value,contract:"met"}:{contract:"missed"}:{contract:"missed"}}function Sv(t,e){switch(t){case "no-served-tier":return "the provider repo\
1768
1769
  rted no service tier for this result, so the rate it was billed at cannot be known: nothing is credited";case "unknown-tier":return `the provider reports the "${e}" tier for this result, a tier this lay\
1769
1770
  er has no published rate for: nothing is credited`;case "standard-rate-tier":return `the provider reports the "${e}" tier for this result, which is not billed below the standard rate: nothing is credite\
1770
1771
  d`;case "no-tier-price":return "there is no published batch price for this model from this provider (or it has expired): nothing is credited";case "no-standard-price":return "this model has no list price \
@@ -1977,4 +1978,4 @@ tokens.eliminatedOutput}})}var kT=qt,xT=gn,wT=pr;/*! Bundled license information
1977
1978
  @noble/curves/abstract/edwards.js:
1978
1979
  @noble/curves/ed25519.js:
1979
1980
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
1980
- */export{ns as AnthropicProvider,He as BV_SALA_VERSION,Un as BatchSubmitError,Or as COMPACTION_TRANSFORMS,gc as COMPACT_ROWS_INSTRUCTION,Ee as CalibrationStateError,Ls as DEFAULT_COST_MODEL,Cc as DEFAULT_MIN_SAVED_CHARS,br as ExactTokenizer,En as ExecutionRouter,_n as FormatSelector,is as GoogleProvider,mr as HeuristicEstimator,gi as InMemoryCacheBreakpointStore,bn as InMemoryExactCache,mi as InMemorySemanticCache,_r as InMemoryToolSetFreezer,fi as LOCAL_EMBEDDING_THRESHOLD,ze as LicenseError,vr as MODELS_BY_ENCODING,Lr as MockProvider,Ki as OpenAICompatibleProvider,wT as PRICES_AS_OF,kT as PRICE_CATALOG,nf as QUALITY_STATUSES,Cr as ResolverRegistry,Dn as SchemaRegistry,vn as Singleflight,we as StreamAbortedError,hr as TokenizerRegistry,Rn as ToolSelector,ic as arithmeticResolver,lf as calibrateSemanticFloor,Di as compactRowsSerializer,$i as compactToolOutput,bc as createCompactRowsSerializer,bi as createDefaultResolvers,rf as createHandoff,xm as createMockProvider,Jv as createSavingsLayer,Ii as csvSerializer,Ei as decodeCompactRows,gr as defaultTokenizerRegistry,Vf as emptyState,mc as encodeCompactRows,St as heuristicEstimator,Ep as instrumentSavingsLayer,Ti as jsonCompactSerializer,xT as listPrice,pi as localEmbedding,Hf as mergeDelta,cm as noopCompressor,am as providerNativeBackend,Tp as recordSavingsOnSpan,ni as registerExactTokenizer,Wf as renderState,nr as savingsSpanAttributes,gp as toCsv,Ap as toFocusRows,Rp as toLangfuseGeneration,Dp as toSavingsSeries,fe as validateAgainstSchema};
1981
+ */export{ns as AnthropicProvider,He as BV_SALA_VERSION,Un as BatchSubmitError,Or as COMPACTION_TRANSFORMS,gc as COMPACT_ROWS_INSTRUCTION,Ee as CalibrationStateError,Ls as DEFAULT_COST_MODEL,Cc as DEFAULT_MIN_SAVED_CHARS,br as ExactTokenizer,En as ExecutionRouter,_n as FormatSelector,is as GoogleProvider,mr as HeuristicEstimator,gi as InMemoryCacheBreakpointStore,bn as InMemoryExactCache,mi as InMemorySemanticCache,_r as InMemoryToolSetFreezer,fi as LOCAL_EMBEDDING_THRESHOLD,ze as LicenseError,vr as MODELS_BY_ENCODING,Lr as MockProvider,Ki as OpenAICompatibleProvider,wT as PRICES_AS_OF,kT as PRICE_CATALOG,nf as QUALITY_STATUSES,Cr as ResolverRegistry,Dn as SchemaRegistry,vn as Singleflight,we as StreamAbortedError,hr as TokenizerRegistry,Rn as ToolSelector,ic as arithmeticResolver,lf as calibrateSemanticFloor,Di as compactRowsSerializer,$i as compactToolOutput,bc as createCompactRowsSerializer,bi as createDefaultResolvers,rf as createHandoff,xm as createMockProvider,Jv as createSavingsLayer,Ii as csvSerializer,Ei as decodeCompactRows,gr as defaultTokenizerRegistry,Vf as emptyState,mc as encodeCompactRows,St as heuristicEstimator,Ep as instrumentSavingsLayer,Ti as jsonCompactSerializer,xT as listPrice,pi as localEmbedding,Hf as mergeDelta,cm as noopCompressor,am as providerNativeBackend,Tp as recordSavingsOnSpan,ni as registerExactTokenizer,Wf as renderState,nr as savingsSpanAttributes,gp as toCsv,Ap as toFocusRows,Rp as toLangfuseGeneration,Dp as toSavingsSeries,de as validateAgainstSchema};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bivelio/savings-layer",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "The savings layer for your LLM bill: a library inside your code that lets through only what has to be paid for and returns a SavingsReport per call, measured with your provider's own meter and kept apart from estimates. Commercial license, paid per seat, commission only on measured savings. Your prompts never leave your infrastructure.",
5
5
  "keywords": [
6
6
  "llm",