@lensmcp/protocol-types 1.26.12 → 1.26.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +1 -0
- package/index.js +1 -1
- package/lib/accounts.d.ts +60 -0
- package/lib/accounts.js +1 -0
- package/lib/ai-cache-facts.js +1 -1
- package/lib/ai-cache-verdict.js +1 -1
- package/lib/ai-cache.js +3 -3
- package/lib/ai-call-groups.js +2 -2
- package/lib/ai-call-row.js +3 -3
- package/lib/ai-call.js +9 -9
- package/lib/ai-compare.js +3 -3
- package/lib/ai-context.js +6 -6
- package/lib/ai-origins.js +9 -9
- package/lib/ai-together.js +5 -5
- package/lib/bounded-clone.js +1 -1
- package/lib/bounded-map.js +1 -1
- package/lib/bounded-writer.js +1 -1
- package/lib/capture-demand.js +1 -1
- package/lib/dashboard-path.js +1 -1
- package/lib/docker-errors.js +1 -1
- package/lib/docker-jobs.js +1 -1
- package/lib/docker-report.js +2 -2
- package/lib/docker-runs.js +3 -3
- package/lib/error-cause.js +6 -6
- package/lib/error-dismissal.js +1 -1
- package/lib/error-verdict.js +3 -3
- package/lib/event-loop.js +1 -1
- package/lib/expected-failure.js +2 -2
- package/lib/finding-proof.js +1 -1
- package/lib/flood-guard.js +1 -1
- package/lib/goal-design.js +1 -1
- package/lib/host-agents.js +1 -1
- package/lib/lint-coverage.js +1 -1
- package/lib/log-query.js +1 -1
- package/lib/metrics-reset.js +1 -1
- package/lib/overseer-findings.js +1 -1
- package/lib/peers.d.ts +1 -1
- package/lib/peers.js +1 -1
- package/lib/perf-rules.js +1 -1
- package/lib/pod-memory.js +1 -1
- package/lib/producer-health.js +1 -1
- package/lib/remote-instances.js +1 -1
- package/lib/sessions.d.ts +17 -1
- package/lib/sources.js +1 -1
- package/lib/static-checks.js +1 -1
- package/lib/system-report.js +1 -1
- package/lib/team-design.d.ts +113 -3
- package/lib/team.js +1 -1
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ export * from './lib/peers.js';
|
|
|
53
53
|
export * from './lib/hosts.js';
|
|
54
54
|
export * from './lib/cluster-hosts.js';
|
|
55
55
|
export * from './lib/dashboard-updates.js';
|
|
56
|
+
export * from './lib/accounts.js';
|
|
56
57
|
export * from './lib/host-agents.js';
|
|
57
58
|
export * from './lib/remote-instances.js';
|
|
58
59
|
export * from './lib/team.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/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.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/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.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/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";
|
|
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/dashboard-lint.js";export*from"./lib/dashboard-typecheck.js";export*from"./lib/lint-coverage.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/host-agents.js";export*from"./lib/remote-instances.js";export*from"./lib/team.js";export*from"./lib/sessions.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/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";
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Accounts page (planning/accounts/00-plan.md): every sign-in agents run under, one row each — the client's own
|
|
3
|
+
* sign-ins included — with its nickname, status and quota. `GET /api/accounts` answers it as `rows`, beside the fields
|
|
4
|
+
* the older accounts card reads.
|
|
5
|
+
*/
|
|
6
|
+
export type DashAccountClient = 'claude' | 'codex';
|
|
7
|
+
/**
|
|
8
|
+
* One quota window as the row shows it. `usedPercent` is what the client said at `DashAccountRow.readAt`; `reset`: its
|
|
9
|
+
* reset time has passed since — the page reads it 0 %, not the old number.
|
|
10
|
+
*/
|
|
11
|
+
export interface DashAccountWindow {
|
|
12
|
+
/** `5-hour`, `weekly`, `weekly Fable`… as the client names it. */
|
|
13
|
+
name: string;
|
|
14
|
+
usedPercent: number;
|
|
15
|
+
resetsAt?: number;
|
|
16
|
+
minutes?: number;
|
|
17
|
+
reset?: true;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* - `ready`: signed in, not out of quota.
|
|
21
|
+
* - `out-of-quota`: a window is full or the client said its limit was reached — until `DashAccountRow.until`.
|
|
22
|
+
* - `sign-in-needed`: not signed in (never, or its sign-in ended).
|
|
23
|
+
* - `signing-in`: the client's sign-in runs now (the dashboard started it).
|
|
24
|
+
*/
|
|
25
|
+
export type DashAccountStatus = 'ready' | 'out-of-quota' | 'sign-in-needed' | 'signing-in';
|
|
26
|
+
export interface DashAccountRow {
|
|
27
|
+
/** `ac-…`, or `own:claude` / `own:codex` for the client's own sign-in (`~/.claude`, `~/.codex`). */
|
|
28
|
+
id: string;
|
|
29
|
+
/** What the terminal calls it: `lensmcp agent <nick>`. The own sign-ins are `claude` and `codex`. */
|
|
30
|
+
nick: string;
|
|
31
|
+
client: DashAccountClient;
|
|
32
|
+
/** Its name — «The client's own sign-in» for an own one. */
|
|
33
|
+
label: string;
|
|
34
|
+
own?: true;
|
|
35
|
+
/** The plan as the client names it (`Max 20×`, `Team`, `Business`…), when known. */
|
|
36
|
+
plan?: string;
|
|
37
|
+
/** New launches of its client use it (`lensmcp claude`, a goal with no account). */
|
|
38
|
+
default?: true;
|
|
39
|
+
/** Kept for the person's own sessions: no team agent runs on it; `run` starts the client on it by hand. */
|
|
40
|
+
standalone?: {
|
|
41
|
+
run: string;
|
|
42
|
+
};
|
|
43
|
+
status: DashAccountStatus;
|
|
44
|
+
/** Why, in a sentence — the client's words when it said why. */
|
|
45
|
+
statusWhy?: string;
|
|
46
|
+
/** `out-of-quota` until then. */
|
|
47
|
+
until?: number;
|
|
48
|
+
/** Its quota windows, shortest first; empty when never read. */
|
|
49
|
+
windows: DashAccountWindow[];
|
|
50
|
+
/** When `windows` were read, and how (`codex app-server`, `anthropic oauth usage`, `claude status line`). */
|
|
51
|
+
readAt?: number;
|
|
52
|
+
readHow?: string;
|
|
53
|
+
/** Why the newest read failed, when it did — `windows` are then the last good reading. */
|
|
54
|
+
readWhy?: string;
|
|
55
|
+
/** While its sign-in runs: when it started, and the link the client printed. */
|
|
56
|
+
signingIn?: {
|
|
57
|
+
startedAt: number;
|
|
58
|
+
link?: string;
|
|
59
|
+
};
|
|
60
|
+
}
|
package/lib/accounts.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";export{};
|
package/lib/ai-cache-facts.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var l=Object.defineProperty;var o=(e,
|
|
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");
|
package/lib/ai-cache-verdict.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ct=Object.defineProperty;var F=(e,o)=>Ct(e,"name",{value:o,configurable:!0});var Ut=Object.defineProperty,k=F((e,o)=>Ut(e,"name",{value:o,configurable:!0}),"w");import{AI_CACHE_TTL_MS as et,AI_GUIDANCE_SOURCES as kt,aiCacheMinTokens as It,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,"It"),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,I=et[n.ttl],a={row:i,start:$,...x!==void 0?{end:x}:{},ttlMs:I,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=It(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.":"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 z=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(z,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+z)&&tt(t.h,"read"));const at=w.filter((t,u)=>S>=0?u>S:t.t>m+z),vt=S>=0?w[S].t:m;let D=f>0?at.filter(t=>t.t<=vt+f+Math.max(z,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(U=>Math.abs(U.tokens-t.t)<=1)?.ttl??n.ttl,N=et[B],T=(l.get(t.h)??[]).filter(U=>U.i<s),W=T.filter(U=>$-h[U.i].start<=N);if(W.length){const U=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(U))??q(pt.filter(U)),mt=q(ft.filter(M=>!U(M)))??q(pt.filter(M=>!U(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 L=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,N)=>Math.max(B,N.t),0),u=Math.max(m,t),p=y.tokens-u;if(y.tokens>=Q&&p>z){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-z,N=c?B?dt-L:c.input-L:void 0;H.push({kind:"broken-prefix",tokens:p,estimate:!0,...N!==void 0?{usd:_(p*N/1e6),arithmetic:`${b(p)} \xD7 (${R(B?dt:c.input)} \u2212 ${R(L)})/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-L)/1e6),arithmetic:`${b(t.tokens)} \xD7 (${R(u)} \u2212 ${R(L)})/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-L)/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 I=[];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&&I.push(a)}for(const a of n)$.delete(a);if(n.size&&(s.readBy=n.size),$.size&&(s.maybeReadBy=$.size),x&&(s.open=!0),I.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 I){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,"Ut"),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 I=e.wrote.find(r=>r.status==="cold");I&&o.idleMs!==void 0&&n.push(`Cold: the same prefix (to the end of \xAB${G(I.s)}\xBB) was last used ${V(o.idleMs)} before \u2014 past its ${I.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 It=Object.defineProperty;var F=(e,s)=>It(e,"name",{value:s,configurable:!0});var Ut=Object.defineProperty,R=F((e,s)=>Ut(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 at,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,i)=>n.at-i.at||n.id.localeCompare(i.id));for(const[n,i]of dt(d,s,g))h.set(n,i)}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,"It"),k(ot,"factsOf");function dt(e,s,g){const h=[],u=new Map,d=new Map;e.forEach((n,i)=>{const o=n.cache,$=n.at,x=n.durationMs!==void 0?n.at+n.durationMs:void 0,U=at[o.ttl],r={row:n,start:$,...x!==void 0?{end:x}:{},ttlMs:U,wrote:[]};h.push(r);const a=o.marks??[],w=a.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 a){const l=d.get(t.h);l?l.push(i):d.set(t.h,[i])}},"remember"),it=k((t,l)=>{const p=u.get(t);p?p.push({i,how:l}):u.set(t,[{i,how:l}])},"hold"),Y=Et(n.provider,n.model);if(!v){if(!n.failed)for(const t of w)it(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.":"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 N=tt(o,A,Y,X);if(N){const t=et(r,h,d,i);if(t&&t.tokens>=Y&&c){const l=c.cacheRead??c.input,p=t.tokens*(c.input-l)/1e6;N.costs.push({kind:"no-cache",tokens:t.tokens,usd:S(p),arithmetic:`${M(t.tokens)} \xD7 (${_(c.input)} \u2212 ${_(l)})/M`,estimate:!0}),N.lostUsd=S(p),N.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&&(N.prewarm=!0),r.verdict=N,nt();return}const z=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:a);t&&Math.abs(t.t-m)<=Math.max(z,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+z)&&it(t.h,"read"));const ct=w.filter((t,l)=>j>=0?l>j:t.t>m+z),bt=j>=0?w[j].t:m;let D=f>0?ct.filter(t=>t.t<=bt+f+Math.max(z,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(I=>Math.abs(I.tokens-t.t)<=1)?.ttl??o.ttl,T=at[b],V=(u.get(t.h)??[]).filter(I=>I.i<i),W=V.filter(I=>$-h[I.i].start<=T);if(W.length){const I=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(I))??q(kt.filter(I)),$t=q(mt.filter(B=>!I(B)))??q(kt.filter(B=>!I(B))),At=gt??$t??q(W),yt=!gt&&!!$t,Ct=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:Ct})}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"});it(t.h,"wrote")});const y=et(r,h,d,i);nt();const L=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>z){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-z,T=c?b?lt-L:c.input-L: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 ${_(L)})/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-L)/1e6),arithmetic:`${M(t.tokens)} \xD7 (${_(l)} \u2212 ${_(L)})/M`}:{}})}const C=[];r.wrote.some(t=>t.status==="duplicate")&&C.push("duplicate-write"),Z&&C.push("broken-prefix"),r.wrote.some(t=>t.status==="cold")&&C.push("cold"),r.wrote.some(t=>t.status==="first")&&C.push("first-writer"),m>0&&C.push("read"),C.length||C.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-L)/1e6):void 0,Mt=C[0];r.verdict={kind:Mt,...C.length>1?{also:C.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 i=n.verdict;if(!n.wrote.length){i.said=st(n,i);continue}const o=new Set,$=new Set;let x=!1;const U=[];for(const r of n.wrote){const a=at[r.ttl],w=(u.get(r.h)??[]).filter(f=>h[f.i].start>n.start&&h[f.i].start-n.start<=a),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+a>g?x=!0:!A.length&&!m.length&&U.push(r)}for(const r of o)$.delete(r);if(o.size&&(i.readBy=o.size),$.size&&(i.maybeReadBy=$.size),x&&(i.open=!0),U.length){const r=n.row,a=r.model?s(r.model,r.tokens?.input??0):void 0;let w=i.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 Q=a?K(a,r.cache.writes,v.ttl):void 0;i.costs.push({kind:"write-nothing-read",tokens:c,estimate:v.estimate||c!==v.tokens,...a?{usd:S(c*(Q-a.input)/1e6),arithmetic:`${M(c)} \xD7 (${_(Q)} \u2212 ${_(a.input)})/M`}:{}})}a&&(i.lostUsd=S(i.costs.reduce((v,c)=>v+(c.usd??0),0)));const A=[i.kind,...i.also??[]],m=A.findIndex(v=>v!=="duplicate-write"&&v!=="broken-prefix"&&v!=="cold");A.splice(m<0?A.length:m,0,"write-nothing-read"),i.kind=A[0];const f=A.slice(1);f.length?i.also=f:delete i.also}i.said=st(n,i)}return new Map(h.map(n=>[n.row.id,n.verdict]))}F(dt,"$t"),R(dt,"Ut"),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,[,i])=>n+i,0);return h.reduce((n,[i,o])=>n+(e.writes[i]??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 i=0;i<u.length;i++){const o=g.get(u[i].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:i};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(i=>i.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,i=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, ${i}).`);const x=e.wrote.find(a=>a.status==="duplicate");if(x&&s.against){const a=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: ${a.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(a.gapMs)} after it.${w}`:x.against?.how==="read"?`Duplicate write: ${a.id} had read the same prefix (to the end of \xAB${H(x.s)}\xBB) ${G(a.gapMs)} before \u2014 the entry was there, and this call did not read it.`:`Duplicate write: ${a.id}${a.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(a.gapMs)} before${a.ended!==void 0&&a.ended<=e.start?` and had ended ${G(e.start-a.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 U=e.wrote.find(a=>a.status==="cold");U&&s.idleMs!==void 0&&o.push(`Cold: the same prefix (to the end of \xAB${H(U.s)}\xBB) was last used ${G(s.idleMs)} before \u2014 past its ${U.ttl} lifetime.`);const r=e.wrote.filter(a=>a.status==="first");return r.length&&o.push(`First writer of the prefix to the end of \xAB${r.map(a=>H(a.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(a=>a.arithmetic).map(a=>`${a.arithmetic}${a.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
|
|
2
|
-
`,e),p=l<0?h:l;let
|
|
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>
|
|
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");
|
package/lib/ai-call-groups.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var m=Object.defineProperty;var i=(
|
|
2
|
-
`).toLowerCase();return
|
|
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");
|
package/lib/ai-call-row.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).map(n=>n.trim()).find(Boolean)??"",
|
|
3
|
-
`).map(
|
|
1
|
+
"use strict";var B=Object.defineProperty;var m=(e,a)=>B(e,"name",{value:a,configurable:!0});var S=Object.defineProperty,d=m((e,a)=>S(e,"name",{value:a,configurable:!0}),"m"),T=Object.defineProperty,c=d((e,a)=>T(e,"name",{value:a,configurable:!0}),"d");import{aiCallOf as z}from"./ai-call.js";import{aiContextOf as E,aiSplitOf as K}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(a=>({at:a.at,tokens:a.tokens,...a.ttl?{ttl:a.ttl}:{},...a.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:a,...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,a){const t=a.toLowerCase(),s=new Map;for(const n of e){if(n.host.toLowerCase()!==t)continue;const r=n.model??"unknown";let o=s.get(r);o||(o={use:{model:r,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},s.set(r,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[...s.values()].map(({use:n,agents:r})=>({...n,agents:r.size})).sort((n,r)=>r.calls-n.calls||r.last-n.last)}m(aiModelUses,"aiModelUses"),d(aiModelUses,"aiModelUses"),c(aiModelUses,"aiModelUses");export function aiAgentUses(e,a){const t=a?.toLowerCase(),s=new Map;for(const n of e){if(t!==void 0&&n.host.toLowerCase()!==t)continue;let r=s.get(n.agent.key);r||(r={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},s.set(n.agent.key,r));const o=r.use;n.prewarm?o.prewarms=(o.prewarms??0)+1:(o.calls+=1,r.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&&r.models.set(n.model,(r.models.get(n.model)??0)+1),o.last=Math.max(o.last,n.at)}return[...s.values()].map(({use:n,runs:r,models:o})=>({...n,runs:r.size,models:[...o].sort((i,p)=>p[1]-i[1]).map(([i])=>i)})).sort((n,r)=>r.input-n.input||r.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 q=160,R="unknown service";export const aiKeyOf=c((e,a)=>`${e}:${a.normalize("NFKD").toLowerCase().replace(/[^a-z0-9:.]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"unnamed"}`,"aiKeyOf");export function humanName(e){const a=e.trim();if(/[A-Z]/.test(a)||/ /.test(a))return a;const t=a.replace(/[-_.]+/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):a}m(humanName,"humanName"),d(humanName,"humanName"),c(humanName,"humanName");const g=c((e,a=q)=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>a?`${t.slice(0,a-1)}\u2026`:t},"line");export function promptTitle(e){const a=e.split(`
|
|
2
|
+
`).map(n=>n.trim()).find(Boolean)??"",t=/^#{1,6}\s+(.+)$/.exec(a);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 s=/^you are (?:an? |the )?(.+?)(?:[.,;:!]|\s+(?:who|that|which|for|in|on|whose|with|and|following|using|working|based|at|to)\b|$)/i.exec(a);if(s){const n=s[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 r=n.join(" ");return r[0].toUpperCase()+r.slice(1)}}m(promptTitle,"promptTitle"),d(promptTitle,"promptTitle"),c(promptTitle,"promptTitle");export function promptOpening(e){const a=e.split(`
|
|
3
|
+
`).map(s=>s.trim()).find(Boolean);if(!a)return;const t=a.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 a=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 a.split(":").map(s=>s.split(".").filter(n=>!t.test(n)).join(".")).filter((s,n,r)=>s||n<r.length-1).join(":").slice(0,120)}m(actionName,"actionName"),d(actionName,"actionName"),c(actionName,"actionName");const h=c((e,a)=>{const t=e.request.headers.find(([s])=>s.toLowerCase()===a)?.[1];if(t===void 0||!a.startsWith("x-lensmcp-")||!t.includes("%"))return t;try{return decodeURIComponent(t)}catch{return t}},"header"),_=c(e=>e!==void 0&&/^\d{1,6}$/.test(e.trim())?Number(e.trim()):void 0,"intOf"),k=c((e,...a)=>{for(const t of a)if(e[t]?.trim())return e[t].trim()},"first");function b(e){const a={};for(const t of e.settings)if(t.name.startsWith("metadata.")){if(Object.keys(a).length>=MAX_META)break;a[t.name.slice(9)]=t.value.slice(0,200)}return a}m(b,"j"),d(b,"T"),c(b,"metaOf");function O(e,a,t){const s=c((f,w)=>({key:aiKeyOf("agent",f),name:humanName(f),from:w}),"named"),n=k(t,"agent","agent_name","agentName","assistant");if(n)return s(n,"metadata");const r=h(e,"x-lensmcp-agent");if(r?.trim())return s(r.trim(),"header");const o=a.system.map(f=>promptTitle(f.text)).find(Boolean);if(o)return s(o,"prompt");const i=a.answer.format?.name;if(i)return s(i,"schema");const p=[...a.tools,...a.answer.toolCalls].map(f=>f.server).find(Boolean);if(p)return s(p,"tools");const l=a.system.map(f=>promptOpening(f.text)).find(Boolean);return l?{key:aiKeyOf("agent",`prompt ${l.replace(/ …$/,"")}`),name:l,from:"prompt"}:s(`${e.service??R} ${a.api==="embeddings"?"embeddings":a.model??a.api}`,"service")}m(O,"U"),d(O,"B"),c(O,"agentOf");function $(e,a,t){const s=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 s(actionName(n),"metadata");const r=h(e,"x-lensmcp-action");if(r?.trim())return s(actionName(r.trim()),"header");if(a.answer.format?.name)return s(a.answer.format.name,"schema")}m($,"_"),d($,"E"),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,"N"),d(C,"x"),c(C,"turnLine");function y(e){const a=e.answer;return a.error?g(`error: ${a.error}`):a.refusal?g(`refused: ${a.refusal}`):a.toolCalls.length?g(a.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(a.text)}m(y,"v"),d(y,"_"),c(y,"saidLine");export function aiCallRow(e,a){const t=z(e);if(!t||!e.ai)return;const s=b(t),n=new Map(t.settings.map(u=>[u.name,u.value])),r=k(s,"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?{}:K(E(t,{sections:!1})),v=k(s,"thread","thread_id","threadId","conversation","conversation_id","conversationId","case","case_id","caseId"),x=h(e,"x-lensmcp-thread")?.trim(),I=k(s,"parent_run","parentRun","parent")??h(e,"x-lensmcp-parent")?.trim(),M=$(e,t,s),A=_(s.round),j=_(s.attempt),U=n.get("continues response"),N=[...t.turns].reverse().map(C).find(Boolean),L=t.answer.status==="failed"||!!t.answer.error||(e.status??0)>=400||!!e.error;return{id:e.id,at:e.startedAt,...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.status!==void 0?{status:e.status}:{},...L?{failed:!0}:{},service:e.service??R,...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,s),run:r?{key:`run:${r}`,from:"metadata"}:o?{key:`run:${o}`,from:"header"}:{key:`run:${e.id}`,from:"alone"},...v?{thread:{key:`thread:${v}`,name:v,from:"metadata"}}:x?{thread:{key:`thread:${x}`,name:x,from:"header"}}:{},...I?{parent:`run:${I}`}:{},...A!==void 0?{round:A}:{},...j!==void 0?{attempt:j}:{},...M?{action:M}:{},...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}:{},...U?{previousResponseId:U}:{},...Object.keys(s).length?{meta:s}:{},...t.gaps.some(u=>/kept to its first|cut/.test(u))?{cut:!0}:{},...a.content&&N?{asked:N}:{},...a.content&&y(t)?{said:y(t)}:{}}}m(aiCallRow,"aiCallRow"),d(aiCallRow,"aiCallRow"),c(aiCallRow,"aiCallRow");export function linkAiRuns(e){const a=[...e].sort((r,o)=>r.at-o.at||r.id.localeCompare(o.id)),t=new Map,s=new Map;for(const r of a){if(r.run.from==="alone"){const o=r.previousResponseId?t.get(r.previousResponseId):void 0,i=o?void 0:r.answers?.map(l=>s.get(l)).find(Boolean),p=o??i;if(p){const l=o?"chain":"tools";r.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})}}r.responseId&&t.set(r.responseId,r);for(const o of r.callIds??[])s.set(o,r)}const n=new Map;for(const r of a){const o=(n.get(r.run.key)??0)+1;n.set(r.run.key,o),r.step=o}return e}m(linkAiRuns,"linkAiRuns"),d(linkAiRuns,"linkAiRuns"),c(linkAiRuns,"linkAiRuns");export function mergedKey(e,a){let t=a;for(let s=0;s<8&&e.merge[t]&&e.merge[t]!==a;s++)t=e.merge[t];return t}m(mergedKey,"mergedKey"),d(mergedKey,"mergedKey"),c(mergedKey,"mergedKey");export function applyAiNames(e,a){if(!Object.keys(a.names).length&&!Object.keys(a.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 s=c(n=>{const r=mergedKey(a,n.key),o=a.names[r];if(o)return{key:r,name:o,from:"renamed"};if(r===n.key)return n;const i=t.get(r);return{key:r,name:i?.name??humanName(r.replace(/^[a-z]+:/,"")),from:i?.from??n.from}},"resolve");for(const n of e)n.agent=s(n.agent),n.action&&(n.action=s(n.action));return e}m(applyAiNames,"applyAiNames"),d(applyAiNames,"applyAiNames"),c(applyAiNames,"applyAiNames");export function aiNamesOf(e){const a=e&&typeof e=="object"?e:{},t=c(s=>{const n={};if(s&&typeof s=="object"&&!Array.isArray(s))for(const[r,o]of Object.entries(s))/^(agent|action):/.test(r)&&typeof o=="string"&&o.trim()&&(n[r]=o.trim().slice(0,120));return n},"pick");return{version:1,names:t(a.names),merge:t(a.merge)}}m(aiNamesOf,"aiNamesOf"),d(aiNamesOf,"aiNamesOf"),c(aiNamesOf,"aiNamesOf");
|