@lensmcp/protocol-types 1.26.36 → 1.26.38

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 (79) hide show
  1. package/index.d.ts +7 -0
  2. package/index.js +1 -1
  3. package/lib/account-drain.js +1 -1
  4. package/lib/ai-cache-facts.js +1 -1
  5. package/lib/ai-cache-verdict.js +1 -1
  6. package/lib/ai-cache.js +3 -3
  7. package/lib/ai-call-groups.js +2 -2
  8. package/lib/ai-call-row.js +3 -3
  9. package/lib/ai-call.js +9 -9
  10. package/lib/ai-compare.js +3 -3
  11. package/lib/ai-context.js +6 -6
  12. package/lib/ai-origins.js +9 -9
  13. package/lib/ai-together.js +5 -5
  14. package/lib/bounded-clone.js +1 -1
  15. package/lib/bounded-map.js +1 -1
  16. package/lib/bounded-writer.js +1 -1
  17. package/lib/canvas-attachments.js +1 -1
  18. package/lib/canvas-catalog.d.ts +10 -5
  19. package/lib/canvas-catalog.js +1 -1
  20. package/lib/canvas-chat.js +2 -2
  21. package/lib/canvas-diagram.d.ts +130 -0
  22. package/lib/canvas-diagram.js +8 -0
  23. package/lib/canvas-editing.js +4 -4
  24. package/lib/canvas-frame-policy.js +1 -1
  25. package/lib/canvas-hub.js +1 -1
  26. package/lib/canvas.d.ts +9 -5
  27. package/lib/capture-demand.js +1 -1
  28. package/lib/dashboard-path.js +1 -1
  29. package/lib/dashboard.d.ts +2 -0
  30. package/lib/delivery-actions.d.ts +257 -0
  31. package/lib/delivery-actions.js +1 -0
  32. package/lib/delivery-status.d.ts +201 -4
  33. package/lib/docker-errors.js +1 -1
  34. package/lib/docker-jobs.js +1 -1
  35. package/lib/docker-report.js +2 -2
  36. package/lib/docker-runs.js +3 -3
  37. package/lib/error-cause.js +6 -6
  38. package/lib/error-dismissal.js +1 -1
  39. package/lib/error-verdict.js +3 -3
  40. package/lib/event-loop.js +1 -1
  41. package/lib/expected-failure.js +2 -2
  42. package/lib/finding-proof.js +1 -1
  43. package/lib/flood-guard.js +1 -1
  44. package/lib/goal-design.js +1 -1
  45. package/lib/goal-main-follow.d.ts +103 -0
  46. package/lib/goal-main-follow.js +1 -0
  47. package/lib/goal-number.js +1 -1
  48. package/lib/goal-process.d.ts +449 -0
  49. package/lib/goal-process.js +1 -0
  50. package/lib/goal-review.d.ts +126 -0
  51. package/lib/goal-review.js +6 -0
  52. package/lib/host-agents.js +1 -1
  53. package/lib/lens-hosts.js +1 -1
  54. package/lib/lint-coverage.js +1 -1
  55. package/lib/lint-ignores.js +2 -2
  56. package/lib/log-query.js +1 -1
  57. package/lib/metrics-reset.js +1 -1
  58. package/lib/overseer-findings.js +1 -1
  59. package/lib/peers.d.ts +31 -31
  60. package/lib/peers.js +1 -1
  61. package/lib/perf-rules.js +1 -1
  62. package/lib/pod-memory.js +1 -1
  63. package/lib/producer-health.js +1 -1
  64. package/lib/pull-requests.d.ts +33 -2
  65. package/lib/remote-instances.js +1 -1
  66. package/lib/source.d.ts +414 -0
  67. package/lib/source.js +1 -0
  68. package/lib/sources.js +1 -1
  69. package/lib/static-checks.js +1 -1
  70. package/lib/system-report.js +1 -1
  71. package/lib/team-decide.d.ts +191 -0
  72. package/lib/team-decide.js +1 -0
  73. package/lib/team-design.d.ts +43 -7
  74. package/lib/team-design.js +1 -1
  75. package/lib/team-library.d.ts +2 -0
  76. package/lib/team-roadmap.d.ts +44 -2
  77. package/lib/team.d.ts +63 -3
  78. package/lib/team.js +1 -1
  79. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -72,8 +72,14 @@ export * from './lib/changes.js';
72
72
  export * from './lib/pull-requests.js';
73
73
  export * from './lib/goal-number.js';
74
74
  export * from './lib/delivery-status.js';
75
+ export * from './lib/goal-process.js';
76
+ export * from './lib/goal-review.js';
77
+ export * from './lib/delivery-actions.js';
78
+ export * from './lib/goal-main-follow.js';
79
+ export * from './lib/source.js';
75
80
  export * from './lib/main-mirror.js';
76
81
  export * from './lib/team-design.js';
82
+ export * from './lib/team-decide.js';
77
83
  export * from './lib/team-library.js';
78
84
  export * from './lib/team-skills.js';
79
85
  export * from './lib/system-report.js';
@@ -90,6 +96,7 @@ export { PROOF_ACTIONS, NOT_RUN_KINDS } from './lib/team-delivery.js';
90
96
  export type { NotRunKind } from './lib/team-delivery.js';
91
97
  export * from './lib/canvas.js';
92
98
  export * from './lib/canvas-catalog.js';
99
+ export * from './lib/canvas-diagram.js';
93
100
  export * from './lib/canvas-frame-policy.js';
94
101
  export * from './lib/canvas-attachments.js';
95
102
  export * from './lib/canvas-editing.js';
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";export*from"./lib/schema-version.js";export*from"./lib/source-location.js";export*from"./lib/context.js";export*from"./lib/event.js";export*from"./lib/node.js";export*from"./lib/edge.js";export*from"./lib/attributes.js";export*from"./lib/producer-health.js";export*from"./lib/resources.js";export*from"./lib/tokens.js";export*from"./lib/capture-demand.js";export*from"./lib/bounded-clone.js";export*from"./lib/bounded-map.js";export*from"./lib/flood-guard.js";export*from"./lib/dashboard.js";export*from"./lib/dashboard-path.js";export*from"./lib/lens-hosts.js";export*from"./lib/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.js";export*from"./lib/lint-ignores.js";export*from"./lib/static-checks.js";export*from"./lib/log-query.js";export*from"./lib/error-dismissal.js";export*from"./lib/expected-failure.js";export*from"./lib/error-verdict.js";export*from"./lib/finding-proof.js";export*from"./lib/error-cause.js";export*from"./lib/metrics-reset.js";export*from"./lib/ai-content.js";export*from"./lib/http-exchange.js";export*from"./lib/ai-call.js";export*from"./lib/ai-call-row.js";export*from"./lib/ai-call-groups.js";export*from"./lib/ai-context.js";export*from"./lib/ai-cache-facts.js";export*from"./lib/ai-cache.js";export*from"./lib/ai-cache-verdict.js";export*from"./lib/ai-together.js";export*from"./lib/ai-origins.js";export*from"./lib/ai-playground.js";export*from"./lib/ai-compare.js";export*from"./lib/pod-memory.js";export*from"./lib/perf-rules.js";export*from"./lib/sources.js";export*from"./lib/page-visit.js";export*from"./lib/replay.js";export*from"./lib/event-loop.js";export*from"./lib/workspace-actions.js";export*from"./lib/docker-jobs.js";export*from"./lib/docker-report.js";export*from"./lib/docker-runs.js";export*from"./lib/docker-errors.js";export*from"./lib/peers.js";export*from"./lib/hosts.js";export*from"./lib/cluster-hosts.js";export*from"./lib/dashboard-updates.js";export*from"./lib/accounts.js";export*from"./lib/account-drain.js";export*from"./lib/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.js";export*from"./lib/conversations.js";export*from"./lib/backlog.js";export*from"./lib/team-review-changes.js";export*from"./lib/goal-outcome.js";export*from"./lib/role-fidelity.js";export*from"./lib/goal-retro.js";export*from"./lib/follow-ups.js";export*from"./lib/changes.js";export*from"./lib/pull-requests.js";export*from"./lib/goal-number.js";export*from"./lib/delivery-status.js";export*from"./lib/main-mirror.js";export*from"./lib/team-design.js";export*from"./lib/team-library.js";export*from"./lib/team-skills.js";export*from"./lib/system-report.js";export*from"./lib/overseer-findings.js";export*from"./lib/overseer-rounds.js";export*from"./lib/goal-design.js";export*from"./lib/overseer-messages.js";export*from"./lib/team-roadmap.js";export*from"./lib/team-prompts.js";export{PROOF_ACTIONS,NOT_RUN_KINDS}from"./lib/team-delivery.js";export*from"./lib/canvas.js";export*from"./lib/canvas-catalog.js";export*from"./lib/canvas-frame-policy.js";export*from"./lib/canvas-attachments.js";export*from"./lib/canvas-editing.js";export*from"./lib/canvas-chat.js";export*from"./lib/canvas-hub.js";
1
+ "use strict";export*from"./lib/schema-version.js";export*from"./lib/source-location.js";export*from"./lib/context.js";export*from"./lib/event.js";export*from"./lib/node.js";export*from"./lib/edge.js";export*from"./lib/attributes.js";export*from"./lib/producer-health.js";export*from"./lib/resources.js";export*from"./lib/tokens.js";export*from"./lib/capture-demand.js";export*from"./lib/bounded-clone.js";export*from"./lib/bounded-map.js";export*from"./lib/flood-guard.js";export*from"./lib/dashboard.js";export*from"./lib/dashboard-path.js";export*from"./lib/lens-hosts.js";export*from"./lib/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.js";export*from"./lib/lint-ignores.js";export*from"./lib/static-checks.js";export*from"./lib/log-query.js";export*from"./lib/error-dismissal.js";export*from"./lib/expected-failure.js";export*from"./lib/error-verdict.js";export*from"./lib/finding-proof.js";export*from"./lib/error-cause.js";export*from"./lib/metrics-reset.js";export*from"./lib/ai-content.js";export*from"./lib/http-exchange.js";export*from"./lib/ai-call.js";export*from"./lib/ai-call-row.js";export*from"./lib/ai-call-groups.js";export*from"./lib/ai-context.js";export*from"./lib/ai-cache-facts.js";export*from"./lib/ai-cache.js";export*from"./lib/ai-cache-verdict.js";export*from"./lib/ai-together.js";export*from"./lib/ai-origins.js";export*from"./lib/ai-playground.js";export*from"./lib/ai-compare.js";export*from"./lib/pod-memory.js";export*from"./lib/perf-rules.js";export*from"./lib/sources.js";export*from"./lib/page-visit.js";export*from"./lib/replay.js";export*from"./lib/event-loop.js";export*from"./lib/workspace-actions.js";export*from"./lib/docker-jobs.js";export*from"./lib/docker-report.js";export*from"./lib/docker-runs.js";export*from"./lib/docker-errors.js";export*from"./lib/peers.js";export*from"./lib/hosts.js";export*from"./lib/cluster-hosts.js";export*from"./lib/dashboard-updates.js";export*from"./lib/accounts.js";export*from"./lib/account-drain.js";export*from"./lib/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.js";export*from"./lib/conversations.js";export*from"./lib/backlog.js";export*from"./lib/team-review-changes.js";export*from"./lib/goal-outcome.js";export*from"./lib/role-fidelity.js";export*from"./lib/goal-retro.js";export*from"./lib/follow-ups.js";export*from"./lib/changes.js";export*from"./lib/pull-requests.js";export*from"./lib/goal-number.js";export*from"./lib/delivery-status.js";export*from"./lib/goal-process.js";export*from"./lib/goal-review.js";export*from"./lib/delivery-actions.js";export*from"./lib/goal-main-follow.js";export*from"./lib/source.js";export*from"./lib/main-mirror.js";export*from"./lib/team-design.js";export*from"./lib/team-decide.js";export*from"./lib/team-library.js";export*from"./lib/team-skills.js";export*from"./lib/system-report.js";export*from"./lib/overseer-findings.js";export*from"./lib/overseer-rounds.js";export*from"./lib/goal-design.js";export*from"./lib/overseer-messages.js";export*from"./lib/team-roadmap.js";export*from"./lib/team-prompts.js";export{PROOF_ACTIONS,NOT_RUN_KINDS}from"./lib/team-delivery.js";export*from"./lib/canvas.js";export*from"./lib/canvas-catalog.js";export*from"./lib/canvas-diagram.js";export*from"./lib/canvas-frame-policy.js";export*from"./lib/canvas-attachments.js";export*from"./lib/canvas-editing.js";export*from"./lib/canvas-chat.js";export*from"./lib/canvas-hub.js";
@@ -1 +1 @@
1
- "use strict";var m=Object.defineProperty;var d=(t,n)=>m(t,"name",{value:n,configurable:!0});var l=Object.defineProperty,c=d((t,n)=>l(t,"name",{value:n,configurable:!0}),"o");export const FIVE_TIGHT_LEFT=10;const A=36e5;export function drainStand(t,n){const e=t.find(a=>a.name==="weekly")??t.find(a=>a.week)??t[0];if(!e)return;const r=e.five?void 0:t.find(a=>a.five),s=r?{window:r,tight:r.left<=10}:void 0,i=e.resetsAt,o=i!==void 0?Math.max(1/60,(i-n)/36e5):void 0,f=o!==void 0?e.left/o:void 0,v=s?.tight?"tight":f===void 0?"no-pace":"open";return{budget:e,left:e.left,...i!==void 0?{resetsAt:i}:{},...o!==void 0&&f!==void 0?{hours:o,pace:f}:{},...s?{five:s}:{},now:v}}d(drainStand,"drainStand"),c(drainStand,"drainStand");export const DRAIN_GROUP={open:0,"no-pace":1,tight:2},drainPaceKey=c(t=>t===void 0?-1:Math.round(t*100),"drainPaceKey");export function drainOrder(t,n){return DRAIN_GROUP[t.now]-DRAIN_GROUP[n.now]||drainPaceKey(n.pace)-drainPaceKey(t.pace)||(t.resetsAt??1/0)-(n.resetsAt??1/0)||n.left-t.left||t.nick.localeCompare(n.nick)}d(drainOrder,"drainOrder"),c(drainOrder,"drainOrder");const p=/spend|extra/i,u=/^weekly\s+(\S.*)$/i;export function drainWindows(t,n){return t.filter(e=>!p.test(e.name)&&(e.name==="5-hour"||e.name==="weekly"||u.test(e.name)||e.minutes!==void 0)).map(e=>{const r=!!e.reset||e.resetsAt!==void 0&&e.resetsAt<=n,s=Math.max(0,Math.min(100,r?0:e.usedPercent)),i=e.name==="5-hour"||e.minutes===300,o=!i&&(e.name==="weekly"||u.test(e.name)||(e.minutes??0)>=10080);return{name:e.name,left:100-s,...!r&&e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...o?{week:!0}:{},...i?{five:!0}:{}}}).sort((e,r)=>e.left-r.left||(e.resetsAt??1/0)-(r.resetsAt??1/0)||0)}d(drainWindows,"drainWindows"),c(drainWindows,"drainWindows");
1
+ "use strict";var m=Object.defineProperty;var d=(t,n)=>m(t,"name",{value:n,configurable:!0});var p=Object.defineProperty,c=d((t,n)=>p(t,"name",{value:n,configurable:!0}),"d"),w=Object.defineProperty,f=c((t,n)=>w(t,"name",{value:n,configurable:!0}),"o");export const FIVE_TIGHT_LEFT=10;const k=36e5;export function drainStand(t,n){const e=t.find(s=>s.name==="weekly")??t.find(s=>s.week)??t[0];if(!e)return;const r=e.five?void 0:t.find(s=>s.five),a=r?{window:r,tight:r.left<=10}:void 0,i=e.resetsAt,o=i!==void 0?Math.max(1/60,(i-n)/36e5):void 0,v=o!==void 0?e.left/o:void 0,l=a?.tight?"tight":v===void 0?"no-pace":"open";return{budget:e,left:e.left,...i!==void 0?{resetsAt:i}:{},...o!==void 0&&v!==void 0?{hours:o,pace:v}:{},...a?{five:a}:{},now:l}}d(drainStand,"drainStand"),c(drainStand,"drainStand"),f(drainStand,"drainStand");export const DRAIN_GROUP={open:0,"no-pace":1,tight:2},drainPaceKey=f(t=>t===void 0?-1:Math.round(t*100),"drainPaceKey");export function drainOrder(t,n){return DRAIN_GROUP[t.now]-DRAIN_GROUP[n.now]||drainPaceKey(n.pace)-drainPaceKey(t.pace)||(t.resetsAt??1/0)-(n.resetsAt??1/0)||n.left-t.left||t.nick.localeCompare(n.nick)}d(drainOrder,"drainOrder"),c(drainOrder,"drainOrder"),f(drainOrder,"drainOrder");const A=/spend|extra/i,u=/^weekly\s+(\S.*)$/i;export function drainWindows(t,n){return t.filter(e=>!A.test(e.name)&&(e.name==="5-hour"||e.name==="weekly"||u.test(e.name)||e.minutes!==void 0)).map(e=>{const r=!!e.reset||e.resetsAt!==void 0&&e.resetsAt<=n,a=Math.max(0,Math.min(100,r?0:e.usedPercent)),i=e.name==="5-hour"||e.minutes===300,o=!i&&(e.name==="weekly"||u.test(e.name)||(e.minutes??0)>=10080);return{name:e.name,left:100-a,...!r&&e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...o?{week:!0}:{},...i?{five:!0}:{}}}).sort((e,r)=>e.left-r.left||(e.resetsAt??1/0)-(r.resetsAt??1/0)||0)}d(drainWindows,"drainWindows"),c(drainWindows,"drainWindows"),f(drainWindows,"drainWindows");
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var o=(e,t)=>l(e,"name",{value:t,configurable:!0});var c=Object.defineProperty,i=o((e,t)=>c(e,"name",{value:t,configurable:!0}),"a");export const AI_GUIDANCE_STALE_DAYS=45,AI_GUIDANCE_SOURCES={openaiCaching:{url:"https://developers.openai.com/api/docs/guides/prompt-caching",readAt:"2026-11-17",how:"summary"},openaiPricing:{url:"https://developers.openai.com/api/docs/pricing",readAt:"2026-11-17",how:"summary"},anthropicCaching:{url:"https://platform.claude.com/docs/en/build-with-claude/prompt-caching",readAt:"2026-11-17",how:"page"}};export function aiGuidanceAge(e,t=Date.now(),a=45){const s=Date.parse(`${e}T00:00:00Z`);if(!Number.isFinite(s))return{stale:!0};const p=Math.max(0,Math.floor((t-s)/864e5));return{days:p,stale:p>a}}o(aiGuidanceAge,"aiGuidanceAge"),i(aiGuidanceAge,"aiGuidanceAge");const n=6e4,r=60*n;export const AI_CACHE_TTL_MS={"5m":5*n,"1h":r,"30m":30*n,"12h":12*r,"24h":24*r,in_memory:10*n},AI_CACHE_FACTS=[{id:"openai.min-tokens",provider:"openai",models:"GPT-5.6 and later",says:"A prefix is cached from 1,024 visible input tokens; hidden system content does not count. Earlier models: the minimum depends on the request settings.",value:1024,source:"openaiCaching"},{id:"openai.modes",provider:"openai",models:"GPT-5.6 and later",says:'`prompt_cache_options.mode`: `implicit` puts one breakpoint at the end of the latest eligible message (a user message, the last tool response of a group, the last developer message of the opening group); `explicit` caches only where a content block carries `prompt_cache_breakpoint: { "mode": "explicit" }`.',value:["implicit","explicit"],source:"openaiCaching"},{id:"openai.no-breakpoint",provider:"openai",models:"GPT-5.6 and later",says:"Explicit mode with no breakpoint: the request reads and writes nothing.",source:"openaiCaching"},{id:"openai.max-writes",provider:"openai",models:"GPT-5.6 and later",says:"A request creates at most four cache writes; in implicit mode the implicit breakpoint takes one of them.",value:4,source:"openaiCaching"},{id:"openai.instructions",provider:"openai",models:"GPT-5.6 and later",says:"Top-level `instructions` cannot hold a breakpoint: reusable instructions go in an `input_text` block of a developer message.",source:"openaiCaching"},{id:"openai.after-last",provider:"openai",models:"GPT-5.6 and later",says:"Content after the last breakpoint is billed at the plain input rate, with no write charge.",source:"openaiCaching"},{id:"openai.ttl",provider:"openai",models:"GPT-5.6 and later",says:'`ttl: "30m"` (the default) writes at 1.25\xD7 the input rate; `"12h"` at 2.5\xD7. A breakpoint may set its own `ttl`. Moving 30-minute coverage to 12 hours is a new 12-hour write, with no credit for the earlier one.',value:["30m","12h"],source:"openaiCaching"},{id:"openai.write-x",provider:"openai",models:"GPT-5.6 and later",says:"Write multipliers on the input rate, by lifetime: 30m 1.25\xD7, 12h 2.5\xD7 \u2014 total rates, not surcharges.",value:["30m:1.25","12h:2.5"],source:"openaiCaching"},{id:"openai.read-x",provider:"openai",models:"GPT-5.6 and later",says:"A read costs 0.1\xD7 the input rate; 0.05\xD7 on GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol and GPT-6.1 Terra, whatever the lifetime.",value:.1,source:"openaiCaching"},{id:"openai.prewarm",provider:"openai",models:"GPT-5.6 and later",says:"`prompt_cache_options.prewarm: true` writes the cache and generates no output, billed at the write rate of its lifetime; the real request follows with the same prefix.",source:"openaiCaching"},{id:"openai.key",provider:"openai",models:"GPT-5.6 and later",says:"`prompt_cache_key` is optional (routing is automatic); a key keeps the cache apart per key.",source:"openaiCaching"},{id:"openai.usage",provider:"openai",models:"GPT-5.6 and later",says:"`input_tokens` includes reads and writes. `input_tokens_details.cached_tokens` are reads (writes excluded); `input_tokens_details.cache_write_tokens` are writes, split in `cache_write_tokens_details.ttl_30m_tokens` and `ttl_12h_tokens`. Plain input = input \u2212 cached \u2212 written.",source:"openaiCaching"},{id:"openai.ends-reuse",provider:"openai",models:"GPT-5.6 and later",says:"Reuse needs the whole rendered prefix to match up to a breakpoint. These settings are part of the cached prefix: `model`, `tools`, `parallel_tool_calls`, `text.format`, `reasoning.effort`, `text.verbosity`, `context_management`.",value:["model","tools","parallel_tool_calls","text.format","reasoning.effort","text.verbosity","context_management"],source:"openaiCaching"},{id:"openai.lookup",provider:"openai",models:"GPT-5.6 and later",says:"Lookup walks from the longest prefix to the shortest, on the machine the request lands on; it considers the first 2 and the latest 50 breakpoints.",source:"openaiCaching"},{id:"openai.concurrent",provider:"openai",models:"all",says:"The page does not say when a write becomes readable by a request sent at the same moment; it says a prewarm\u2019s follow-up should wait for the prewarm to complete.",source:"openaiCaching"},{id:"openai.tpm",provider:"openai",models:"all",says:"Cached input tokens still count toward the tokens-per-minute limit.",source:"openaiCaching"},{id:"openai.retention",provider:"openai",models:"before GPT-5.6",says:"Earlier models cache implicitly only, with `prompt_cache_retention`: `in_memory` (about 5\u201310 minutes of inactivity, up to an hour) or `24h` (the default without Zero Data Retention).",value:["in_memory","24h"],source:"openaiCaching"},{id:"anthropic.breakpoints",provider:"anthropic",models:"all Claude models",says:'A block marked `cache_control: { "type": "ephemeral" }` ends a cacheable prefix, in the order tools \u2192 system \u2192 messages; up to 4 breakpoints. A top-level `cache_control` (automatic caching) puts one on the last cacheable block and takes one of the 4. No `cache_control`: nothing is cached.',value:4,source:"anthropicCaching"},{id:"anthropic.ttl",provider:"anthropic",models:"all Claude models",says:'The default lifetime is 5 minutes, refreshed free on each read; `"ttl": "1h"` lives an hour. Longer lifetimes must come before shorter ones.',value:["5m","1h"],source:"anthropicCaching"},{id:"anthropic.write-x",provider:"anthropic",models:"all Claude models",says:"A 5-minute write costs 1.25\xD7 the input rate, a 1-hour write 2\xD7.",value:["5m:1.25","1h:2"],source:"anthropicCaching"},{id:"anthropic.read-x",provider:"anthropic",models:"all Claude models",says:"A read costs 0.1\xD7 the input rate; 0.05\xD7 on Claude Opus 5.5 and Sonnet 5.5; 0.025\xD7 on Claude Fable and Mythos 5.1 and 5.2.",value:.1,source:"anthropicCaching"},{id:"anthropic.min-tokens",provider:"anthropic",models:"by model",says:"The shortest cacheable prompt: 512 tokens on Claude Opus 5.5, Opus 5, Sonnet 5.5, Haiku 5.5 and Fable/Mythos 5.x; 1,024 on Sonnet 5, Opus 4.8 and Sonnet 4.x; 2,048 on Opus 4.7; 4,096 on Opus 4.5/4.6 and Haiku 4.5. Shorter prompts are not cached, without an error.",value:512,source:"anthropicCaching"},{id:"anthropic.lookback",provider:"anthropic",models:"all Claude models",says:"A breakpoint looks back at most 20 blocks for an entry earlier requests wrote; writes happen only at breakpoints.",value:20,source:"anthropicCaching"},{id:"anthropic.concurrent",provider:"anthropic",models:"all Claude models",says:"A cache entry becomes available only after the first response starts: for parallel requests to hit it, wait for the first response before sending the rest.",source:"anthropicCaching"},{id:"anthropic.usage",provider:"anthropic",models:"all Claude models",says:"`cache_read_input_tokens` are reads, `cache_creation_input_tokens` writes (split in `cache_creation.ephemeral_5m_input_tokens` / `ephemeral_1h_input_tokens`), `input_tokens` the rest after the last breakpoint.",source:"anthropicCaching"},{id:"anthropic.ends-reuse",provider:"anthropic",models:"all Claude models",says:"A change to the tools ends every level; web search, citations and speed end system and messages; `tool_choice`, images, thinking and effort settings end the messages level.",value:["tools","tool_choice","thinking","output_config.effort","speed"],source:"anthropicCaching"}];export function aiCacheFact(e){const t=AI_CACHE_FACTS.find(a=>a.id===e);return t?{...t,from:AI_GUIDANCE_SOURCES[t.source]}:void 0}o(aiCacheFact,"aiCacheFact"),i(aiCacheFact,"aiCacheFact");export const openaiNewCache=i(e=>!!e&&/^(?:openai\/)?gpt-(?:5\.(?:[6-9]|\d{2,})|[6-9]|\d{2,})/.test(e),"openaiNewCache");export function aiCacheMinTokens(e,t){if(e!=="anthropic")return 1024;const a=(t??"").replace(/^anthropic\//,"");return/^claude-(?:opus-4-[56]|haiku-4-5)/.test(a)?4096:/^claude-opus-4-7/.test(a)?2048:/^claude-(?:sonnet-5(?!-5)|opus-4-8|sonnet-4|opus-4(?:-1)?(?![-\d]))/.test(a)?1024:512}o(aiCacheMinTokens,"aiCacheMinTokens"),i(aiCacheMinTokens,"aiCacheMinTokens");export const aiDefaultTtl=i((e,t)=>e==="anthropic"?"5m":openaiNewCache(t)?"30m":"24h","aiDefaultTtl");
1
+ "use strict";var l=Object.defineProperty;var o=(e,a)=>l(e,"name",{value:a,configurable:!0});var d=Object.defineProperty,n=o((e,a)=>d(e,"name",{value:a,configurable:!0}),"o"),h=Object.defineProperty,i=n((e,a)=>h(e,"name",{value:a,configurable:!0}),"a");export const AI_GUIDANCE_STALE_DAYS=45,AI_GUIDANCE_SOURCES={openaiCaching:{url:"https://developers.openai.com/api/docs/guides/prompt-caching",readAt:"2026-11-17",how:"summary"},openaiPricing:{url:"https://developers.openai.com/api/docs/pricing",readAt:"2026-11-17",how:"summary"},anthropicCaching:{url:"https://platform.claude.com/docs/en/build-with-claude/prompt-caching",readAt:"2026-11-17",how:"page"}};export function aiGuidanceAge(e,a=Date.now(),t=45){const p=Date.parse(`${e}T00:00:00Z`);if(!Number.isFinite(p))return{stale:!0};const c=Math.max(0,Math.floor((a-p)/864e5));return{days:c,stale:c>t}}o(aiGuidanceAge,"aiGuidanceAge"),n(aiGuidanceAge,"aiGuidanceAge"),i(aiGuidanceAge,"aiGuidanceAge");const r=6e4,s=60*r;export const AI_CACHE_TTL_MS={"5m":5*r,"1h":s,"30m":30*r,"12h":12*s,"24h":24*s,in_memory:10*r},AI_CACHE_FACTS=[{id:"openai.min-tokens",provider:"openai",models:"GPT-5.6 and later",says:"A prefix is cached from 1,024 visible input tokens; hidden system content does not count. Earlier models: the minimum depends on the request settings.",value:1024,source:"openaiCaching"},{id:"openai.modes",provider:"openai",models:"GPT-5.6 and later",says:'`prompt_cache_options.mode`: `implicit` puts one breakpoint at the end of the latest eligible message (a user message, the last tool response of a group, the last developer message of the opening group); `explicit` caches only where a content block carries `prompt_cache_breakpoint: { "mode": "explicit" }`.',value:["implicit","explicit"],source:"openaiCaching"},{id:"openai.no-breakpoint",provider:"openai",models:"GPT-5.6 and later",says:"Explicit mode with no breakpoint: the request reads and writes nothing.",source:"openaiCaching"},{id:"openai.max-writes",provider:"openai",models:"GPT-5.6 and later",says:"A request creates at most four cache writes; in implicit mode the implicit breakpoint takes one of them.",value:4,source:"openaiCaching"},{id:"openai.instructions",provider:"openai",models:"GPT-5.6 and later",says:"Top-level `instructions` cannot hold a breakpoint: reusable instructions go in an `input_text` block of a developer message.",source:"openaiCaching"},{id:"openai.after-last",provider:"openai",models:"GPT-5.6 and later",says:"Content after the last breakpoint is billed at the plain input rate, with no write charge.",source:"openaiCaching"},{id:"openai.ttl",provider:"openai",models:"GPT-5.6 and later",says:'`ttl: "30m"` (the default) writes at 1.25\xD7 the input rate; `"12h"` at 2.5\xD7. A breakpoint may set its own `ttl`. Moving 30-minute coverage to 12 hours is a new 12-hour write, with no credit for the earlier one.',value:["30m","12h"],source:"openaiCaching"},{id:"openai.write-x",provider:"openai",models:"GPT-5.6 and later",says:"Write multipliers on the input rate, by lifetime: 30m 1.25\xD7, 12h 2.5\xD7 \u2014 total rates, not surcharges.",value:["30m:1.25","12h:2.5"],source:"openaiCaching"},{id:"openai.read-x",provider:"openai",models:"GPT-5.6 and later",says:"A read costs 0.1\xD7 the input rate; 0.05\xD7 on GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol and GPT-6.1 Terra, whatever the lifetime.",value:.1,source:"openaiCaching"},{id:"openai.prewarm",provider:"openai",models:"GPT-5.6 and later",says:"`prompt_cache_options.prewarm: true` writes the cache and generates no output, billed at the write rate of its lifetime; the real request follows with the same prefix.",source:"openaiCaching"},{id:"openai.key",provider:"openai",models:"GPT-5.6 and later",says:"`prompt_cache_key` is optional (routing is automatic); a key keeps the cache apart per key.",source:"openaiCaching"},{id:"openai.usage",provider:"openai",models:"GPT-5.6 and later",says:"`input_tokens` includes reads and writes. `input_tokens_details.cached_tokens` are reads (writes excluded); `input_tokens_details.cache_write_tokens` are writes, split in `cache_write_tokens_details.ttl_30m_tokens` and `ttl_12h_tokens`. Plain input = input \u2212 cached \u2212 written.",source:"openaiCaching"},{id:"openai.ends-reuse",provider:"openai",models:"GPT-5.6 and later",says:"Reuse needs the whole rendered prefix to match up to a breakpoint. These settings are part of the cached prefix: `model`, `tools`, `parallel_tool_calls`, `text.format`, `reasoning.effort`, `text.verbosity`, `context_management`.",value:["model","tools","parallel_tool_calls","text.format","reasoning.effort","text.verbosity","context_management"],source:"openaiCaching"},{id:"openai.lookup",provider:"openai",models:"GPT-5.6 and later",says:"Lookup walks from the longest prefix to the shortest, on the machine the request lands on; it considers the first 2 and the latest 50 breakpoints.",source:"openaiCaching"},{id:"openai.concurrent",provider:"openai",models:"all",says:"The page does not say when a write becomes readable by a request sent at the same moment; it says a prewarm\u2019s follow-up should wait for the prewarm to complete.",source:"openaiCaching"},{id:"openai.tpm",provider:"openai",models:"all",says:"Cached input tokens still count toward the tokens-per-minute limit.",source:"openaiCaching"},{id:"openai.retention",provider:"openai",models:"before GPT-5.6",says:"Earlier models cache implicitly only, with `prompt_cache_retention`: `in_memory` (about 5\u201310 minutes of inactivity, up to an hour) or `24h` (the default without Zero Data Retention).",value:["in_memory","24h"],source:"openaiCaching"},{id:"anthropic.breakpoints",provider:"anthropic",models:"all Claude models",says:'A block marked `cache_control: { "type": "ephemeral" }` ends a cacheable prefix, in the order tools \u2192 system \u2192 messages; up to 4 breakpoints. A top-level `cache_control` (automatic caching) puts one on the last cacheable block and takes one of the 4. No `cache_control`: nothing is cached.',value:4,source:"anthropicCaching"},{id:"anthropic.ttl",provider:"anthropic",models:"all Claude models",says:'The default lifetime is 5 minutes, refreshed free on each read; `"ttl": "1h"` lives an hour. Longer lifetimes must come before shorter ones.',value:["5m","1h"],source:"anthropicCaching"},{id:"anthropic.write-x",provider:"anthropic",models:"all Claude models",says:"A 5-minute write costs 1.25\xD7 the input rate, a 1-hour write 2\xD7.",value:["5m:1.25","1h:2"],source:"anthropicCaching"},{id:"anthropic.read-x",provider:"anthropic",models:"all Claude models",says:"A read costs 0.1\xD7 the input rate; 0.05\xD7 on Claude Opus 5.5 and Sonnet 5.5; 0.025\xD7 on Claude Fable and Mythos 5.1 and 5.2.",value:.1,source:"anthropicCaching"},{id:"anthropic.min-tokens",provider:"anthropic",models:"by model",says:"The shortest cacheable prompt: 512 tokens on Claude Opus 5.5, Opus 5, Sonnet 5.5, Haiku 5.5 and Fable/Mythos 5.x; 1,024 on Sonnet 5, Opus 4.8 and Sonnet 4.x; 2,048 on Opus 4.7; 4,096 on Opus 4.5/4.6 and Haiku 4.5. Shorter prompts are not cached, without an error.",value:512,source:"anthropicCaching"},{id:"anthropic.lookback",provider:"anthropic",models:"all Claude models",says:"A breakpoint looks back at most 20 blocks for an entry earlier requests wrote; writes happen only at breakpoints.",value:20,source:"anthropicCaching"},{id:"anthropic.concurrent",provider:"anthropic",models:"all Claude models",says:"A cache entry becomes available only after the first response starts: for parallel requests to hit it, wait for the first response before sending the rest.",source:"anthropicCaching"},{id:"anthropic.usage",provider:"anthropic",models:"all Claude models",says:"`cache_read_input_tokens` are reads, `cache_creation_input_tokens` writes (split in `cache_creation.ephemeral_5m_input_tokens` / `ephemeral_1h_input_tokens`), `input_tokens` the rest after the last breakpoint.",source:"anthropicCaching"},{id:"anthropic.ends-reuse",provider:"anthropic",models:"all Claude models",says:"A change to the tools ends every level; web search, citations and speed end system and messages; `tool_choice`, images, thinking and effort settings end the messages level.",value:["tools","tool_choice","thinking","output_config.effort","speed"],source:"anthropicCaching"}];export function aiCacheFact(e){const a=AI_CACHE_FACTS.find(t=>t.id===e);return a?{...a,from:AI_GUIDANCE_SOURCES[a.source]}:void 0}o(aiCacheFact,"aiCacheFact"),n(aiCacheFact,"aiCacheFact"),i(aiCacheFact,"aiCacheFact");export const openaiNewCache=i(e=>!!e&&/^(?:openai\/)?gpt-(?:5\.(?:[6-9]|\d{2,})|[6-9]|\d{2,})/.test(e),"openaiNewCache");export function aiCacheMinTokens(e,a){if(e!=="anthropic")return 1024;const t=(a??"").replace(/^anthropic\//,"");return/^claude-(?:opus-4-[56]|haiku-4-5)/.test(t)?4096:/^claude-opus-4-7/.test(t)?2048:/^claude-(?:sonnet-5(?!-5)|opus-4-8|sonnet-4|opus-4(?:-1)?(?![-\d]))/.test(t)?1024:512}o(aiCacheMinTokens,"aiCacheMinTokens"),n(aiCacheMinTokens,"aiCacheMinTokens"),i(aiCacheMinTokens,"aiCacheMinTokens");export const aiDefaultTtl=i((e,a)=>e==="anthropic"?"5m":openaiNewCache(a)?"30m":"24h","aiDefaultTtl");
@@ -1 +1 @@
1
- "use strict";var Ct=Object.defineProperty;var F=(e,o)=>Ct(e,"name",{value:o,configurable:!0});var It=Object.defineProperty,k=F((e,o)=>It(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as Ut,aiGuidanceAge as Dt}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const b=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),ot=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),R=k(e=>`$${Number(e.toFixed(4))}`,"rate"),_=k(e=>Math.round(e*1e6)/1e6,"usd"),V=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Et=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,o,g=Date.now()){const h=new Map,l=new Map;for(const d of e){if(!d.cache)continue;const i=l.get(d.agent.key);i?i.push(d):l.set(d.agent.key,[d])}for(const d of l.values()){d.sort((i,s)=>i.at-s.at||i.id.localeCompare(s.id));for(const[i,s]of $t(d,o,g))h.set(i,s)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function gt(e,o){const g=e==="anthropic"?kt.anthropicCaching:kt.openaiCaching;return{source:g.url,readAt:g.readAt,...Dt(g.readAt,o).stale?{stale:!0}:{}}}F(gt,"Ut"),k(gt,"factsOf");function $t(e,o,g){const h=[],l=new Map,d=new Map;e.forEach((i,s)=>{const n=i.cache,$=i.at,x=i.durationMs!==void 0?i.at+i.durationMs:void 0,U=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:U,wrote:[]};h.push(a);const r=n.marks??[],w=r.filter(t=>t.bp),A=i.tokens?.input??0,m=i.tokens?.cached??0,f=i.tokens?.written??0,v=Et(i),c=i.model?o(i.model,A):void 0,J=gt(i.provider,g),K={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:J},Z=k(()=>{for(const t of r){const u=d.get(t.h);u?u.push(s):d.set(t.h,[s])}},"remember"),tt=k((t,u)=>{const p=l.get(t);p?p.push({i:s,how:u}):l.set(t,[{i:s,how:u}])},"hold"),Q=Ut(i.provider,i.model);if(!v){if(!i.failed)for(const t of w)tt(t.h,"unknown");Z(),a.verdict=it(n,A,Q,K)??{kind:"unknown",said:i.failed?"It failed \u2014 the provider counted nothing for it.":i.noUsage?`${i.noUsage.said} No verdict.`:"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:K},i.prewarm&&(a.verdict.prewarm=!0);return}const O=it(n,A,Q,K);if(O){const t=st(a,h,d,s);if(t&&t.tokens>=Q&&c){const u=c.cacheRead??c.input,p=t.tokens*(c.input-u)/1e6;O.costs.push({kind:"no-cache",tokens:t.tokens,usd:_(p),arithmetic:`${b(t.tokens)} \xD7 (${R(c.input)} \u2212 ${R(u)})/M`,estimate:!0}),O.lostUsd=_(p),O.said+=` It shares \u2248 ${b(t.tokens)} tokens with ${t.id} (${V($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${ot(p)} less.`}i.prewarm&&(O.prewarm=!0),a.verdict=O,Z();return}const N=Math.max(256,A*.03),xt=k((t,u)=>u.reduce((p,B)=>!p||Math.abs(B.t-t)<Math.abs(p.t-t)?B:p,void 0),"nearest");let S=-1;if(m>0){const t=xt(m,w.length?w:r);t&&Math.abs(t.t-m)<=Math.max(N,m*.15)&&(a.readBp={h:t.h,t:t.t,s:t.s},S=w.indexOf(t))}w.forEach((t,u)=>(u<=S||S<0&&t.t<=m+N)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+N),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(N,f*.15)):[];if(f>0&&!D.length){const t=at[0]??w[w.length-1];D=t?[t]:[]}const nt=D.map((t,u)=>Math.max(1,t.t-(u?D[u-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=nt.reduce((t,u)=>t+u,0);D.forEach((t,u)=>{const p=D.length===1?f:Math.round(nt[u]/Bt*f),B=n.breakpoints.find(I=>Math.abs(I.tokens-t.t)<=1)?.ttl??n.ttl,L=et[B],T=(l.get(t.h)??[]).filter(I=>I.i<s),W=T.filter(I=>$-h[I.i].start<=L);if(W.length){const I=k(M=>h[M.i].end!==void 0&&h[M.i].end<=$,"done"),q=k(M=>M[M.length-1],"last"),ft=W.filter(M=>M.how==="wrote"),pt=W.filter(M=>M.how==="unknown"),wt=q(ft.filter(I))??q(pt.filter(I)),mt=q(ft.filter(M=>!I(M)))??q(pt.filter(M=>!I(M))),bt=wt??mt??q(W),At=!wt&&!!mt,yt=W.filter(M=>M.how==="read").length;a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"duplicate",against:bt,race:At,readFirst:yt})}else T.length?a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"cold",against:T[T.length-1],idleMs:$-h[T[T.length-1].i].start}):a.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:B,status:"first"});tt(t.h,"wrote")});const y=st(a,h,d,s);Z();const z=c?c.cacheRead??c.input:void 0,dt=c?Y(c,n.writes,n.ttl):void 0,H=[];let X,ct;if(y){const t=w.filter(B=>B.t<=y.tokens+1&&y.hashes.has(B.h)).reduce((B,L)=>Math.max(B,L.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>N){X={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ct=h[y.i];const B=m+f>=y.tokens-N,L=c?B?dt-z:c.input-z:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...L!==void 0?{usd:_(p*L/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(z)})/M`}:{}})}}for(const t of a.wrote){if(t.status==="first")continue;const u=c?Y(c,n.writes,t.ttl):void 0;H.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:_(t.tokens*(u-z)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(z)})/M`}:{}})}const C=[];a.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),X&&C.push("broken-prefix"),a.wrote.some(t=>t.status==="cold")&&C.push("cold"),a.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.push("no-cache");const j=a.wrote.find(t=>t.status==="duplicate"),P=a.wrote.find(t=>t.status==="cold"),ht=j?.against??P?.against,E=ht?h[ht.i]:ct,ut=H.some(t=>t.usd!==void 0)?_(H.reduce((t,u)=>t+(u.usd??0),0)):void 0,lt=c&&m>0?_(m*(c.input-z)/1e6):void 0,Mt=C[0];a.verdict={kind:Mt,...C.length>1?{also:C.slice(1)}:{},said:"",costs:H,...ut!==void 0?{lostUsd:ut}:{},...lt!==void 0?{savedUsd:lt}:{},...j||P||a.wrote[0]||a.readBp?{prefix:(j??P??a.wrote[0])?.h??a.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...j?{race:!!j.race,...j.readFirst?{readBefore:j.readFirst}:{}}:{},...X?{brokeAt:X}:{},...P?.idleMs!==void 0?{idleMs:P.idleMs}:{},...i.prewarm?{prewarm:!0}:{},basis:K}});for(const i of h){const s=i.verdict;if(!i.wrote.length){s.said=rt(i,s);continue}const n=new Set,$=new Set;let x=!1;const U=[];for(const a of i.wrote){const r=et[a.ttl],w=(l.get(a.h)??[]).filter(f=>h[f.i].start>i.start&&h[f.i].start-i.start<=r),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)n.add(f.i);for(const f of m)$.add(f.i);i.start+r>g?x=!0:!A.length&&!m.length&&U.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),U.length){const a=i.row,r=a.model?o(a.model,a.tokens?.input??0):void 0;let w=s.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of U){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const J=r?Y(r,a.cache.writes,v.ttl):void 0;s.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...r?{usd:_(c*(J-r.input)/1e6),arithmetic:`${b(c)} \xD7 (${R(J)} \u2212 ${R(r.input)})/M`}:{}})}r&&(s.lostUsd=_(s.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[s.kind,...s.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),s.kind=A[0];const f=A.slice(1);f.length?s.also=f:delete s.also}s.said=rt(i,s)}return new Map(h.map(i=>[i.row.id,i.verdict]))}F($t,"It"),k($t,"judgeAgent");function Y(e,o,g){const h=Object.entries(o??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((i,[,s])=>i+s,0);return h.reduce((i,[s,n])=>i+(e.writes[s]??e.input)*n,0)/d}const l=h[0]?.[0]??g;return e.writes[l]??e.input}F(Y,"et"),k(Y,"writeRate");function it(e,o,g,h){const l=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return l("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return l("No `cache_control`: Anthropic cached nothing of it.");if(o>0&&o<g)return l(`${b(o)} input tokens \u2014 under the ${b(g)}-token minimum: nothing is cached.`)}F(it,"pt"),k(it,"structural");function st(e,o,g,h){const l=e.row.cache?.marks??[];let d;for(let s=0;s<l.length;s++){const n=g.get(l[s].h);if(n)for(let $=n.length-1;$>=0;$--){const x=n[$];if(!(x>=h)){if(e.start-o[x].start>e.ttlMs)break;d={i:x,at:s};break}}}if(!d)return;const i=o[d.i];return{i:d.i,id:i.row.id,tokens:l[d.at].t,...l[d.at+1]?{next:l[d.at+1].s}:{},hashes:new Set((i.row.cache?.marks??[]).map(s=>s.h))}}F(st,"wt"),k(st,"sharedWith");const G=k(e=>e.split(" \u203A ")[0],"block");function rt(e,o){if(o.said)return o.said;const g=e.row,h=g.cache,l=g.tokens?.input??0,d=o.read??0,i=o.written??0,s=h.ttl,n=[],$=o.prewarm?"A prewarm (it answers nothing): it ":"It ";n.push(`${$}read ${b(d)} of its ${b(l)} input tokens from the cache${i?` and wrote ${b(i)}`:""} (${h.mode} mode, ${s}).`);const x=e.wrote.find(r=>r.status==="duplicate");if(x&&o.against){const r=o.against,w=o.readBefore?` ${b(o.readBefore)} call${o.readBefore===1?"":"s"} sent before this one read it.`:"";n.push(o.race?`Duplicate write \u2014 a race: ${r.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) and was still in flight when this one was sent, ${V(r.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${r.id} had read the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${r.id}${r.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${G(x.s)}\xBB) ${V(r.gapMs)} before${r.ended!==void 0&&r.ended<=e.start?` and had ended ${V(e.start-r.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}o.brokeAt&&n.push(`Broken prefix: it shares \u2248 ${b(o.brokeAt.tokens)} tokens with ${o.brokeAt.id}, then they part in \xAB${o.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${b(d)}.`);const U=e.wrote.find(r=>r.status==="cold");U&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(U.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${U.ttl} lifetime.`);const a=e.wrote.filter(r=>r.status==="first");return a.length&&n.push(`First writer of the prefix to the end of \xAB${a.map(r=>G(r.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(o.kind==="write-nothing-read"||o.also?.includes("write-nothing-read")?n.push("No later call of its agent read what it wrote inside its lifetime."):o.readBy?n.push(`${b(o.readBy)} later call${o.readBy===1?"":"s"} read what it wrote.`):o.maybeReadBy?n.push(`${b(o.maybeReadBy)} later call${o.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):o.open&&n.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!o.brokeAt&&n.push(`Read${e.readBp?` to the end of \xAB${G(e.readBp.s)}\xBB`:""}.`),o.lostUsd!==void 0&&o.lostUsd>0&&n.push(`\u2248 ${ot(o.lostUsd)} lost: ${o.costs.filter(r=>r.arithmetic).map(r=>`${r.arithmetic}${r.estimate?" (estimate)":""}`).join(" + ")}.`),o.savedUsd&&n.push(`Its reads saved \u2248 ${ot(o.savedUsd)} against plain input.`),n.join(" ")}F(rt,"kt"),k(rt,"said");
1
+ "use strict";var Ct=Object.defineProperty;var F=(e,s)=>Ct(e,"name",{value:s,configurable:!0});var It=Object.defineProperty,R=F((e,s)=>It(e,"name",{value:s,configurable:!0}),"F"),Dt=Object.defineProperty,k=R((e,s)=>Dt(e,"name",{value:s,configurable:!0}),"w");import{AI_CACHE_TTL_MS as it,AI_GUIDANCE_SOURCES as xt,aiCacheMinTokens as Et,aiGuidanceAge as Ft}from"./ai-cache-facts.js";export const AI_CACHE_VERDICT_LABEL={read:"read","first-writer":"first writer","duplicate-write":"duplicate write","broken-prefix":"broken prefix",cold:"cold","write-nothing-read":"write nothing read","no-cache":"no cache",unknown:"unknown"};const M=k(e=>Math.round(e).toLocaleString("en-US"),"fmt"),rt=k(e=>`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`,"money"),_=k(e=>`$${Number(e.toFixed(4))}`,"rate"),S=k(e=>Math.round(e*1e6)/1e6,"usd"),G=k(e=>e<1e3?`${Math.round(e)} ms`:e<12e4?`${(e/1e3).toFixed(1)} s`:e<72e5?`${Math.round(e/6e4)} min`:`${(e/36e5).toFixed(1)} h`,"dur"),Rt=k(e=>e.tokens?.input!==void 0&&e.cache!==void 0&&!e.failed,"counted");export function aiCacheVerdicts(e,s,g=Date.now()){const h=new Map,u=new Map;for(const d of e){if(!d.cache)continue;const n=u.get(d.agent.key);n?n.push(d):u.set(d.agent.key,[d])}for(const d of u.values()){d.sort((n,a)=>n.at-a.at||n.id.localeCompare(a.id));for(const[n,a]of dt(d,s,g))h.set(n,a)}return h}F(aiCacheVerdicts,"aiCacheVerdicts"),R(aiCacheVerdicts,"aiCacheVerdicts"),k(aiCacheVerdicts,"aiCacheVerdicts");function ot(e,s){const g=e==="anthropic"?xt.anthropicCaching:xt.openaiCaching;return{source:g.url,readAt:g.readAt,...Ft(g.readAt,s).stale?{stale:!0}:{}}}F(ot,"gt"),R(ot,"Ut"),k(ot,"factsOf");function dt(e,s,g){const h=[],u=new Map,d=new Map;e.forEach((n,a)=>{const o=n.cache,$=n.at,x=n.durationMs!==void 0?n.at+n.durationMs:void 0,I=it[o.ttl],r={row:n,start:$,...x!==void 0?{end:x}:{},ttlMs:I,wrote:[]};h.push(r);const i=o.marks??[],w=i.filter(t=>t.bp),A=n.tokens?.input??0,m=n.tokens?.cached??0,f=n.tokens?.written??0,v=Rt(n),c=n.model?s(n.model,A):void 0,Q=ot(n.provider,g),X={...c?{price:{...c.source?{source:c.source}:{},...c.readAt?{readAt:c.readAt}:{},...c.stale?{stale:!0}:{}}}:{},facts:Q},nt=k(()=>{for(const t of i){const l=d.get(t.h);l?l.push(a):d.set(t.h,[a])}},"remember"),at=k((t,l)=>{const p=u.get(t);p?p.push({i:a,how:l}):u.set(t,[{i:a,how:l}])},"hold"),Y=Et(n.provider,n.model);if(!v){if(!n.failed)for(const t of w)at(t.h,"unknown");nt(),r.verdict=tt(o,A,Y,X)??{kind:"unknown",said:n.failed?"It failed \u2014 the provider counted nothing for it.":n.noUsage?`${n.noUsage.said} No verdict.`:"Its token count was not kept (the answer was cut by the capture): no verdict.",costs:[],basis:X},n.prewarm&&(r.verdict.prewarm=!0);return}const L=tt(o,A,Y,X);if(L){const t=et(r,h,d,a);if(t&&t.tokens>=Y&&c){const l=c.cacheRead??c.input,p=t.tokens*(c.input-l)/1e6;L.costs.push({kind:"no-cache",tokens:t.tokens,usd:S(p),arithmetic:`${M(t.tokens)} \xD7 (${_(c.input)} \u2212 ${_(l)})/M`,estimate:!0}),L.lostUsd=S(p),L.said+=` It shares \u2248 ${M(t.tokens)} tokens with ${t.id} (${G($-h[t.i].start)} before): read from a cache, they would cost \u2248 ${rt(p)} less.`}n.prewarm&&(L.prewarm=!0),r.verdict=L,nt();return}const N=Math.max(256,A*.03),vt=k((t,l)=>l.reduce((p,b)=>!p||Math.abs(b.t-t)<Math.abs(p.t-t)?b:p,void 0),"nearest");let j=-1;if(m>0){const t=vt(m,w.length?w:i);t&&Math.abs(t.t-m)<=Math.max(N,m*.15)&&(r.readBp={h:t.h,t:t.t,s:t.s},j=w.indexOf(t))}w.forEach((t,l)=>(l<=j||j<0&&t.t<=m+N)&&at(t.h,"read"));const ct=w.filter((t,l)=>j>=0?l>j:t.t>m+N),bt=j>=0?w[j].t:m;let D=f>0?ct.filter(t=>t.t<=bt+f+Math.max(N,f*.15)):[];if(f>0&&!D.length){const t=ct[0]??w[w.length-1];D=t?[t]:[]}const ht=D.map((t,l)=>Math.max(1,t.t-(l?D[l-1].t:Math.max(m,w.filter(p=>p.t<t.t).pop()?.t??0)))),Bt=ht.reduce((t,l)=>t+l,0);D.forEach((t,l)=>{const p=D.length===1?f:Math.round(ht[l]/Bt*f),b=o.breakpoints.find(C=>Math.abs(C.tokens-t.t)<=1)?.ttl??o.ttl,T=it[b],V=(u.get(t.h)??[]).filter(C=>C.i<a),W=V.filter(C=>$-h[C.i].start<=T);if(W.length){const C=k(B=>h[B.i].end!==void 0&&h[B.i].end<=$,"done"),q=k(B=>B[B.length-1],"last"),mt=W.filter(B=>B.how==="wrote"),kt=W.filter(B=>B.how==="unknown"),gt=q(mt.filter(C))??q(kt.filter(C)),$t=q(mt.filter(B=>!C(B)))??q(kt.filter(B=>!C(B))),At=gt??$t??q(W),yt=!gt&&!!$t,Ut=W.filter(B=>B.how==="read").length;r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"duplicate",against:At,race:yt,readFirst:Ut})}else V.length?r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"cold",against:V[V.length-1],idleMs:$-h[V[V.length-1].i].start}):r.wrote.push({h:t.h,s:t.s,tokens:p,estimate:D.length>1,ttl:b,status:"first"});at(t.h,"wrote")});const y=et(r,h,d,a);nt();const z=c?c.cacheRead??c.input:void 0,lt=c?K(c,o.writes,o.ttl):void 0,P=[];let Z,ut;if(y){const t=w.filter(b=>b.t<=y.tokens+1&&y.hashes.has(b.h)).reduce((b,T)=>Math.max(b,T.t),0),l=Math.max(m,t),p=y.tokens-l;if(y.tokens>=Y&&p>N){Z={region:y.next??"(the end of the prompt)",tokens:y.tokens,id:h[y.i].row.id},ut=h[y.i];const b=m+f>=y.tokens-N,T=c?b?lt-z:c.input-z:void 0;P.push({kind:"broken-prefix",tokens:p,estimate:!0,...T!==void 0?{usd:S(p*T/1e6),arithmetic:`${M(p)} \xD7 (${_(b?lt:c.input)} \u2212 ${_(z)})/M`}:{}})}}for(const t of r.wrote){if(t.status==="first")continue;const l=c?K(c,o.writes,t.ttl):void 0;P.push({kind:t.status==="duplicate"?"duplicate-write":"cold",tokens:t.tokens,estimate:t.estimate,...c?{usd:S(t.tokens*(l-z)/1e6),arithmetic:`${M(t.tokens)} \xD7 (${_(l)} \u2212 ${_(z)})/M`}:{}})}const U=[];r.wrote.some(t=>t.status==="duplicate")&&U.push("duplicate-write"),Z&&U.push("broken-prefix"),r.wrote.some(t=>t.status==="cold")&&U.push("cold"),r.wrote.some(t=>t.status==="first")&&U.push("first-writer"),m>0&&U.push("read"),U.length||U.push("no-cache");const O=r.wrote.find(t=>t.status==="duplicate"),J=r.wrote.find(t=>t.status==="cold"),ft=O?.against??J?.against,E=ft?h[ft.i]:ut,pt=P.some(t=>t.usd!==void 0)?S(P.reduce((t,l)=>t+(l.usd??0),0)):void 0,wt=c&&m>0?S(m*(c.input-z)/1e6):void 0,Mt=U[0];r.verdict={kind:Mt,...U.length>1?{also:U.slice(1)}:{},said:"",costs:P,...pt!==void 0?{lostUsd:pt}:{},...wt!==void 0?{savedUsd:wt}:{},...O||J||r.wrote[0]||r.readBp?{prefix:(O??J??r.wrote[0])?.h??r.readBp.h}:{},read:m,written:f,...E?{against:{id:E.row.id,at:E.start,...E.end!==void 0?{ended:E.end}:{},inFlight:E.end===void 0||E.end>$,gapMs:$-E.start,...E.row.prewarm?{prewarm:!0}:{}}}:{},...O?{race:!!O.race,...O.readFirst?{readBefore:O.readFirst}:{}}:{},...Z?{brokeAt:Z}:{},...J?.idleMs!==void 0?{idleMs:J.idleMs}:{},...n.prewarm?{prewarm:!0}:{},basis:X}});for(const n of h){const a=n.verdict;if(!n.wrote.length){a.said=st(n,a);continue}const o=new Set,$=new Set;let x=!1;const I=[];for(const r of n.wrote){const i=it[r.ttl],w=(u.get(r.h)??[]).filter(f=>h[f.i].start>n.start&&h[f.i].start-n.start<=i),A=w.filter(f=>f.how==="read"),m=w.filter(f=>f.how==="unknown");for(const f of A)o.add(f.i);for(const f of m)$.add(f.i);n.start+i>g?x=!0:!A.length&&!m.length&&I.push(r)}for(const r of o)$.delete(r);if(o.size&&(a.readBy=o.size),$.size&&(a.maybeReadBy=$.size),x&&(a.open=!0),I.length){const r=n.row,i=r.model?s(r.model,r.tokens?.input??0):void 0;let w=a.costs.find(v=>v.kind==="broken-prefix")?.tokens??0;for(const v of I){if(v.status!=="first")continue;const c=Math.max(0,v.tokens-w);if(w=0,!c)continue;const Q=i?K(i,r.cache.writes,v.ttl):void 0;a.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...i?{usd:S(c*(Q-i.input)/1e6),arithmetic:`${M(c)} \xD7 (${_(Q)} \u2212 ${_(i.input)})/M`}:{}})}i&&(a.lostUsd=S(a.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[a.kind,...a.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),a.kind=A[0];const f=A.slice(1);f.length?a.also=f:delete a.also}a.said=st(n,a)}return new Map(h.map(n=>[n.row.id,n.verdict]))}F(dt,"$t"),R(dt,"It"),k(dt,"judgeAgent");function K(e,s,g){const h=Object.entries(s??{}).filter(d=>typeof d[1]=="number"&&d[1]>0);if(h.length>1){const d=h.reduce((n,[,a])=>n+a,0);return h.reduce((n,[a,o])=>n+(e.writes[a]??e.input)*o,0)/d}const u=h[0]?.[0]??g;return e.writes[u]??e.input}F(K,"Y"),R(K,"et"),k(K,"writeRate");function tt(e,s,g,h){const u=k(d=>({kind:"no-cache",said:d,costs:[],basis:h}),"no");if(e.mode==="explicit"&&!e.breakpoints.length)return u("Explicit mode with no breakpoint: it read and wrote nothing.");if(e.mode==="none")return u("No `cache_control`: Anthropic cached nothing of it.");if(s>0&&s<g)return u(`${M(s)} input tokens \u2014 under the ${M(g)}-token minimum: nothing is cached.`)}F(tt,"it"),R(tt,"pt"),k(tt,"structural");function et(e,s,g,h){const u=e.row.cache?.marks??[];let d;for(let a=0;a<u.length;a++){const o=g.get(u[a].h);if(o)for(let $=o.length-1;$>=0;$--){const x=o[$];if(!(x>=h)){if(e.start-s[x].start>e.ttlMs)break;d={i:x,at:a};break}}}if(!d)return;const n=s[d.i];return{i:d.i,id:n.row.id,tokens:u[d.at].t,...u[d.at+1]?{next:u[d.at+1].s}:{},hashes:new Set((n.row.cache?.marks??[]).map(a=>a.h))}}F(et,"st"),R(et,"wt"),k(et,"sharedWith");const H=k(e=>e.split(" \u203A ")[0],"block");function st(e,s){if(s.said)return s.said;const g=e.row,h=g.cache,u=g.tokens?.input??0,d=s.read??0,n=s.written??0,a=h.ttl,o=[],$=s.prewarm?"A prewarm (it answers nothing): it ":"It ";o.push(`${$}read ${M(d)} of its ${M(u)} input tokens from the cache${n?` and wrote ${M(n)}`:""} (${h.mode} mode, ${a}).`);const x=e.wrote.find(i=>i.status==="duplicate");if(x&&s.against){const i=s.against,w=s.readBefore?` ${M(s.readBefore)} call${s.readBefore===1?"":"s"} sent before this one read it.`:"";o.push(s.race?`Duplicate write \u2014 a race: ${i.id}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${H(x.s)}\xBB) and was still in flight when this one was sent, ${G(i.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${i.id} had read the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(i.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${i.id}${i.prewarm?" (a prewarm)":""}${x.against?.how==="unknown"?" (its count was not kept: it may have)":""} wrote the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(i.gapMs)} before${i.ended!==void 0&&i.ended<=e.start?` and had ended ${G(e.start-i.ended)} before this one was sent \u2014 not a race: the write had finished and this call did not read it`:""}.${w}`)}s.brokeAt&&o.push(`Broken prefix: it shares \u2248 ${M(s.brokeAt.tokens)} tokens with ${s.brokeAt.id}, then they part in \xAB${s.brokeAt.region}\xBB \u2014 no breakpoint ends where they part, so it read only ${M(d)}.`);const I=e.wrote.find(i=>i.status==="cold");I&&s.idleMs!==void 0&&o.push(`Cold: the same prefix (to the end of \xAB${H(I.s)}\xBB) was last used ${G(s.idleMs)} before \u2014 past its ${I.ttl} lifetime.`);const r=e.wrote.filter(i=>i.status==="first");return r.length&&o.push(`First writer of the prefix to the end of \xAB${r.map(i=>H(i.s)).join("\xBB, \xAB")}\xBB.`),e.wrote.length&&(s.kind==="write-nothing-read"||s.also?.includes("write-nothing-read")?o.push("No later call of its agent read what it wrote inside its lifetime."):s.readBy?o.push(`${M(s.readBy)} later call${s.readBy===1?"":"s"} read what it wrote.`):s.maybeReadBy?o.push(`${M(s.maybeReadBy)} later call${s.maybeReadBy===1?"":"s"} may have read it (their counts were not kept).`):s.open&&o.push("Its lifetime has not run out: a later call may still read it.")),!e.wrote.length&&d>0&&!s.brokeAt&&o.push(`Read${e.readBp?` to the end of \xAB${H(e.readBp.s)}\xBB`:""}.`),s.lostUsd!==void 0&&s.lostUsd>0&&o.push(`\u2248 ${rt(s.lostUsd)} lost: ${s.costs.filter(i=>i.arithmetic).map(i=>`${i.arithmetic}${i.estimate?" (estimate)":""}`).join(" + ")}.`),s.savedUsd&&o.push(`Its reads saved \u2248 ${rt(s.savedUsd)} against plain input.`),o.join(" ")}F(st,"rt"),R(st,"kt"),k(st,"said");
package/lib/ai-cache.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var H=Object.defineProperty;var b=(t,o)=>H(t,"name",{value:o,configurable:!0});var Q=Object.defineProperty,u=b((t,o)=>Q(t,"name",{value:o,configurable:!0}),"u");import{aiDefaultTtl as D,openaiNewCache as U}from"./ai-cache-facts.js";export const MAX_MARKS=48;const L=400,V=72,S=u(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),g=u(t=>typeof t=="string"?t:void 0,"str"),v=u(t=>Array.isArray(t)?t:[],"arr"),x=u(t=>S(t)?t:{},"obj"),W=["5m","1h","30m","12h","24h","in_memory"],O=u(t=>typeof t=="string"&&W.includes(t)?t:void 0,"ttlOf");function A(t){if(typeof t=="string")return t;const o=x(t),e=g(o.text)??g(o.refusal);if(e!==void 0)return e;const{prompt_cache_breakpoint:h,cache_control:l,...p}=o;return JSON.stringify(p)}b(A,"C"),u(A,"partText");const R=u((t,o)=>{const e={};for(const h of o){let l=t;for(const p of h.split("."))l=x(l)[p];l!==void 0&&(e[h]=l)}return e},"pick");function P(t){const o=x(t).prompt_cache_breakpoint;if(o==null||o===!1)return;const e=O(x(o).ttl);return e?{ttl:e}:{}}b(P,"F"),u(P,"openaiBreakpoint");function j(t){const o=x(t).cache_control;if(!S(o))return;const e=O(o.ttl);return e?{ttl:e}:{}}b(j,"L"),u(j,"anthropicBreakpoint");function T(t){const o=g(t.model),e=x(t.prompt_cache_options),h=U(o),l=g(e.mode)==="explicit"||g(e.mode)==="implicit",p=g(e.mode)==="explicit"?"explicit":"implicit",i=O(h?e.ttl:t.prompt_cache_retention),s=[],r=g(t.instructions);r&&s.push({label:"instructions",role:"developer",text:r}),v(t.tools).length&&s.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const n=x(x(t.text).format);n.schema!==void 0&&s.push({label:`answer schema${g(n.name)?` \xB7 ${g(n.name)}`:""}`,text:JSON.stringify(n.schema),weight:.7});let m=-1;const a=t.input;if(typeof a=="string")s.push({label:"user",role:"user",text:a}),m=s.length-1;else{const y=v(a).map(x);let _=!0;y.forEach((c,k)=>{const f=g(c.type)??(c.role?"message":""),w=g(c.role)??(f==="function_call_output"?"tool":"item"),M=f==="message"?c.content:f==="function_call_output"?c.output:void 0,J=typeof M=="string"?[M]:Array.isArray(M)?M:void 0,B=f==="message"?w:f||"item";if(J)J.forEach((E,z)=>{const C=P(E);s.push({label:J.length>1?`${B} \xB7 block ${z+1} of ${J.length}`:B,role:w,text:A(E),...C?{bp:C}:{}})});else{const{id:E,status:z,...C}=c;s.push({label:B,role:w,text:JSON.stringify(C)})}const N=y[k+1],q=N?g(N.type)??(N.role?"message":""):"";(f==="message"&&w==="user"||f==="function_call_output"&&q!=="function_call_output"||_&&f==="message"&&w==="developer"&&!(q==="message"&&g(N.role)==="developer"))&&(m=s.length-1),f==="message"&&w==="developer"||(_=!1)})}p==="implicit"&&m>=0&&(s[m].bp={...s[m].bp??{},implicit:!0});const d={model:o,...R(t,["tools","parallel_tool_calls","text.format","reasoning.effort","text.verbosity","context_management","prompt_cache_key","previous_response_id","conversation"])};return{provider:"openai",api:"responses",...o?{model:o}:{},settings:JSON.stringify(d),blocks:s,mode:p,modeSaid:l,ttl:i??D("openai",o),ttlSaid:!!i,prewarm:e.prewarm===!0,key:typeof t.prompt_cache_key=="string"}}b(T,"G"),u(T,"responsesRequest");function I(t){const o=g(t.model),e=[];v(t.tools).length&&e.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const h=x(t.response_format);h.json_schema!==void 0&&e.push({label:"answer schema",text:JSON.stringify(h.json_schema),weight:.7});let l=-1;const p=v(t.messages).map(x);p.forEach((r,n)=>{const m=g(r.role)??"user",a=r.content,d=typeof a=="string"?[a]:Array.isArray(a)?a:[];d.length||e.push({label:m,role:m,text:JSON.stringify({...r,content:void 0})}),d.forEach((_,c)=>e.push({label:d.length>1?`${m} \xB7 block ${c+1} of ${d.length}`:m,role:m,text:A(_)})),r.tool_calls!==void 0&&e.push({label:`${m} \xB7 tool calls`,role:m,text:JSON.stringify(r.tool_calls)});const y=g(p[n+1]?.role);(m==="user"||m==="tool"&&y!=="tool")&&(l=e.length-1)}),l>=0&&(e[l].bp={implicit:!0});const i=O(t.prompt_cache_retention),s={model:o,...R(t,["tools","parallel_tool_calls","response_format","reasoning_effort","verbosity","prompt_cache_key"])};return{provider:"openai",api:"chat",...o?{model:o}:{},settings:JSON.stringify(s),blocks:e,mode:"implicit",modeSaid:!1,ttl:i??D("openai",o),ttlSaid:!!i,prewarm:!1,key:typeof t.prompt_cache_key=="string"}}b(I,"Q"),u(I,"chatRequest");function K(t){const o=g(t.model),e=[];for(const n of v(t.tools).map(x)){const m=j(n),{cache_control:a,...d}=n;e.push({label:`tools \xB7 ${g(n.name)??g(n.type)??"tool"}`,text:JSON.stringify(d),weight:.7,...m?{bp:m}:{}})}const h=t.system;if(typeof h=="string"&&h)e.push({label:"system",role:"system",text:h});else{const n=v(h);n.forEach((m,a)=>{const d=j(m);e.push({label:n.length>1?`system \xB7 block ${a+1} of ${n.length}`:"system",role:"system",text:A(m),...d?{bp:d}:{}})})}for(const n of v(t.messages).map(x)){const m=g(n.role)??"user",a=n.content,d=typeof a=="string"?[a]:v(a);d.forEach((y,_)=>{const c=j(y);e.push({label:d.length>1?`${m} \xB7 block ${_+1} of ${d.length}`:m,role:m,text:A(y),...c?{bp:c}:{}})})}const l=t.cache_control,p=e.some(n=>n.bp);if(S(l)&&e.length){const n=e[e.length-1];n.bp={...n.bp??(O(l.ttl)?{ttl:O(l.ttl)}:{}),implicit:!0}}const i=p?"explicit":S(l)?"automatic":"none",s=S(l)?O(l.ttl):void 0,r={model:o,...R(t,["tool_choice","thinking","output_config.effort","speed"])};return{provider:"anthropic",api:"messages",...o?{model:o}:{},settings:JSON.stringify(r),blocks:e,mode:i,modeSaid:p||S(l),ttl:s??"5m",ttlSaid:!!s,prewarm:!1,key:!1}}b(K,"U"),u(K,"messagesRequest");export function aiCacheRequestOf(t,o){if(S(o)){if(t==="responses")return T(o);if(t==="chat")return I(o);if(t==="messages")return K(o)}}b(aiCacheRequestOf,"aiCacheRequestOf"),u(aiCacheRequestOf,"aiCacheRequestOf");class Y{static{b(this,"V")}static{u(this,"Prefix")}constructor(){this.h1=3735928559,this.h2=1103547991,this.tokens=0,this.chars=0,this.word=0,this.digits=0,this.space=0}feed(o,e=!0,h=1){let l=this.h1,p=this.h2,i=0,s=this.word,r=this.digits,n=this.space;for(let m=0;m<o.length;m++){const a=o.charCodeAt(m);l=Math.imul(l^a,2654435761),p=Math.imul(p^a,1597334677),e&&(a>=65&&a<=90||a>=97&&a<=122?((s===0||s>=8&&(s-8)%4===3)&&(i+=1),s++,r=0,n=0):a>=48&&a<=57?(r%3===0&&(i+=1),r++,s=0,n=0):a===32||a===9||a===10||a===13?((a===10||n===1)&&(i+=n<2?1:0),n=a===10?2:n+1,s=0,r=0):(s=0,r=0,n=0,i+=a>=11904?.9:a>=192?.66:.75))}this.h1=l,this.h2=p,this.word=s,this.digits=r,this.space=n,e&&(this.tokens+=i*h,this.chars+=o.length)}digest(){let o=this.h1,e=this.h2;return o=Math.imul(o^o>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(o^o>>>13,3266489909),(4294967296*(2097151&e)+(o>>>0)).toString(36)}}export function aiCacheSections(t){const o=[];let e=0;const h=t.length;for(;e<h;){const l=t.indexOf(`
2
- `,e),p=l<0?h:l;let i=e;for(;i<p&&(t.charCodeAt(i)===32||t.charCodeAt(i)===9);)i++;const s=t[i];if(s==="-"||s==="#"||s==="<"){const r=t.slice(i,Math.min(p,i+240)),n=s==="-"?/^-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/.exec(r):s==="#"?/^#{1,3}[ \t]+(.+?)[ \t#]*$/.exec(r):/^<([a-z][a-z0-9_-]{0,40})(?:[\s>])/.exec(r);n&&n[1].trim()&&o.push({at:e,title:n[1].trim().slice(0,V)})}e=p+1}return o}b(aiCacheSections,"aiCacheSections"),u(aiCacheSections,"aiCacheSections");function X(t,o){const e=t.text.length,h=e>=2*L?aiCacheSections(t.text):[],l=[{block:o,from:0,to:e,title:t.label,end:!0}];if(!h.length)return l;const p=h[0].at===0?h[0].title:void 0;let i={at:0,title:p??"(opening)",last:void 0,opening:!p};const s=[],r=u(n=>`${t.label} \u203A ${n.last?`${F(n.title)} \u2026 ${F(n.last)}`:n.title}`,"titled");for(const n of h)if(n.at!==0){if(n.at-i.at<L){i.opening?i={at:i.at,title:n.title,last:void 0,opening:!1}:i.last=n.title;continue}s.push({block:o,from:i.at,to:n.at,title:r(i),end:!1}),i={at:n.at,title:n.title,last:void 0,opening:!1}}return s.length?(s.push({block:o,from:i.at,to:e,title:r(i),end:!0}),s):l}b(X,"W"),u(X,"regionsOf");const F=u(t=>t.length>36?`${t.slice(0,35)}\u2026`:t,"clip"),Z=4;export function aiCacheOf(t,o,e,h={}){const l=aiCacheRequestOf(t,o);if(!l)return;const p=new Y;p.feed(l.settings,!1);const i=[];l.blocks.forEach((c,k)=>{p.feed(`\0${c.role??""}`,!1),p.tokens+=Z;for(const f of X(c,k))p.feed(c.text.slice(f.from,f.to),!0,c.weight??1),(f.end||i.length<MAX_MARKS-8)&&i.push({h:p.digest(),chars:p.chars,tokens:p.tokens,s:f.title,...f.end&&c.bp?{bp:c.bp}:{},blockEnd:f.end})});const s=p.tokens,r=e?.input!==void 0&&e.input>0,n=r&&s>0?e.input/s:1,m=u(c=>Math.round(c*n),"round");let a=i.map(c=>({h:c.h,t:m(c.tokens),s:c.s,...c.bp?{bp:1}:{}}));if(a.length>MAX_MARKS){const c=new Set;a.forEach((k,f)=>k.bp&&c.add(f));for(let k=a.length-1;k>=0&&c.size<MAX_MARKS;k--)c.add(k);a=a.filter((k,f)=>c.has(f))}const d=i.filter(c=>c.bp).map(c=>({at:c.s.split(" \u203A ")[0],...c.bp.ttl?{ttl:c.bp.ttl}:{},...c.bp.implicit?{implicit:!0}:{},chars:c.chars,tokens:m(c.tokens)})),y=e?.cached,_=e?.written;return{provider:l.provider,mode:l.mode,modeSaid:l.modeSaid,ttl:l.ttl,ttlSaid:l.ttlSaid,...l.prewarm||h.prewarm?{prewarm:!0}:{},...l.key?{key:!0}:{},breakpoints:d,...r?{read:y??0,written:_??0,plain:Math.max(0,e.input-(y??0)-(_??0))}:{},...e?.writes&&Object.keys(e.writes).length?{writes:{...e.writes}}:{},marks:a,estimated:!r}}b(aiCacheOf,"aiCacheOf"),u(aiCacheOf,"aiCacheOf");const G=200,$=u((t,o)=>{const e=t.lastIndexOf(`
1
+ "use strict";var V=Object.defineProperty;var b=(t,o)=>V(t,"name",{value:o,configurable:!0});var W=Object.defineProperty,x=b((t,o)=>W(t,"name",{value:o,configurable:!0}),"b"),X=Object.defineProperty,m=x((t,o)=>X(t,"name",{value:o,configurable:!0}),"u");import{aiDefaultTtl as I,openaiNewCache as H}from"./ai-cache-facts.js";export const MAX_MARKS=48;const K=400,Y=72,S=m(t=>!!t&&typeof t=="object"&&!Array.isArray(t),"isObj"),g=m(t=>typeof t=="string"?t:void 0,"str"),O=m(t=>Array.isArray(t)?t:[],"arr"),y=m(t=>S(t)?t:{},"obj"),Z=["5m","1h","30m","12h","24h","in_memory"],w=m(t=>typeof t=="string"&&Z.includes(t)?t:void 0,"ttlOf");function A(t){if(typeof t=="string")return t;const o=y(t),e=g(o.text)??g(o.refusal);if(e!==void 0)return e;const{prompt_cache_breakpoint:h,cache_control:l,...p}=o;return JSON.stringify(p)}b(A,"A"),x(A,"C"),m(A,"partText");const q=m((t,o)=>{const e={};for(const h of o){let l=t;for(const p of h.split("."))l=y(l)[p];l!==void 0&&(e[h]=l)}return e},"pick");function D(t){const o=y(t).prompt_cache_breakpoint;if(o==null||o===!1)return;const e=w(y(o).ttl);return e?{ttl:e}:{}}b(D,"P"),x(D,"F"),m(D,"openaiBreakpoint");function M(t){const o=y(t).cache_control;if(!S(o))return;const e=w(o.ttl);return e?{ttl:e}:{}}b(M,"j"),x(M,"L"),m(M,"anthropicBreakpoint");function L(t){const o=g(t.model),e=y(t.prompt_cache_options),h=H(o),l=g(e.mode)==="explicit"||g(e.mode)==="implicit",p=g(e.mode)==="explicit"?"explicit":"implicit",n=w(h?e.ttl:t.prompt_cache_retention),s=[],r=g(t.instructions);r&&s.push({label:"instructions",role:"developer",text:r}),O(t.tools).length&&s.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const i=y(y(t.text).format);i.schema!==void 0&&s.push({label:`answer schema${g(i.name)?` \xB7 ${g(i.name)}`:""}`,text:JSON.stringify(i.schema),weight:.7});let f=-1;const a=t.input;if(typeof a=="string")s.push({label:"user",role:"user",text:a}),f=s.length-1;else{const k=O(a).map(y);let v=!0;k.forEach((c,_)=>{const u=g(c.type)??(c.role?"message":""),$=g(c.role)??(u==="function_call_output"?"tool":"item"),N=u==="message"?c.content:u==="function_call_output"?c.output:void 0,J=typeof N=="string"?[N]:Array.isArray(N)?N:void 0,E=u==="message"?$:u||"item";if(J)J.forEach((R,G)=>{const B=D(R);s.push({label:J.length>1?`${E} \xB7 block ${G+1} of ${J.length}`:E,role:$,text:A(R),...B?{bp:B}:{}})});else{const{id:R,status:G,...B}=c;s.push({label:E,role:$,text:JSON.stringify(B)})}const j=k[_+1],F=j?g(j.type)??(j.role?"message":""):"";(u==="message"&&$==="user"||u==="function_call_output"&&F!=="function_call_output"||v&&u==="message"&&$==="developer"&&!(F==="message"&&g(j.role)==="developer"))&&(f=s.length-1),u==="message"&&$==="developer"||(v=!1)})}p==="implicit"&&f>=0&&(s[f].bp={...s[f].bp??{},implicit:!0});const d={model:o,...q(t,["tools","parallel_tool_calls","text.format","reasoning.effort","text.verbosity","context_management","prompt_cache_key","previous_response_id","conversation"])};return{provider:"openai",api:"responses",...o?{model:o}:{},settings:JSON.stringify(d),blocks:s,mode:p,modeSaid:l,ttl:n??I("openai",o),ttlSaid:!!n,prewarm:e.prewarm===!0,key:typeof t.prompt_cache_key=="string"}}b(L,"T"),x(L,"G"),m(L,"responsesRequest");function z(t){const o=g(t.model),e=[];O(t.tools).length&&e.push({label:"tools",text:JSON.stringify(t.tools),weight:.7});const h=y(t.response_format);h.json_schema!==void 0&&e.push({label:"answer schema",text:JSON.stringify(h.json_schema),weight:.7});let l=-1;const p=O(t.messages).map(y);p.forEach((r,i)=>{const f=g(r.role)??"user",a=r.content,d=typeof a=="string"?[a]:Array.isArray(a)?a:[];d.length||e.push({label:f,role:f,text:JSON.stringify({...r,content:void 0})}),d.forEach((v,c)=>e.push({label:d.length>1?`${f} \xB7 block ${c+1} of ${d.length}`:f,role:f,text:A(v)})),r.tool_calls!==void 0&&e.push({label:`${f} \xB7 tool calls`,role:f,text:JSON.stringify(r.tool_calls)});const k=g(p[i+1]?.role);(f==="user"||f==="tool"&&k!=="tool")&&(l=e.length-1)}),l>=0&&(e[l].bp={implicit:!0});const n=w(t.prompt_cache_retention),s={model:o,...q(t,["tools","parallel_tool_calls","response_format","reasoning_effort","verbosity","prompt_cache_key"])};return{provider:"openai",api:"chat",...o?{model:o}:{},settings:JSON.stringify(s),blocks:e,mode:"implicit",modeSaid:!1,ttl:n??I("openai",o),ttlSaid:!!n,prewarm:!1,key:typeof t.prompt_cache_key=="string"}}b(z,"I"),x(z,"Q"),m(z,"chatRequest");function P(t){const o=g(t.model),e=[];for(const i of O(t.tools).map(y)){const f=M(i),{cache_control:a,...d}=i;e.push({label:`tools \xB7 ${g(i.name)??g(i.type)??"tool"}`,text:JSON.stringify(d),weight:.7,...f?{bp:f}:{}})}const h=t.system;if(typeof h=="string"&&h)e.push({label:"system",role:"system",text:h});else{const i=O(h);i.forEach((f,a)=>{const d=M(f);e.push({label:i.length>1?`system \xB7 block ${a+1} of ${i.length}`:"system",role:"system",text:A(f),...d?{bp:d}:{}})})}for(const i of O(t.messages).map(y)){const f=g(i.role)??"user",a=i.content,d=typeof a=="string"?[a]:O(a);d.forEach((k,v)=>{const c=M(k);e.push({label:d.length>1?`${f} \xB7 block ${v+1} of ${d.length}`:f,role:f,text:A(k),...c?{bp:c}:{}})})}const l=t.cache_control,p=e.some(i=>i.bp);if(S(l)&&e.length){const i=e[e.length-1];i.bp={...i.bp??(w(l.ttl)?{ttl:w(l.ttl)}:{}),implicit:!0}}const n=p?"explicit":S(l)?"automatic":"none",s=S(l)?w(l.ttl):void 0,r={model:o,...q(t,["tool_choice","thinking","output_config.effort","speed"])};return{provider:"anthropic",api:"messages",...o?{model:o}:{},settings:JSON.stringify(r),blocks:e,mode:n,modeSaid:p||S(l),ttl:s??"5m",ttlSaid:!!s,prewarm:!1,key:!1}}b(P,"K"),x(P,"U"),m(P,"messagesRequest");export function aiCacheRequestOf(t,o){if(S(o)){if(t==="responses")return L(o);if(t==="chat")return z(o);if(t==="messages")return P(o)}}b(aiCacheRequestOf,"aiCacheRequestOf"),x(aiCacheRequestOf,"aiCacheRequestOf"),m(aiCacheRequestOf,"aiCacheRequestOf");class tt{static{b(this,"Y")}static{x(this,"V")}static{m(this,"Prefix")}constructor(){this.h1=3735928559,this.h2=1103547991,this.tokens=0,this.chars=0,this.word=0,this.digits=0,this.space=0}feed(o,e=!0,h=1){let l=this.h1,p=this.h2,n=0,s=this.word,r=this.digits,i=this.space;for(let f=0;f<o.length;f++){const a=o.charCodeAt(f);l=Math.imul(l^a,2654435761),p=Math.imul(p^a,1597334677),e&&(a>=65&&a<=90||a>=97&&a<=122?((s===0||s>=8&&(s-8)%4===3)&&(n+=1),s++,r=0,i=0):a>=48&&a<=57?(r%3===0&&(n+=1),r++,s=0,i=0):a===32||a===9||a===10||a===13?((a===10||i===1)&&(n+=i<2?1:0),i=a===10?2:i+1,s=0,r=0):(s=0,r=0,i=0,n+=a>=11904?.9:a>=192?.66:.75))}this.h1=l,this.h2=p,this.word=s,this.digits=r,this.space=i,e&&(this.tokens+=n*h,this.chars+=o.length)}digest(){let o=this.h1,e=this.h2;return o=Math.imul(o^o>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(o^o>>>13,3266489909),(4294967296*(2097151&e)+(o>>>0)).toString(36)}}export function aiCacheSections(t){const o=[];let e=0;const h=t.length;for(;e<h;){const l=t.indexOf(`
2
+ `,e),p=l<0?h:l;let n=e;for(;n<p&&(t.charCodeAt(n)===32||t.charCodeAt(n)===9);)n++;const s=t[n];if(s==="-"||s==="#"||s==="<"){const r=t.slice(n,Math.min(p,n+240)),i=s==="-"?/^-{3,}[ \t]*(.+?)[ \t]*-{3,}[ \t]*$/.exec(r):s==="#"?/^#{1,3}[ \t]+(.+?)[ \t#]*$/.exec(r):/^<([a-z][a-z0-9_-]{0,40})(?:[\s>])/.exec(r);i&&i[1].trim()&&o.push({at:e,title:i[1].trim().slice(0,Y)})}e=p+1}return o}b(aiCacheSections,"aiCacheSections"),x(aiCacheSections,"aiCacheSections"),m(aiCacheSections,"aiCacheSections");function T(t,o){const e=t.text.length,h=e>=2*K?aiCacheSections(t.text):[],l=[{block:o,from:0,to:e,title:t.label,end:!0}];if(!h.length)return l;const p=h[0].at===0?h[0].title:void 0;let n={at:0,title:p??"(opening)",last:void 0,opening:!p};const s=[],r=m(i=>`${t.label} \u203A ${i.last?`${Q(i.title)} \u2026 ${Q(i.last)}`:i.title}`,"titled");for(const i of h)if(i.at!==0){if(i.at-n.at<K){n.opening?n={at:n.at,title:i.title,last:void 0,opening:!1}:n.last=i.title;continue}s.push({block:o,from:n.at,to:i.at,title:r(n),end:!1}),n={at:i.at,title:i.title,last:void 0,opening:!1}}return s.length?(s.push({block:o,from:n.at,to:e,title:r(n),end:!0}),s):l}b(T,"X"),x(T,"W"),m(T,"regionsOf");const Q=m(t=>t.length>36?`${t.slice(0,35)}\u2026`:t,"clip"),et=4;export function aiCacheOf(t,o,e,h={}){const l=aiCacheRequestOf(t,o);if(!l)return;const p=new tt;p.feed(l.settings,!1);const n=[];l.blocks.forEach((c,_)=>{p.feed(`\0${c.role??""}`,!1),p.tokens+=et;for(const u of T(c,_))p.feed(c.text.slice(u.from,u.to),!0,c.weight??1),(u.end||n.length<MAX_MARKS-8)&&n.push({h:p.digest(),chars:p.chars,tokens:p.tokens,s:u.title,...u.end&&c.bp?{bp:c.bp}:{},blockEnd:u.end})});const s=p.tokens,r=e?.input!==void 0&&e.input>0,i=r&&s>0?e.input/s:1,f=m(c=>Math.round(c*i),"round");let a=n.map(c=>({h:c.h,t:f(c.tokens),s:c.s,...c.bp?{bp:1}:{}}));if(a.length>MAX_MARKS){const c=new Set;a.forEach((_,u)=>_.bp&&c.add(u));for(let _=a.length-1;_>=0&&c.size<MAX_MARKS;_--)c.add(_);a=a.filter((_,u)=>c.has(u))}const d=n.filter(c=>c.bp).map(c=>({at:c.s.split(" \u203A ")[0],...c.bp.ttl?{ttl:c.bp.ttl}:{},...c.bp.implicit?{implicit:!0}:{},chars:c.chars,tokens:f(c.tokens)})),k=e?.cached,v=e?.written;return{provider:l.provider,mode:l.mode,modeSaid:l.modeSaid,ttl:l.ttl,ttlSaid:l.ttlSaid,...l.prewarm||h.prewarm?{prewarm:!0}:{},...l.key?{key:!0}:{},breakpoints:d,...r?{read:k??0,written:v??0,plain:Math.max(0,e.input-(k??0)-(v??0))}:{},...e?.writes&&Object.keys(e.writes).length?{writes:{...e.writes}}:{},marks:a,estimated:!r}}b(aiCacheOf,"aiCacheOf"),x(aiCacheOf,"aiCacheOf"),m(aiCacheOf,"aiCacheOf");const U=200,C=m((t,o)=>{const e=t.lastIndexOf(`
3
3
  `,o-1)+1,h=t.indexOf(`
4
- `,o),l=t.slice(e,h<0?t.length:h).trim();return l.length>G?`${l.slice(0,G-1)}\u2026`:l},"lineAt");export function aiCacheDiff(t,o,e){if(t.settings!==o.settings){const i=JSON.parse(t.settings),s=JSON.parse(o.settings);return{region:"settings",setting:[...new Set([...Object.keys(i),...Object.keys(s)])].filter(r=>JSON.stringify(i[r])!==JSON.stringify(s[r])).join(", "),chars:0,tokens:0}}let h=0;const l=t.blocks.reduce((i,s)=>i+s.text.length,0),p=u(i=>e!==void 0&&l>0?Math.round(i/l*e):Math.round(i/4),"tokensAt");for(let i=0;i<Math.max(t.blocks.length,o.blocks.length);i++){const s=t.blocks[i],r=o.blocks[i];if(!s||!r)return{region:s?s.label:"the end of this prompt",chars:h,tokens:p(h),...s?{line:$(s.text,0)}:{},...r?{otherLine:$(r.text,0)}:{}};if(s.role!==r.role)return{region:s.label,chars:h,tokens:p(h),line:$(s.text,0),otherLine:$(r.text,0)};if(s.text===r.text){h+=s.text.length;continue}let n=0;const m=Math.min(s.text.length,r.text.length);for(;n<m&&s.text.charCodeAt(n)===r.text.charCodeAt(n);)n++;const a=[...aiCacheSections(s.text)].reverse().find(d=>d.at<=n);return{region:a?`${s.label} \u203A ${a.title}`:s.label,chars:h+n,tokens:p(h+n),line:$(s.text,Math.min(n,Math.max(0,s.text.length-1))),otherLine:$(r.text,Math.min(n,Math.max(0,r.text.length-1)))}}return{region:"(none)",chars:h,tokens:p(h),same:!0}}b(aiCacheDiff,"aiCacheDiff"),u(aiCacheDiff,"aiCacheDiff");
4
+ `,o),l=t.slice(e,h<0?t.length:h).trim();return l.length>U?`${l.slice(0,U-1)}\u2026`:l},"lineAt");export function aiCacheDiff(t,o,e){if(t.settings!==o.settings){const n=JSON.parse(t.settings),s=JSON.parse(o.settings);return{region:"settings",setting:[...new Set([...Object.keys(n),...Object.keys(s)])].filter(r=>JSON.stringify(n[r])!==JSON.stringify(s[r])).join(", "),chars:0,tokens:0}}let h=0;const l=t.blocks.reduce((n,s)=>n+s.text.length,0),p=m(n=>e!==void 0&&l>0?Math.round(n/l*e):Math.round(n/4),"tokensAt");for(let n=0;n<Math.max(t.blocks.length,o.blocks.length);n++){const s=t.blocks[n],r=o.blocks[n];if(!s||!r)return{region:s?s.label:"the end of this prompt",chars:h,tokens:p(h),...s?{line:C(s.text,0)}:{},...r?{otherLine:C(r.text,0)}:{}};if(s.role!==r.role)return{region:s.label,chars:h,tokens:p(h),line:C(s.text,0),otherLine:C(r.text,0)};if(s.text===r.text){h+=s.text.length;continue}let i=0;const f=Math.min(s.text.length,r.text.length);for(;i<f&&s.text.charCodeAt(i)===r.text.charCodeAt(i);)i++;const a=[...aiCacheSections(s.text)].reverse().find(d=>d.at<=i);return{region:a?`${s.label} \u203A ${a.title}`:s.label,chars:h+i,tokens:p(h+i),line:C(s.text,Math.min(i,Math.max(0,s.text.length-1))),otherLine:C(r.text,Math.min(i,Math.max(0,r.text.length-1)))}}return{region:"(none)",chars:h,tokens:p(h),same:!0}}b(aiCacheDiff,"aiCacheDiff"),x(aiCacheDiff,"aiCacheDiff"),m(aiCacheDiff,"aiCacheDiff");
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var i=(t,a)=>m(t,"name",{value:a,configurable:!0});var u=Object.defineProperty,c=i((t,a)=>u(t,"name",{value:a,configurable:!0}),"i");export function aiTotalsOf(t){const a=t.filter(e=>!e.prewarm),n={calls:a.length,prewarms:t.length-a.length,runs:new Set(a.map(e=>e.run.key)).size,failed:0,input:0,cached:0,written:0,output:0,split:{},costUsd:0,priced:0,first:1/0,last:0,models:[]},o=new Map;for(const e of t){e.failed&&n.failed++,n.input+=e.tokens?.input??0,n.cached+=e.tokens?.cached??0,n.written+=e.tokens?.written??0,n.output+=e.tokens?.output??0;for(const[r,s]of Object.entries(e.split??{}))n.split[r]=(n.split[r]??0)+s;e.costUsd!==void 0&&(n.costUsd+=e.costUsd,n.priced++),n.first=Math.min(n.first,e.at),n.last=Math.max(n.last,e.at),e.model&&o.set(e.model,(o.get(e.model)??0)+1)}return n.models=[...o].sort((e,r)=>r[1]-e[1]).map(([e])=>e),t.length||(n.first=0),n}i(aiTotalsOf,"aiTotalsOf"),c(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(t,a=!1){const n=new Map;for(const o of t){const e=n.get(o.run.key);e?e.push(o):n.set(o.run.key,[o])}return[...n.entries()].map(([o,e])=>{e.sort((s,l)=>(s.step??0)-(l.step??0)||s.at-l.at);const r=aiTotalsOf(e);return{key:o,from:e[0].run.from,calls:e,at:r.first,last:r.last,totals:r}}).sort((o,e)=>a?o.at-e.at:e.last-o.last)}i(aiRunsOf,"aiRunsOf"),c(aiRunsOf,"aiRunsOf");const d="(none)";function f(t,a){if(a==="agent")return t.agent;if(a==="action")return t.action??{key:"action:",name:"(no action)"};if(a==="run")return{key:t.run.key,name:t.agent.name};if(a==="thread")return t.thread?{key:t.thread.key,name:`thread ${t.thread.name}`}:{key:"thread:",name:"(no thread)"};if(a==="flow")return t.flowId?{key:`flow:${t.flowId}`,name:t.flowId}:t.requestId?{key:`request:${t.requestId}`,name:`request ${t.requestId}`}:{key:"flow:",name:"(no flow)"};if(a==="model")return{key:`model:${t.model??""}`,name:t.model??"(unknown model)"};if(a==="service")return{key:`service:${t.service}`,name:t.service};const n=a.slice(5),o=t.meta?.[n];return{key:`${a}=${o??""}`,name:o??d}}i(f,"m"),c(f,"keyOf");export function groupAiCalls(t,a,n){const o=new Map;for(const r of t){const s=f(r,a),l=o.get(s.key);l?l.rows.push(r):o.set(s.key,{...s,rows:[r]})}const e=a==="agent"||a==="action";return[...o.values()].map(r=>({key:r.key,name:r.name,...r.from?{from:r.from}:{},nameable:e&&/^(agent|action):./.test(r.key),merged:n?Object.entries(n.merge).filter(([,s])=>s===r.key).map(([s])=>s).sort():[],runs:aiRunsOf(r.rows,a==="flow"),totals:aiTotalsOf(r.rows)})).sort((r,s)=>s.totals.last-r.totals.last||r.name.localeCompare(s.name))}i(groupAiCalls,"groupAiCalls"),c(groupAiCalls,"groupAiCalls");export function matchesAi(t,a){const n=a.toLowerCase().split(/\s+/).filter(Boolean);if(!n.length)return!0;const o=[t.id,t.agent.name,t.action?.name,t.model,t.service,t.flowId,t.requestId,t.schema,t.asked,t.said,...t.called??[],...Object.entries(t.meta??{}).map(([e,r])=>`${e}:${r}`)].filter(Boolean).join(`
2
- `).toLowerCase();return n.every(e=>o.includes(e))}i(matchesAi,"matchesAi"),c(matchesAi,"matchesAi");
1
+ "use strict";var m=Object.defineProperty;var i=(e,n)=>m(e,"name",{value:n,configurable:!0});var d=Object.defineProperty,l=i((e,n)=>d(e,"name",{value:n,configurable:!0}),"i"),p=Object.defineProperty,f=l((e,n)=>p(e,"name",{value:n,configurable:!0}),"i");export function aiTotalsOf(e){const n=e.filter(t=>!t.prewarm),o={calls:n.length,prewarms:e.length-n.length,runs:new Set(n.map(t=>t.run.key)).size,failed:0,input:0,cached:0,written:0,output:0,split:{},costUsd:0,priced:0,first:1/0,last:0,models:[]},r=new Map;for(const t of e){t.failed&&o.failed++,o.input+=t.tokens?.input??0,o.cached+=t.tokens?.cached??0,o.written+=t.tokens?.written??0,o.output+=t.tokens?.output??0;for(const[s,a]of Object.entries(t.split??{}))o.split[s]=(o.split[s]??0)+a;t.costUsd!==void 0&&(o.costUsd+=t.costUsd,o.priced++),o.first=Math.min(o.first,t.at),o.last=Math.max(o.last,t.at),t.model&&r.set(t.model,(r.get(t.model)??0)+1)}return o.models=[...r].sort((t,s)=>s[1]-t[1]).map(([t])=>t),e.length||(o.first=0),o}i(aiTotalsOf,"aiTotalsOf"),l(aiTotalsOf,"aiTotalsOf"),f(aiTotalsOf,"aiTotalsOf");export function aiRunsOf(e,n=!1){const o=new Map;for(const r of e){const t=o.get(r.run.key);t?t.push(r):o.set(r.run.key,[r])}return[...o.entries()].map(([r,t])=>{t.sort((a,c)=>(a.step??0)-(c.step??0)||a.at-c.at);const s=aiTotalsOf(t);return{key:r,from:t[0].run.from,calls:t,at:s.first,last:s.last,totals:s}}).sort((r,t)=>n?r.at-t.at:t.last-r.last)}i(aiRunsOf,"aiRunsOf"),l(aiRunsOf,"aiRunsOf"),f(aiRunsOf,"aiRunsOf");const k="(none)";function u(e,n){if(n==="agent")return e.agent;if(n==="action")return e.action??{key:"action:",name:"(no action)"};if(n==="run")return{key:e.run.key,name:e.agent.name};if(n==="thread")return e.thread?{key:e.thread.key,name:`thread ${e.thread.name}`}:{key:"thread:",name:"(no thread)"};if(n==="flow")return e.flowId?{key:`flow:${e.flowId}`,name:e.flowId}:e.requestId?{key:`request:${e.requestId}`,name:`request ${e.requestId}`}:{key:"flow:",name:"(no flow)"};if(n==="model")return{key:`model:${e.model??""}`,name:e.model??"(unknown model)"};if(n==="service")return{key:`service:${e.service}`,name:e.service};const o=n.slice(5),r=e.meta?.[o];return{key:`${n}=${r??""}`,name:r??k}}i(u,"f"),l(u,"m"),f(u,"keyOf");export function groupAiCalls(e,n,o){const r=new Map;for(const s of e){const a=u(s,n),c=r.get(a.key);c?c.rows.push(s):r.set(a.key,{...a,rows:[s]})}const t=n==="agent"||n==="action";return[...r.values()].map(s=>({key:s.key,name:s.name,...s.from?{from:s.from}:{},nameable:t&&/^(agent|action):./.test(s.key),merged:o?Object.entries(o.merge).filter(([,a])=>a===s.key).map(([a])=>a).sort():[],runs:aiRunsOf(s.rows,n==="flow"),totals:aiTotalsOf(s.rows)})).sort((s,a)=>a.totals.last-s.totals.last||s.name.localeCompare(a.name))}i(groupAiCalls,"groupAiCalls"),l(groupAiCalls,"groupAiCalls"),f(groupAiCalls,"groupAiCalls");export function matchesAi(e,n){const o=n.toLowerCase().split(/\s+/).filter(Boolean);if(!o.length)return!0;const r=[e.id,e.agent.name,e.action?.name,e.model,e.service,e.flowId,e.requestId,e.schema,e.asked,e.said,...e.called??[],...Object.entries(e.meta??{}).map(([t,s])=>`${t}:${s}`)].filter(Boolean).join(`
2
+ `).toLowerCase();return o.every(t=>r.includes(t))}i(matchesAi,"matchesAi"),l(matchesAi,"matchesAi"),f(matchesAi,"matchesAi");
@@ -1,3 +1,3 @@
1
- "use strict";var B=Object.defineProperty;var m=(t,o)=>B(t,"name",{value:o,configurable:!0});var T=Object.defineProperty,c=m((t,o)=>T(t,"name",{value:o,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as q,aiSplitOf as E}from"./ai-context.js";export function aiCallCacheOf(t){return{mode:t.mode,...t.modeSaid?{modeSaid:!0}:{},ttl:t.ttl,...t.ttlSaid?{ttlSaid:!0}:{},...t.key?{key:!0}:{},breakpoints:t.breakpoints.map(o=>({at:o.at,tokens:o.tokens,...o.ttl?{ttl:o.ttl}:{},...o.implicit?{implicit:!0}:{}})),...t.writes?{writes:{...t.writes}}:{},...t.marks.length?{marks:t.marks}:{}}}m(aiCallCacheOf,"aiCallCacheOf"),c(aiCallCacheOf,"aiCallCacheOf");export function aiRowOut(t){if(!t.cache?.marks)return t;const{marks:o,...e}=t.cache;return{...t,cache:e}}m(aiRowOut,"aiRowOut"),c(aiRowOut,"aiRowOut");export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(t,o){const e=o.toLowerCase(),a=new Map;for(const n of t){if(n.host.toLowerCase()!==e)continue;const s=n.model??"unknown";let r=a.get(s);r||(r={use:{model:s,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:n.at,last:n.at},agents:new Set},a.set(s,r));const i=r.use;n.prewarm?i.prewarms=(i.prewarms??0)+1:i.calls+=1,n.failed&&(i.failed+=1),n.tokens?(i.input+=n.tokens.input??0,i.cached+=n.tokens.cached??0,i.output+=n.tokens.output??0):i.unmetered+=1,n.costUsd!==void 0&&(i.costUsd+=n.costUsd,i.priced+=1),r.agents.add(n.agent.key),i.first=Math.min(i.first,n.at),i.last=Math.max(i.last,n.at)}return[...a.values()].map(({use:n,agents:s})=>({...n,agents:s.size})).sort((n,s)=>s.calls-n.calls||s.last-n.last)}m(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(t,o){const e=o?.toLowerCase(),a=new Map;for(const n of t){if(e!==void 0&&n.host.toLowerCase()!==e)continue;let s=a.get(n.agent.key);s||(s={use:{key:n.agent.key,name:n.agent.name,from:n.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:n.at},runs:new Set,models:new Map},a.set(n.agent.key,s));const r=s.use;n.prewarm?r.prewarms=(r.prewarms??0)+1:(r.calls+=1,s.runs.add(n.run.key)),n.failed&&(r.failed+=1),r.input+=n.tokens?.input??0,r.cached+=n.tokens?.cached??0,r.written+=n.tokens?.written??0,r.output+=n.tokens?.output??0,n.costUsd!==void 0&&(r.costUsd+=n.costUsd,r.priced+=1);for(const[i,u]of Object.entries(n.split??{}))r.split[i]=(r.split[i]??0)+u;n.model&&s.models.set(n.model,(s.models.get(n.model)??0)+1),r.last=Math.max(r.last,n.at)}return[...a.values()].map(({use:n,runs:s,models:r})=>({...n,runs:s.size,models:[...r].sort((i,u)=>u[1]-i[1]).map(([i])=>i)})).sort((n,s)=>s.input-n.input||s.calls-n.calls)}m(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const K=160,A="unknown service";export const aiKeyOf=c((t,o)=>`${t}:${o.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(t){const o=t.trim();if(/[A-Z]/.test(o)||/ /.test(o))return o;const e=o.replace(/[-_.]+/g," ").trim();return e?e[0].toUpperCase()+e.slice(1):o}m(humanName,"humanName"),c(humanName,"humanName");const f=c((t,o=K)=>{if(!t)return;const e=t.replace(/\s+/g," ").trim();if(e)return e.length>o?`${e.slice(0,o-1)}\u2026`:e},"line");export function promptTitle(t){const o=t.split(`
2
- `).map(n=>n.trim()).find(Boolean)??"",e=/^#{1,6}\s+(.+)$/.exec(o);if(e){const n=e[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return n?n.slice(0,60):void 0}const a=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(o);if(a){const n=a[1].trim().split(/\s+/);if(n.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(n[0]))return;const s=n.join(" ");return s[0].toUpperCase()+s.slice(1)}}m(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(t){const o=t.split(`
3
- `).map(a=>a.trim()).find(Boolean);if(!o)return;const e=o.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(e.length<3))return e.length>7?`${e.slice(0,7).join(" ")} \u2026`:e.join(" ")}m(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(t){const o=t.split("::")[0],e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return o.split(":").map(a=>a.split(".").filter(n=>!e.test(n)).join(".")).filter((a,n,s)=>a||n<s.length-1).join(":").slice(0,120)}m(actionName,"actionName"),c(actionName,"actionName");const g=c((t,o)=>{const e=t.request.headers.find(([a])=>a.toLowerCase()===o)?.[1];if(e===void 0||!o.startsWith("x-lensmcp-")||!e.includes("%"))return e;try{return decodeURIComponent(e)}catch{return e}},"header"),U=c(t=>t!==void 0&&/^\d{1,6}$/.test(t.trim())?Number(t.trim()):void 0,"intOf"),h=c((t,...o)=>{for(const e of o)if(t[e]?.trim())return t[e].trim()},"first");function _(t){const o={};for(const e of t.settings)if(e.name.startsWith("metadata.")){if(Object.keys(o).length>=MAX_META)break;o[e.name.slice(9)]=e.value.slice(0,200)}return o}m(_,"B"),c(_,"metaOf");function N(t,o,e){const a=c((p,k)=>({key:aiKeyOf("agent",p),name:humanName(p),from:k}),"named"),n=h(e,"agent","agent_name","agentName","assistant");if(n)return a(n,"metadata");const s=g(t,"x-lensmcp-agent");if(s?.trim())return a(s.trim(),"header");const r=o.system.map(p=>promptTitle(p.text)).find(Boolean);if(r)return a(r,"prompt");const i=o.answer.format?.name;if(i)return a(i,"schema");const u=[...o.tools,...o.answer.toolCalls].map(p=>p.server).find(Boolean);if(u)return a(u,"tools");const l=o.system.map(p=>promptOpening(p.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:a(`${t.service??A} ${o.api==="embeddings"?"embeddings":o.model??o.api}`,"service")}m(N,"E"),c(N,"agentOf");function R(t,o,e){const a=c((r,i)=>({key:aiKeyOf("action",r),name:r,from:i}),"named"),n=h(e,"act","action","task","step","operation");if(n&&actionName(n))return a(actionName(n),"metadata");const s=g(t,"x-lensmcp-action");if(s?.trim())return a(actionName(s.trim()),"header");if(o.answer.format?.name)return a(o.answer.format.name,"schema")}m(R,"x"),c(R,"actionOf");function L(t){if(t.kind==="message")return f(t.text);if(t.kind==="tool")return f(t.output!==void 0?`${t.tool} \u2192 ${t.output}`:`${t.tool}(${t.arguments})`)}m(L,"z"),c(L,"turnLine");function v(t){const o=t.answer;return o.error?f(`error: ${o.error}`):o.refusal?f(`refused: ${o.refusal}`):o.toolCalls.length?f(o.toolCalls.map(e=>`${e.tool}(${e.arguments})`).join(" \xB7 ")):t.embedding?`${t.embedding.vectors??t.embedding.count} vector${(t.embedding.vectors??t.embedding.count)===1?"":"s"}${t.embedding.dimensions?` \xD7 ${t.embedding.dimensions}`:""}`:f(o.text)}m(v,"A"),c(v,"saidLine");function S(t,o){if(o)return{why:"failed",said:"It failed \u2014 the provider counted nothing for it."};const e=t.gaps.find(a=>/^The (answer|stream)\b/.test(a)||/of the stream’s events were kept/.test(a));return e&&/was not kept|only each event’s name/.test(e)?{why:"not-kept",said:e}:e?{why:"cut",said:`Its token counts were not kept: ${e}`}:{why:"not-sent",said:"Its answer was kept whole, and the provider counted no tokens in it."}}m(S,"q"),c(S,"noUsageOf");export function aiCallRow(t,o){const e=z(t);if(!e||!t.ai)return;const a=_(e),n=new Map(e.settings.map(d=>[d.name,d.value])),s=h(a,"run","run_id","runId"),r=g(t,"x-lensmcp-run")?.trim(),i=e.turns.filter(d=>d.kind==="tool").filter(d=>d.output!==void 0&&d.callId).map(d=>d.callId),u=e.answer.toolCalls.map(d=>d.callId).filter(d=>!!d),l=e.usage,p=l?{...l.input!==void 0?{input:l.input}:{},...l.cached?{cached:l.cached}:{},...l.written?{written:l.written}:{},...l.output!==void 0?{output:l.output}:{},...l.reasoning?{reasoning:l.reasoning}:{}}:void 0,k=e.shape==="embedding"||l?.input===void 0?{}:E(q(e,{sections:!1})),w=h(a,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),y=g(t,"x-lensmcp-thread")?.trim(),b=h(a,"parent_run","parentRun","parent")??g(t,"x-lensmcp-parent")?.trim(),x=R(t,e,a),$=U(a.round),O=U(a.attempt),I=n.get("continues response"),C=[...e.turns].reverse().map(L).find(Boolean),M=e.answer.status==="failed"||!!e.answer.error||(t.status??0)>=400||!!t.error,j=p&&Object.keys(p).length?void 0:S(e,M);return{id:t.id,at:t.startedAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.status!==void 0?{status:t.status}:{},...M?{failed:!0}:{},service:t.service??A,...t.flowId?{flowId:t.flowId}:{},...t.requestId?{requestId:t.requestId}:{},provider:t.ai.provider,host:t.host,api:e.api,shape:e.shape,...e.model?{model:e.model}:{},...t.response.stream?{streamed:!0}:{},...p&&Object.keys(p).length?{tokens:p}:{},...Object.keys(k).length?{split:k}:{},...e.cache?.prewarm?{prewarm:!0}:{},...e.cache?{cache:aiCallCacheOf(e.cache)}:{},agent:N(t,e,a),run:s?{key:`run:${s}`,from:"metadata"}:r?{key:`run:${r}`,from:"header"}:{key:`run:${t.id}`,from:"alone"},...w?{thread:{key:`thread:${w}`,name:w,from:"metadata"}}:y?{thread:{key:`thread:${y}`,name:y,from:"header"}}:{},...b?{parent:`run:${b}`}:{},...$!==void 0?{round:$}:{},...O!==void 0?{attempt:O}:{},...x?{action:x}:{},...e.answer.format?.name?{schema:e.answer.format.name}:{},...e.tools.length?{tools:e.tools.slice(0,MAX_TOOLS).map(d=>d.name)}:{},...e.answer.toolCalls.length?{called:e.answer.toolCalls.map(d=>d.name)}:{},...u.length?{callIds:u}:{},...i.length?{answers:i}:{},...e.responseId?{responseId:e.responseId}:{},...I?{previousResponseId:I}:{},...Object.keys(a).length?{meta:a}:{},...e.gaps.some(d=>/kept to its first|cut/.test(d))?{cut:!0}:{},...j?{noUsage:j}:{},...o.content&&C?{asked:C}:{},...o.content&&v(e)?{said:v(e)}:{}}}m(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(t){const o=[...t].sort((s,r)=>s.at-r.at||s.id.localeCompare(r.id)),e=new Map,a=new Map;for(const s of o){if(s.run.from==="alone"){const r=s.previousResponseId?e.get(s.previousResponseId):void 0,i=r?void 0:s.answers?.map(l=>a.get(l)).find(Boolean),u=r??i;if(u){const l=r?"chain":"tools";s.run={key:u.run.key,from:u.run.from==="alone"||u.run.from===l?l:u.run.from},u.run.from==="alone"&&(u.run={key:u.run.key,from:l})}}s.responseId&&e.set(s.responseId,s);for(const r of s.callIds??[])a.set(r,s)}const n=new Map;for(const s of o){const r=(n.get(s.run.key)??0)+1;n.set(s.run.key,r),s.step=r}return t}m(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(t,o){let e=o;for(let a=0;a<8&&t.merge[e]&&t.merge[e]!==o;a++)e=t.merge[e];return e}m(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(t,o){if(!Object.keys(o.names).length&&!Object.keys(o.merge).length)return t;const e=new Map;for(const n of t)e.has(n.agent.key)||e.set(n.agent.key,n.agent),n.action&&!e.has(n.action.key)&&e.set(n.action.key,n.action);const a=c(n=>{const s=mergedKey(o,n.key),r=o.names[s];if(r)return{key:s,name:r,from:"renamed"};if(s===n.key)return n;const i=e.get(s);return{key:s,name:i?.name??humanName(s.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of t)n.agent=a(n.agent),n.action&&(n.action=a(n.action));return t}m(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(t){const o=t&&typeof t=="object"?t:{},e=c(a=>{const n={};if(a&&typeof a=="object"&&!Array.isArray(a))for(const[s,r]of Object.entries(a))/^(agent|action):/.test(s)&&typeof r=="string"&&r.trim()&&(n[s]=r.trim().slice(0,120));return n},"pick");return{version:1,names:e(o.names),merge:e(o.merge)}}m(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
1
+ "use strict";var T=Object.defineProperty;var m=(e,s)=>T(e,"name",{value:s,configurable:!0});var z=Object.defineProperty,d=m((e,s)=>z(e,"name",{value:s,configurable:!0}),"m"),K=Object.defineProperty,c=d((e,s)=>K(e,"name",{value:s,configurable:!0}),"d");import{aiCallOf as q}from"./ai-call.js";import{aiContextOf as E,aiSplitOf as D}from"./ai-context.js";export function aiCallCacheOf(e){return{mode:e.mode,...e.modeSaid?{modeSaid:!0}:{},ttl:e.ttl,...e.ttlSaid?{ttlSaid:!0}:{},...e.key?{key:!0}:{},breakpoints:e.breakpoints.map(s=>({at:s.at,tokens:s.tokens,...s.ttl?{ttl:s.ttl}:{},...s.implicit?{implicit:!0}:{}})),...e.writes?{writes:{...e.writes}}:{},...e.marks.length?{marks:e.marks}:{}}}m(aiCallCacheOf,"aiCallCacheOf"),d(aiCallCacheOf,"aiCallCacheOf"),c(aiCallCacheOf,"aiCallCacheOf");export function aiRowOut(e){if(!e.cache?.marks)return e;const{marks:s,...t}=e.cache;return{...e,cache:t}}m(aiRowOut,"aiRowOut"),d(aiRowOut,"aiRowOut"),c(aiRowOut,"aiRowOut");export const EMPTY_AI_NAMES={version:1,names:{},merge:{}};export function aiModelUses(e,s){const t=s.toLowerCase(),r=new Map;for(const n of e){if(n.host.toLowerCase()!==t)continue;const a=n.model??"unknown";let o=r.get(a);o||(o={use:{model:a,calls:0,failed:0,unmetered:0,input:0,cached:0,output:0,costUsd:0,priced:0,agents:0,first:n.at,last:n.at},agents:new Set},r.set(a,o));const i=o.use;n.prewarm?i.prewarms=(i.prewarms??0)+1:i.calls+=1,n.failed&&(i.failed+=1),n.tokens?(i.input+=n.tokens.input??0,i.cached+=n.tokens.cached??0,i.output+=n.tokens.output??0):i.unmetered+=1,n.costUsd!==void 0&&(i.costUsd+=n.costUsd,i.priced+=1),o.agents.add(n.agent.key),i.first=Math.min(i.first,n.at),i.last=Math.max(i.last,n.at)}return[...r.values()].map(({use:n,agents:a})=>({...n,agents:a.size})).sort((n,a)=>a.calls-n.calls||a.last-n.last)}m(aiModelUses,"aiModelUses"),d(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(e,s){const t=s?.toLowerCase(),r=new Map;for(const n of e){if(t!==void 0&&n.host.toLowerCase()!==t)continue;let a=r.get(n.agent.key);a||(a={use:{key:n.agent.key,name:n.agent.name,from:n.agent.from,calls:0,runs:0,failed:0,input:0,cached:0,written:0,output:0,costUsd:0,priced:0,split:{},models:[],last:n.at},runs:new Set,models:new Map},r.set(n.agent.key,a));const o=a.use;n.prewarm?o.prewarms=(o.prewarms??0)+1:(o.calls+=1,a.runs.add(n.run.key)),n.failed&&(o.failed+=1),o.input+=n.tokens?.input??0,o.cached+=n.tokens?.cached??0,o.written+=n.tokens?.written??0,o.output+=n.tokens?.output??0,n.costUsd!==void 0&&(o.costUsd+=n.costUsd,o.priced+=1);for(const[i,p]of Object.entries(n.split??{}))o.split[i]=(o.split[i]??0)+p;n.model&&a.models.set(n.model,(a.models.get(n.model)??0)+1),o.last=Math.max(o.last,n.at)}return[...r.values()].map(({use:n,runs:a,models:o})=>({...n,runs:a.size,models:[...o].sort((i,p)=>p[1]-i[1]).map(([i])=>i)})).sort((n,a)=>a.input-n.input||a.calls-n.calls)}m(aiAgentUses,"aiAgentUses"),d(aiAgentUses,"aiAgentUses"),c(aiAgentUses,"aiAgentUses");export const MAX_TOOLS=40,MAX_THREAD_CALLS=300,MAX_META=24;const P=160,B="unknown service";export const aiKeyOf=c((e,s)=>`${e}:${s.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const s=e.trim();if(/[A-Z]/.test(s)||/ /.test(s))return s;const t=s.replace(/[-_.]+/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):s}m(humanName,"humanName"),d(humanName,"humanName"),c(humanName,"humanName");const g=c((e,s=P)=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>s?`${t.slice(0,s-1)}\u2026`:t},"line");export function promptTitle(e){const s=e.split(`
2
+ `).map(n=>n.trim()).find(Boolean)??"",t=/^#{1,6}\s+(.+)$/.exec(s);if(t){const n=t[1].split(/\s+[—–]\s+|\s+-\s+|:\s/)[0].replace(/[*_`]/g,"").trim();return n?n.slice(0,60):void 0}const r=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(s);if(r){const n=r[1].trim().split(/\s+/);if(n.length>6||/^(?:going|about|given|now|here|responsible|able|allowed|expected|tasked|asked|helping|working|being|not)$/i.test(n[0]))return;const a=n.join(" ");return a[0].toUpperCase()+a.slice(1)}}m(promptTitle,"promptTitle"),d(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(e){const s=e.split(`
3
+ `).map(r=>r.trim()).find(Boolean);if(!s)return;const t=s.replace(/^[#>*\s-]+/,"").split(/\s+/).filter(Boolean);if(!(t.length<3))return t.length>7?`${t.slice(0,7).join(" ")} \u2026`:t.join(" ")}m(promptOpening,"promptOpening"),d(promptOpening,"promptOpening"),c(promptOpening,"promptOpening");export function actionName(e){const s=e.split("::")[0],t=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,}|\d{4,})$/i;return s.split(":").map(r=>r.split(".").filter(n=>!t.test(n)).join(".")).filter((r,n,a)=>r||n<a.length-1).join(":").slice(0,120)}m(actionName,"actionName"),d(actionName,"actionName"),c(actionName,"actionName");const h=c((e,s)=>{const t=e.request.headers.find(([r])=>r.toLowerCase()===s)?.[1];if(t===void 0||!s.startsWith("x-lensmcp-")||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}},"header"),S=c(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),k=c((e,...s)=>{for(const t of s)if(e[t]?.trim())return e[t].trim()},"first");function x(e){const s={};for(const t of e.settings)if(t.name.startsWith("metadata.")){if(Object.keys(s).length>=MAX_META)break;s[t.name.slice(9)]=t.value.slice(0,200)}return s}m(x,"_"),d(x,"B"),c(x,"metaOf");function O(e,s,t){const r=c((f,w)=>({key:aiKeyOf("agent",f),name:humanName(f),from:w}),"named"),n=k(t,"agent","agent_name","agentName","assistant");if(n)return r(n,"metadata");const a=h(e,"x-lensmcp-agent");if(a?.trim())return r(a.trim(),"header");const o=s.system.map(f=>promptTitle(f.text)).find(Boolean);if(o)return r(o,"prompt");const i=s.answer.format?.name;if(i)return r(i,"schema");const p=[...s.tools,...s.answer.toolCalls].map(f=>f.server).find(Boolean);if(p)return r(p,"tools");const l=s.system.map(f=>promptOpening(f.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:r(`${e.service??B} ${s.api==="embeddings"?"embeddings":s.model??s.api}`,"service")}m(O,"N"),d(O,"E"),c(O,"agentOf");function $(e,s,t){const r=c((o,i)=>({key:aiKeyOf("action",o),name:o,from:i}),"named"),n=k(t,"act","action","task","step","operation");if(n&&actionName(n))return r(actionName(n),"metadata");const a=h(e,"x-lensmcp-action");if(a?.trim())return r(actionName(a.trim()),"header");if(s.answer.format?.name)return r(s.answer.format.name,"schema")}m($,"R"),d($,"x"),c($,"actionOf");function C(e){if(e.kind==="message")return g(e.text);if(e.kind==="tool")return g(e.output!==void 0?`${e.tool} \u2192 ${e.output}`:`${e.tool}(${e.arguments})`)}m(C,"L"),d(C,"z"),c(C,"turnLine");function y(e){const s=e.answer;return s.error?g(`error: ${s.error}`):s.refusal?g(`refused: ${s.refusal}`):s.toolCalls.length?g(s.toolCalls.map(t=>`${t.tool}(${t.arguments})`).join(" \xB7 ")):e.embedding?`${e.embedding.vectors??e.embedding.count} vector${(e.embedding.vectors??e.embedding.count)===1?"":"s"}${e.embedding.dimensions?` \xD7 ${e.embedding.dimensions}`:""}`:g(s.text)}m(y,"v"),d(y,"A"),c(y,"saidLine");function I(e,s){if(s)return{why:"failed",said:"It failed \u2014 the provider counted nothing for it."};const t=e.gaps.find(r=>/^The (answer|stream)\b/.test(r)||/of the stream’s events were kept/.test(r));return t&&/was not kept|only each event’s name/.test(t)?{why:"not-kept",said:t}:t?{why:"cut",said:`Its token counts were not kept: ${t}`}:{why:"not-sent",said:"Its answer was kept whole, and the provider counted no tokens in it."}}m(I,"S"),d(I,"q"),c(I,"noUsageOf");export function aiCallRow(e,s){const t=q(e);if(!t||!e.ai)return;const r=x(t),n=new Map(t.settings.map(u=>[u.name,u.value])),a=k(r,"run","run_id","runId"),o=h(e,"x-lensmcp-run")?.trim(),i=t.turns.filter(u=>u.kind==="tool").filter(u=>u.output!==void 0&&u.callId).map(u=>u.callId),p=t.answer.toolCalls.map(u=>u.callId).filter(u=>!!u),l=t.usage,f=l?{...l.input!==void 0?{input:l.input}:{},...l.cached?{cached:l.cached}:{},...l.written?{written:l.written}:{},...l.output!==void 0?{output:l.output}:{},...l.reasoning?{reasoning:l.reasoning}:{}}:void 0,w=t.shape==="embedding"||l?.input===void 0?{}:D(E(t,{sections:!1})),v=k(r,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),b=h(e,"x-lensmcp-thread")?.trim(),M=k(r,"parent_run","parentRun","parent")??h(e,"x-lensmcp-parent")?.trim(),A=$(e,t,r),j=S(r.round),U=S(r.attempt),N=n.get("continues response"),R=[...t.turns].reverse().map(C).find(Boolean),_=t.answer.status==="failed"||!!t.answer.error||(e.status??0)>=400||!!e.error,L=f&&Object.keys(f).length?void 0:I(t,_);return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},..._?{failed:!0}:{},service:e.service??B,...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},provider:e.ai.provider,host:e.host,api:t.api,shape:t.shape,...t.model?{model:t.model}:{},...e.response.stream?{streamed:!0}:{},...f&&Object.keys(f).length?{tokens:f}:{},...Object.keys(w).length?{split:w}:{},...t.cache?.prewarm?{prewarm:!0}:{},...t.cache?{cache:aiCallCacheOf(t.cache)}:{},agent:O(e,t,r),run:a?{key:`run:${a}`,from:"metadata"}:o?{key:`run:${o}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...v?{thread:{key:`thread:${v}`,name:v,from:"metadata"}}:b?{thread:{key:`thread:${b}`,name:b,from:"header"}}:{},...M?{parent:`run:${M}`}:{},...j!==void 0?{round:j}:{},...U!==void 0?{attempt:U}:{},...A?{action:A}:{},...t.answer.format?.name?{schema:t.answer.format.name}:{},...t.tools.length?{tools:t.tools.slice(0,MAX_TOOLS).map(u=>u.name)}:{},...t.answer.toolCalls.length?{called:t.answer.toolCalls.map(u=>u.name)}:{},...p.length?{callIds:p}:{},...i.length?{answers:i}:{},...t.responseId?{responseId:t.responseId}:{},...N?{previousResponseId:N}:{},...Object.keys(r).length?{meta:r}:{},...t.gaps.some(u=>/kept to its first|cut/.test(u))?{cut:!0}:{},...L?{noUsage:L}:{},...s.content&&R?{asked:R}:{},...s.content&&y(t)?{said:y(t)}:{}}}m(aiCallRow,"aiCallRow"),d(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(e){const s=[...e].sort((a,o)=>a.at-o.at||a.id.localeCompare(o.id)),t=new Map,r=new Map;for(const a of s){if(a.run.from==="alone"){const o=a.previousResponseId?t.get(a.previousResponseId):void 0,i=o?void 0:a.answers?.map(l=>r.get(l)).find(Boolean),p=o??i;if(p){const l=o?"chain":"tools";a.run={key:p.run.key,from:p.run.from==="alone"||p.run.from===l?l:p.run.from},p.run.from==="alone"&&(p.run={key:p.run.key,from:l})}}a.responseId&&t.set(a.responseId,a);for(const o of a.callIds??[])r.set(o,a)}const n=new Map;for(const a of s){const o=(n.get(a.run.key)??0)+1;n.set(a.run.key,o),a.step=o}return e}m(linkAiRuns,"linkAiRuns"),d(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(e,s){let t=s;for(let r=0;r<8&&e.merge[t]&&e.merge[t]!==s;r++)t=e.merge[t];return t}m(mergedKey,"mergedKey"),d(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(e,s){if(!Object.keys(s.names).length&&!Object.keys(s.merge).length)return e;const t=new Map;for(const n of e)t.has(n.agent.key)||t.set(n.agent.key,n.agent),n.action&&!t.has(n.action.key)&&t.set(n.action.key,n.action);const r=c(n=>{const a=mergedKey(s,n.key),o=s.names[a];if(o)return{key:a,name:o,from:"renamed"};if(a===n.key)return n;const i=t.get(a);return{key:a,name:i?.name??humanName(a.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of e)n.agent=r(n.agent),n.action&&(n.action=r(n.action));return e}m(applyAiNames,"applyAiNames"),d(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(e){const s=e&&typeof e=="object"?e:{},t=c(r=>{const n={};if(r&&typeof r=="object"&&!Array.isArray(r))for(const[a,o]of Object.entries(r))/^(agent|action):/.test(a)&&typeof o=="string"&&o.trim()&&(n[a]=o.trim().slice(0,120));return n},"pick");return{version:1,names:t(s.names),merge:t(s.merge)}}m(aiNamesOf,"aiNamesOf"),d(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");