opencode-quota-gui 1.3.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -17
- package/dist/bin/opencode-quota-gui.js +0 -0
- package/dist/contracts/build-identity.js +1 -1
- package/dist/contracts/dashboard.d.ts +8 -1
- package/dist/contracts/dto-guards.js +2 -0
- package/dist/contracts/openai-quota.d.ts +3 -0
- package/dist/contracts/openai-quota.js +3 -0
- package/dist/data/modelsdev-temporal.min.json +57 -0
- package/dist/gui/config.d.ts +3 -3
- package/dist/gui/config.js +31 -2
- package/dist/gui/lifecycle.d.ts +5 -3
- package/dist/gui/lifecycle.js +3 -3
- package/dist/gui/primary-quota-windows.js +16 -14
- package/dist/gui/provider-cards.d.ts +10 -2
- package/dist/gui/provider-cards.js +51 -23
- package/dist/gui/quota-notification-detector.d.ts +4 -4
- package/dist/gui/quota-notification-detector.js +76 -42
- package/dist/gui/quota-notification-observer.d.ts +2 -3
- package/dist/gui/quota-notification-observer.js +68 -19
- package/dist/gui/rpc.d.ts +2 -0
- package/dist/gui/rpc.js +11 -3
- package/dist/gui/server.js +11 -2
- package/dist/gui/snapshot-service.d.ts +3 -1
- package/dist/gui/snapshot-service.js +126 -18
- package/dist/gui/sources.js +98 -56
- package/dist/gui-experimental.cjs +230 -225
- package/dist/lib/accounting-format.js +8 -0
- package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
- package/dist/lib/alibaba-coding-plan-cli.js +539 -0
- package/dist/lib/anthropic-auth.d.ts +2 -3
- package/dist/lib/anthropic-auth.js +2 -3
- package/dist/lib/anthropic.d.ts +48 -12
- package/dist/lib/anthropic.js +610 -275
- package/dist/lib/api-key-retry-after.d.ts +7 -0
- package/dist/lib/api-key-retry-after.js +62 -0
- package/dist/lib/atomic-json.d.ts +2 -0
- package/dist/lib/atomic-json.js +1 -0
- package/dist/lib/cache-observer-ingestion.d.ts +90 -0
- package/dist/lib/cache-observer-ingestion.js +981 -0
- package/dist/lib/cache-observer.d.ts +138 -0
- package/dist/lib/cache-observer.js +317 -0
- package/dist/lib/canonical-config-lock.d.ts +9 -0
- package/dist/lib/canonical-config-lock.js +36 -0
- package/dist/lib/chutes.js +62 -51
- package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
- package/dist/lib/claude-agent-transcript-ttl.js +154 -0
- package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
- package/dist/lib/claude-agent-ttl-tracker.js +152 -0
- package/dist/lib/cli-show.js +5 -3
- package/dist/lib/config-write-target.d.ts +1 -1
- package/dist/lib/config-write-target.js +5 -2
- package/dist/lib/config.d.ts +2 -1
- package/dist/lib/config.js +193 -2
- package/dist/lib/copilot.js +171 -86
- package/dist/lib/dashboard-web-policy.d.ts +4 -4
- package/dist/lib/dashboard-web-policy.js +2 -2
- package/dist/lib/deepseek.js +25 -13
- package/dist/lib/display-sanitize.js +1 -0
- package/dist/lib/entries.d.ts +23 -0
- package/dist/lib/entries.js +2 -0
- package/dist/lib/glm-coding-plan.js +98 -74
- package/dist/lib/google-agy.js +90 -12
- package/dist/lib/google-gemini-cli.js +84 -11
- package/dist/lib/http.d.ts +4 -0
- package/dist/lib/http.js +16 -2
- package/dist/lib/init-installer.js +5 -3
- package/dist/lib/kilo.js +37 -18
- package/dist/lib/kimi.js +35 -18
- package/dist/lib/mimo.d.ts +2 -0
- package/dist/lib/mimo.js +36 -0
- package/dist/lib/nanogpt.d.ts +1 -0
- package/dist/lib/nanogpt.js +26 -3
- package/dist/lib/ollama-cloud.d.ts +1 -1
- package/dist/lib/ollama-cloud.js +48 -35
- package/dist/lib/openai.js +84 -38
- package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
- package/dist/lib/opencode-auth-sqlite.js +2 -2
- package/dist/lib/opencode-config-editor.d.ts +1 -0
- package/dist/lib/opencode-config-editor.js +6 -1
- package/dist/lib/opencode-go.js +29 -2
- package/dist/lib/opencode-version-core.d.ts +23 -0
- package/dist/lib/opencode-version-core.js +49 -0
- package/dist/lib/opencode-version.d.ts +2 -22
- package/dist/lib/opencode-version.js +4 -48
- package/dist/lib/opencode-zen.d.ts +3 -0
- package/dist/lib/opencode-zen.js +71 -5
- package/dist/lib/provider-add.js +5 -2
- package/dist/lib/provider-registration.d.ts +19 -9
- package/dist/lib/provider-registration.js +17 -6
- package/dist/lib/quota-command-format.js +1 -1
- package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
- package/dist/lib/quota-exhaustion-projection.js +25 -0
- package/dist/lib/quota-providers-remote.d.ts +2 -1
- package/dist/lib/quota-providers-remote.js +59 -3
- package/dist/lib/quota-providers.d.ts +1 -1
- package/dist/lib/quota-providers.js +12 -35
- package/dist/lib/quota-render-data.d.ts +6 -0
- package/dist/lib/quota-render-data.js +43 -17
- package/dist/lib/quota-state-codec.js +17 -1
- package/dist/lib/quota-state.d.ts +7 -1
- package/dist/lib/quota-state.js +208 -34
- package/dist/lib/quota-stats.js +21 -0
- package/dist/lib/quota-status.js +3 -51
- package/dist/lib/scoped-update.d.ts +1 -1
- package/dist/lib/synthetic.js +65 -54
- package/dist/lib/types.d.ts +31 -1
- package/dist/lib/types.js +13 -0
- package/dist/lib/xai.js +48 -22
- package/dist/plugin.js +261 -13
- package/dist/provider-logos/NOTICE.md +1 -1
- package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
- package/dist/providers/alibaba-coding-plan.js +107 -104
- package/dist/providers/anthropic.d.ts +12 -3
- package/dist/providers/anthropic.js +71 -228
- package/dist/providers/cache-policies.d.ts +11 -4
- package/dist/providers/cache-policies.js +19 -13
- package/dist/providers/claude-agent.d.ts +19 -0
- package/dist/providers/claude-agent.js +196 -0
- package/dist/providers/copilot.js +2 -0
- package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
- package/dist/providers/google-account-format.js +1 -0
- package/dist/providers/google-agy.d.ts +6 -5
- package/dist/providers/google-agy.js +43 -15
- package/dist/providers/google-gemini-cli.js +1 -0
- package/dist/providers/kilo.js +1 -0
- package/dist/providers/kimi-code.js +2 -0
- package/dist/providers/mimo.js +1 -0
- package/dist/providers/nanogpt.js +1 -0
- package/dist/providers/opencode-go.js +3 -0
- package/dist/providers/opencode-zen.js +2 -0
- package/dist/providers/openrouter.js +1 -0
- package/dist/providers/quota-providers.js +16 -5
- package/dist/providers/registry.js +2 -0
- package/dist/providers/result-helpers.d.ts +2 -0
- package/dist/providers/result-helpers.js +2 -0
- package/dist/rpc.d.ts +121 -8
- package/dist/rpc.js +204 -12
- package/dist/ui/assets/{index-cDd9jUVY.css → index-BcueIm3Z.css} +1 -1
- package/dist/ui/assets/index-C6qRSoh8.js +10 -0
- package/dist/ui/assets/{popover-BGkgv9s0.js → popover-4bFSvRZ7.js} +1 -1
- package/dist/ui/assets/providers/claude-agent.svg +3 -0
- package/dist/ui/index.html +2 -2
- package/package.json +44 -45
- package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
- package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
- package/dist/ui/assets/index-DLHeXYff.js +0 -9
|
@@ -0,0 +1,981 @@
|
|
|
1
|
+
import { classifyCacheObserverState, createCacheObserverState, observeCacheInvocation, } from "./cache-observer.js";
|
|
2
|
+
/** Bound retained exact-session state even when a window observes many forks. */
|
|
3
|
+
export const CACHE_OBSERVER_MAX_SESSIONS = 128;
|
|
4
|
+
const CACHE_OBSERVER_MAX_STARTED_STEPS = 512;
|
|
5
|
+
const PRIMARY_STEP_BASIS = {
|
|
6
|
+
source: "opencode-v2.2.0-session-runner",
|
|
7
|
+
reference: "packages/core/src/session/runner/llm.ts#233-287",
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* A raw host step.ended is cache evidence only when its finish is successful. Projected
|
|
11
|
+
* DTOs carry no finish, so the ingestor re-reads them through the ungated update function
|
|
12
|
+
* after projection has already applied this same gate.
|
|
13
|
+
*/
|
|
14
|
+
function isUnsuccessfulStepEnded(event) {
|
|
15
|
+
return (isRecord(event) &&
|
|
16
|
+
event.type === "session.step.ended" &&
|
|
17
|
+
isRecord(event.data) &&
|
|
18
|
+
!isEligibleStepFinish(event.data.finish));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Raw host-event boundary: failed, length-truncated, content-filtered, errored, unknown,
|
|
22
|
+
* and unfinished steps leave the estimate unchanged.
|
|
23
|
+
*/
|
|
24
|
+
export function cacheObserverUpdateFromRawOpenCodeEvent(event) {
|
|
25
|
+
if (isUnsuccessfulStepEnded(event))
|
|
26
|
+
return undefined;
|
|
27
|
+
return cacheObserverUpdateFromOpenCodeEvent(event);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* OpenCode v2.2.0's runner calls the primary request path before its completed
|
|
31
|
+
* step event. Selected model identity is correlated from the exact Started
|
|
32
|
+
* event; session usage aggregates and mutable model catalogs are not invocation
|
|
33
|
+
* route or dispatch-TTL evidence.
|
|
34
|
+
*/
|
|
35
|
+
export function cacheObserverUpdateFromOpenCodeEvent(event) {
|
|
36
|
+
if (!isRecord(event) || typeof event.type !== "string" || !isRecord(event.data))
|
|
37
|
+
return undefined;
|
|
38
|
+
const sessionId = nonEmptyString(event.data.sessionID);
|
|
39
|
+
if (sessionId === undefined)
|
|
40
|
+
return undefined;
|
|
41
|
+
if (event.type === "session.created") {
|
|
42
|
+
const parentSessionId = nonEmptyString(event.data.parentID);
|
|
43
|
+
return parentSessionId === undefined
|
|
44
|
+
? undefined
|
|
45
|
+
: { kind: "created", sessionId, parentSessionId };
|
|
46
|
+
}
|
|
47
|
+
if (event.type === "session.deleted")
|
|
48
|
+
return { kind: "deleted", sessionId };
|
|
49
|
+
if (event.type === "session.forked") {
|
|
50
|
+
const parentSessionId = nonEmptyString(event.data.parentID);
|
|
51
|
+
return {
|
|
52
|
+
kind: "forked",
|
|
53
|
+
sessionId,
|
|
54
|
+
...(parentSessionId === undefined ? {} : { parentSessionId }),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
if (event.type === "session.compaction.ended")
|
|
58
|
+
return { kind: "compaction", sessionId };
|
|
59
|
+
if (event.type !== "session.step.ended" || !isRecord(event.data.tokens))
|
|
60
|
+
return undefined;
|
|
61
|
+
const messageId = nonEmptyString(event.data.assistantMessageID);
|
|
62
|
+
const order = eventOrder(event, messageId);
|
|
63
|
+
if (order === undefined)
|
|
64
|
+
return undefined;
|
|
65
|
+
const tokens = event.data.tokens;
|
|
66
|
+
const cache = isRecord(tokens.cache) ? tokens.cache : undefined;
|
|
67
|
+
// OpenCode v2.2.0 defines distinct fresh/cache-read/cache-write counters in
|
|
68
|
+
// https://github.com/anomalyco/opencode/blob/v2.2.0/packages/ai/src/schema/events.ts#L20-L55
|
|
69
|
+
// and maps them onto step tokens (normalizing missing values to zero) in
|
|
70
|
+
// https://github.com/anomalyco/opencode/blob/v2.2.0/packages/core/src/session/usage.ts#L8-L18.
|
|
71
|
+
// This supports host-reported telemetry only, not protocol or cache-validity inference.
|
|
72
|
+
const fresh = ownFiniteNumber(tokens, "input");
|
|
73
|
+
const read = cache === undefined ? undefined : ownFiniteNumber(cache, "read");
|
|
74
|
+
const write = cache === undefined ? undefined : ownFiniteNumber(cache, "write");
|
|
75
|
+
const counts = {
|
|
76
|
+
...(fresh === undefined ? {} : { fresh }),
|
|
77
|
+
...(read === undefined ? {} : { read }),
|
|
78
|
+
...(write === undefined ? {} : { write }),
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
kind: "invocation",
|
|
82
|
+
observation: {
|
|
83
|
+
sessionId,
|
|
84
|
+
order,
|
|
85
|
+
basis: PRIMARY_STEP_BASIS,
|
|
86
|
+
counts,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Strip an OpenCode event to the content-free DTO carried on Native's shared RPC stream.
|
|
92
|
+
* Started is published at first output (v2.2.0 `publish-llm-event.ts:121-135`). The actual
|
|
93
|
+
* request uses resolved `model.cache` (`model-request.ts:277-294`), while
|
|
94
|
+
* `SessionModelRequest.prepare` can rewrite the base URL and HTTP request through hooks
|
|
95
|
+
* (`model-request.ts:303-329`). The mutable model catalog therefore cannot establish
|
|
96
|
+
* invocation-bound TTL or effective-route evidence here.
|
|
97
|
+
*/
|
|
98
|
+
export function projectOpenCodeCacheObserverEvent(event) {
|
|
99
|
+
const started = projectStartedStep(event);
|
|
100
|
+
if (started !== undefined)
|
|
101
|
+
return started;
|
|
102
|
+
// Only successful steps reach the observer; a failed or incomplete step is dropped here.
|
|
103
|
+
if (isUnsuccessfulStepEnded(event))
|
|
104
|
+
return undefined;
|
|
105
|
+
const update = cacheObserverUpdateFromOpenCodeEvent(event);
|
|
106
|
+
if (update === undefined) {
|
|
107
|
+
return projectSessionStatusEvent(event) ?? projectSessionMetadataEvent(event);
|
|
108
|
+
}
|
|
109
|
+
if (update.kind === "invocation") {
|
|
110
|
+
const { completedAtMs, messageId } = update.observation.order;
|
|
111
|
+
const { fresh, read, write } = update.observation.counts;
|
|
112
|
+
const cache = {
|
|
113
|
+
...(read === undefined ? {} : { read }),
|
|
114
|
+
...(write === undefined ? {} : { write }),
|
|
115
|
+
};
|
|
116
|
+
return {
|
|
117
|
+
type: "session.step.ended",
|
|
118
|
+
created: completedAtMs,
|
|
119
|
+
data: {
|
|
120
|
+
sessionID: update.observation.sessionId,
|
|
121
|
+
assistantMessageID: messageId,
|
|
122
|
+
tokens: {
|
|
123
|
+
...(fresh === undefined ? {} : { input: fresh }),
|
|
124
|
+
...(read === undefined && write === undefined ? {} : { cache }),
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
if (update.kind === "created") {
|
|
130
|
+
return {
|
|
131
|
+
type: "session.created",
|
|
132
|
+
data: { sessionID: update.sessionId, parentID: update.parentSessionId },
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
if (update.kind === "forked") {
|
|
136
|
+
return {
|
|
137
|
+
type: "session.forked",
|
|
138
|
+
data: {
|
|
139
|
+
sessionID: update.sessionId,
|
|
140
|
+
...(update.parentSessionId === undefined ? {} : { parentID: update.parentSessionId }),
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const type = update.kind === "compaction" ? "session.compaction.ended" : "session.deleted";
|
|
145
|
+
return { type, data: { sessionID: update.sessionId } };
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Project the host's authoritative session execution state to the content-free
|
|
149
|
+
* status DTO. `session.status` busy/retry, `session.idle` and the execution
|
|
150
|
+
* lifecycle events are the confirmed busy sources; error details, messages and
|
|
151
|
+
* every other field are neither read nor copied.
|
|
152
|
+
*/
|
|
153
|
+
function projectSessionStatusEvent(event) {
|
|
154
|
+
if (!isRecord(event) || typeof event.type !== "string" || !isRecord(event.data))
|
|
155
|
+
return undefined;
|
|
156
|
+
if (typeof event.created !== "number" || !Number.isFinite(event.created) || event.created < 0) {
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
const sessionId = nonEmptyString(event.data.sessionID);
|
|
160
|
+
if (sessionId === undefined)
|
|
161
|
+
return undefined;
|
|
162
|
+
let state;
|
|
163
|
+
if (event.type === "session.status") {
|
|
164
|
+
const status = isRecord(event.data.status) ? event.data.status.type : undefined;
|
|
165
|
+
if (status === "busy" || status === "retry")
|
|
166
|
+
state = "busy";
|
|
167
|
+
else if (status === "idle")
|
|
168
|
+
state = "idle";
|
|
169
|
+
else
|
|
170
|
+
return undefined;
|
|
171
|
+
}
|
|
172
|
+
else if (event.type === "session.idle" || event.type === "session.execution.succeeded") {
|
|
173
|
+
state = "idle";
|
|
174
|
+
}
|
|
175
|
+
else if (event.type === "session.execution.started") {
|
|
176
|
+
state = "busy";
|
|
177
|
+
}
|
|
178
|
+
else if (event.type === "session.execution.failed" ||
|
|
179
|
+
event.type === "session.execution.interrupted") {
|
|
180
|
+
state = "idle";
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
return { type: "session.status", created: event.created, data: { sessionID: sessionId, state } };
|
|
186
|
+
}
|
|
187
|
+
const MAX_RELAYED_TITLE_CODEUNITS = 200;
|
|
188
|
+
const MAX_RELAYED_ID_CODEUNITS = 256;
|
|
189
|
+
/**
|
|
190
|
+
* A relayed session title: control characters removed, whitespace collapsed,
|
|
191
|
+
* bounded to what the event guard accepts. An empty result omits the field.
|
|
192
|
+
*/
|
|
193
|
+
function boundedRelayedTitle(value) {
|
|
194
|
+
if (typeof value !== "string")
|
|
195
|
+
return undefined;
|
|
196
|
+
const clean = Array.from(value.normalize("NFC"), (character) => {
|
|
197
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
198
|
+
if (codePoint < 0x20 || codePoint === 0x7f)
|
|
199
|
+
return " ";
|
|
200
|
+
return character;
|
|
201
|
+
})
|
|
202
|
+
.join("")
|
|
203
|
+
.replace(/\s+/gu, " ")
|
|
204
|
+
.trim();
|
|
205
|
+
if (!clean)
|
|
206
|
+
return undefined;
|
|
207
|
+
return clean.length > MAX_RELAYED_TITLE_CODEUNITS
|
|
208
|
+
? clean.slice(0, MAX_RELAYED_TITLE_CODEUNITS)
|
|
209
|
+
: clean;
|
|
210
|
+
}
|
|
211
|
+
function boundedRelayedId(value) {
|
|
212
|
+
if (typeof value !== "string")
|
|
213
|
+
return undefined;
|
|
214
|
+
const clean = value.trim();
|
|
215
|
+
if (!clean || clean.length > MAX_RELAYED_ID_CODEUNITS)
|
|
216
|
+
return undefined;
|
|
217
|
+
for (const character of clean) {
|
|
218
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
219
|
+
if (codePoint < 0x20 || codePoint === 0x7f)
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
return clean;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Project the host's session-identity updates to the content-free metadata
|
|
226
|
+
* DTO: renames carry the new title, model/agent selections their reference.
|
|
227
|
+
* `previous` values and every other field are neither read nor copied.
|
|
228
|
+
*/
|
|
229
|
+
function projectSessionMetadataEvent(event) {
|
|
230
|
+
if (!isRecord(event) || typeof event.type !== "string" || !isRecord(event.data))
|
|
231
|
+
return undefined;
|
|
232
|
+
if (typeof event.created !== "number" || !Number.isFinite(event.created) || event.created < 0) {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
const sessionId = nonEmptyString(event.data.sessionID);
|
|
236
|
+
if (sessionId === undefined || sessionId.length > MAX_RELAYED_ID_CODEUNITS)
|
|
237
|
+
return undefined;
|
|
238
|
+
if (event.type === "session.renamed") {
|
|
239
|
+
const title = boundedRelayedTitle(event.data.title);
|
|
240
|
+
return title === undefined
|
|
241
|
+
? undefined
|
|
242
|
+
: { type: "session.metadata", created: event.created, data: { sessionID: sessionId, title } };
|
|
243
|
+
}
|
|
244
|
+
if (event.type === "session.agent.selected") {
|
|
245
|
+
const agent = boundedRelayedId(event.data.agent);
|
|
246
|
+
return agent === undefined
|
|
247
|
+
? undefined
|
|
248
|
+
: { type: "session.metadata", created: event.created, data: { sessionID: sessionId, agent } };
|
|
249
|
+
}
|
|
250
|
+
if (event.type === "session.model.selected") {
|
|
251
|
+
const model = isRecord(event.data.model) ? event.data.model : undefined;
|
|
252
|
+
if (model === undefined)
|
|
253
|
+
return undefined;
|
|
254
|
+
const providerId = boundedRelayedId(model.providerID);
|
|
255
|
+
const modelId = boundedRelayedId(model.id);
|
|
256
|
+
if (providerId === undefined || modelId === undefined)
|
|
257
|
+
return undefined;
|
|
258
|
+
const variant = boundedRelayedId(model.variant);
|
|
259
|
+
return {
|
|
260
|
+
type: "session.metadata",
|
|
261
|
+
created: event.created,
|
|
262
|
+
data: {
|
|
263
|
+
sessionID: sessionId,
|
|
264
|
+
model: {
|
|
265
|
+
providerID: providerId,
|
|
266
|
+
id: modelId,
|
|
267
|
+
...(variant === undefined ? {} : { variant }),
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
return undefined;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Immediately project a message.list item to the small cache-observer domain DTO.
|
|
276
|
+
* Assistant content, metadata, tools, cost, and all unrelated message fields
|
|
277
|
+
* are intentionally neither read nor copied.
|
|
278
|
+
*/
|
|
279
|
+
export function projectOpenCodeCacheObserverHistoryMessage(sessionId, message) {
|
|
280
|
+
if (!sessionId.trim() || !isRecord(message) || message.type !== "assistant")
|
|
281
|
+
return undefined;
|
|
282
|
+
// An unfinished, errored, or incomplete assistant message is not a successful request.
|
|
283
|
+
if (!isEligibleStepFinish(message.finish) || message.error !== undefined)
|
|
284
|
+
return undefined;
|
|
285
|
+
const messageId = nonEmptyString(message.id);
|
|
286
|
+
const model = isRecord(message.model) ? message.model : undefined;
|
|
287
|
+
const providerId = model === undefined ? undefined : nonEmptyString(model.providerID);
|
|
288
|
+
const modelId = model === undefined ? undefined : nonEmptyString(model.id);
|
|
289
|
+
const time = isRecord(message.time) ? message.time : undefined;
|
|
290
|
+
const completedAtMs = time === undefined ? undefined : ownNonNegativeFiniteNumber(time, "completed");
|
|
291
|
+
if (messageId === undefined ||
|
|
292
|
+
providerId === undefined ||
|
|
293
|
+
modelId === undefined ||
|
|
294
|
+
completedAtMs === undefined) {
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
const variantId = normalizedVariantId(model?.variant);
|
|
298
|
+
const tokenUsage = isRecord(message.tokens) ? message.tokens : undefined;
|
|
299
|
+
const cache = tokenUsage !== undefined && isRecord(tokenUsage.cache) ? tokenUsage.cache : undefined;
|
|
300
|
+
const fresh = tokenUsage === undefined ? undefined : ownNonNegativeFiniteNumber(tokenUsage, "input");
|
|
301
|
+
const read = cache === undefined ? undefined : ownNonNegativeFiniteNumber(cache, "read");
|
|
302
|
+
const write = cache === undefined ? undefined : ownNonNegativeFiniteNumber(cache, "write");
|
|
303
|
+
// The public schema's `time.created` is copied from the runner's
|
|
304
|
+
// step-started timestamp (upstream v2.2.1 message-updater.ts:230,254): a
|
|
305
|
+
// host request-dispatch-side time, not exact provider acceptance. Keep it
|
|
306
|
+
// only as a narrow valid timestamp: finite, non-negative, and not after
|
|
307
|
+
// completion. Completion is never used as a request start.
|
|
308
|
+
const rawDispatchAtMs = time === undefined ? undefined : ownNonNegativeFiniteNumber(time, "created");
|
|
309
|
+
const dispatchAtMs = rawDispatchAtMs === undefined || rawDispatchAtMs > completedAtMs ? undefined : rawDispatchAtMs;
|
|
310
|
+
return {
|
|
311
|
+
sessionId,
|
|
312
|
+
messageId,
|
|
313
|
+
completedAtMs,
|
|
314
|
+
...(dispatchAtMs === undefined ? {} : { dispatchAtMs }),
|
|
315
|
+
route: {
|
|
316
|
+
providerId,
|
|
317
|
+
modelId,
|
|
318
|
+
...(variantId === undefined ? {} : { variantId }),
|
|
319
|
+
basis: {
|
|
320
|
+
source: "OpenCode message.list assistant model identity",
|
|
321
|
+
reference: messageId,
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
counts: {
|
|
325
|
+
...(fresh === undefined ? {} : { fresh }),
|
|
326
|
+
...(read === undefined ? {} : { read }),
|
|
327
|
+
...(write === undefined ? {} : { write }),
|
|
328
|
+
},
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
/** True only for a completed compaction boundary in the public message-list DTO. */
|
|
332
|
+
export function isCompletedCacheObserverHistoryCompaction(message) {
|
|
333
|
+
return isRecord(message) && message.type === "compaction" && message.status === "completed";
|
|
334
|
+
}
|
|
335
|
+
export function createCacheObserverIngestor(options = {}) {
|
|
336
|
+
const now = options.now ?? Date.now;
|
|
337
|
+
const states = new Map();
|
|
338
|
+
const listeners = new Map();
|
|
339
|
+
const startedSteps = new Map();
|
|
340
|
+
const pendingEndedSteps = new Map();
|
|
341
|
+
const liveStepKeys = new Map();
|
|
342
|
+
const latestLiveRoutes = new Map();
|
|
343
|
+
const latestLiveCompletedAt = new Map();
|
|
344
|
+
const latestLiveCompletion = new Map();
|
|
345
|
+
const latestUsableLiveCompletion = new Map();
|
|
346
|
+
const recheckTimers = new Map();
|
|
347
|
+
let disposed = false;
|
|
348
|
+
function query(sessionId) {
|
|
349
|
+
if (!sessionId.trim())
|
|
350
|
+
return undefined;
|
|
351
|
+
const state = states.get(sessionId);
|
|
352
|
+
if (state !== undefined) {
|
|
353
|
+
states.delete(sessionId);
|
|
354
|
+
states.set(sessionId, state);
|
|
355
|
+
}
|
|
356
|
+
if (state === undefined)
|
|
357
|
+
return undefined;
|
|
358
|
+
return classifyCacheObserverState(state, now());
|
|
359
|
+
}
|
|
360
|
+
function route(sessionId) {
|
|
361
|
+
if (!sessionId.trim())
|
|
362
|
+
return undefined;
|
|
363
|
+
const observed = states.get(sessionId)?.invocations.at(-1)?.route;
|
|
364
|
+
if (observed === undefined)
|
|
365
|
+
return undefined;
|
|
366
|
+
return {
|
|
367
|
+
...observed,
|
|
368
|
+
basis: { ...observed.basis },
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function notify(sessionId) {
|
|
372
|
+
const classification = query(sessionId);
|
|
373
|
+
const sessionListeners = listeners.get(sessionId);
|
|
374
|
+
if (sessionListeners === undefined || sessionListeners.size === 0) {
|
|
375
|
+
clearRecheckTimer(sessionId);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
for (const listener of Array.from(sessionListeners)) {
|
|
379
|
+
try {
|
|
380
|
+
listener(classification);
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
// A consumer failure must not interrupt host-event ingestion.
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
scheduleRecheck(sessionId, classification);
|
|
387
|
+
}
|
|
388
|
+
function clearRecheckTimer(sessionId) {
|
|
389
|
+
const timer = recheckTimers.get(sessionId);
|
|
390
|
+
if (timer !== undefined)
|
|
391
|
+
clearTimeout(timer);
|
|
392
|
+
recheckTimers.delete(sessionId);
|
|
393
|
+
}
|
|
394
|
+
function scheduleRecheck(sessionId, classification) {
|
|
395
|
+
clearRecheckTimer(sessionId);
|
|
396
|
+
if ((listeners.get(sessionId)?.size ?? 0) === 0 || classification?.recheckAtMs === undefined)
|
|
397
|
+
return;
|
|
398
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
399
|
+
const delayMs = Math.min(Math.max(1, classification.recheckAtMs - now()), MAX_TIMEOUT_MS);
|
|
400
|
+
const scheduledAtMs = classification.recheckAtMs;
|
|
401
|
+
const timer = setTimeout(() => {
|
|
402
|
+
recheckTimers.delete(sessionId);
|
|
403
|
+
if (disposed || (listeners.get(sessionId)?.size ?? 0) === 0)
|
|
404
|
+
return;
|
|
405
|
+
const updated = query(sessionId);
|
|
406
|
+
if (scheduledAtMs > now()) {
|
|
407
|
+
scheduleRecheck(sessionId, updated);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
for (const listener of Array.from(listeners.get(sessionId) ?? [])) {
|
|
411
|
+
try {
|
|
412
|
+
listener(updated);
|
|
413
|
+
}
|
|
414
|
+
catch {
|
|
415
|
+
// A consumer failure cannot interrupt time-driven classification.
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
scheduleRecheck(sessionId, updated);
|
|
419
|
+
}, delayMs);
|
|
420
|
+
recheckTimers.set(sessionId, timer);
|
|
421
|
+
}
|
|
422
|
+
function clearStartedSteps(sessionId) {
|
|
423
|
+
for (const [key, started] of startedSteps) {
|
|
424
|
+
if (started.sessionId === sessionId)
|
|
425
|
+
startedSteps.delete(key);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
function clearPendingEndedSteps(sessionId) {
|
|
429
|
+
for (const [key, ended] of pendingEndedSteps) {
|
|
430
|
+
if (ended.sessionId === sessionId)
|
|
431
|
+
pendingEndedSteps.delete(key);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
function clearPendingSteps(sessionId) {
|
|
435
|
+
clearStartedSteps(sessionId);
|
|
436
|
+
clearPendingEndedSteps(sessionId);
|
|
437
|
+
}
|
|
438
|
+
function markObservationGap(sessionId) {
|
|
439
|
+
if (disposed || !sessionId.trim())
|
|
440
|
+
return;
|
|
441
|
+
// Only the in-flight correlation fences are dropped. The retained estimate and
|
|
442
|
+
// cache share are the last observed evidence, so they persist through the gap.
|
|
443
|
+
clearPendingSteps(sessionId);
|
|
444
|
+
clearLiveContext(sessionId);
|
|
445
|
+
}
|
|
446
|
+
function ingest(event) {
|
|
447
|
+
ingestEvent(event, "live");
|
|
448
|
+
}
|
|
449
|
+
function captureConfiguration(sessionId, messageId) {
|
|
450
|
+
const key = startedStepKey(sessionId, messageId);
|
|
451
|
+
const started = startedSteps.get(key);
|
|
452
|
+
return (ttl) => {
|
|
453
|
+
if (started !== undefined &&
|
|
454
|
+
startedSteps.get(key) === started &&
|
|
455
|
+
(ttl === 300_000 || ttl === 3_600_000))
|
|
456
|
+
started.configuredTtlMs = ttl;
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
function ingestEvent(event, source) {
|
|
460
|
+
if (disposed)
|
|
461
|
+
return;
|
|
462
|
+
if (isRecord(event) && event.type === "session.cache.ttl") {
|
|
463
|
+
if (source === "live")
|
|
464
|
+
applyObservedTtl(event.data);
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const started = startedStepFromDto(event);
|
|
468
|
+
if (started !== undefined) {
|
|
469
|
+
const key = startedStepKey(started.sessionId, started.messageId);
|
|
470
|
+
if (source === "live") {
|
|
471
|
+
rememberLiveStep(key, started.sessionId);
|
|
472
|
+
latestLiveRoutes.delete(started.sessionId);
|
|
473
|
+
latestLiveRoutes.set(started.sessionId, started.route);
|
|
474
|
+
while (latestLiveRoutes.size > CACHE_OBSERVER_MAX_SESSIONS) {
|
|
475
|
+
const oldestSessionId = latestLiveRoutes.keys().next().value;
|
|
476
|
+
if (oldestSessionId === undefined)
|
|
477
|
+
break;
|
|
478
|
+
latestLiveRoutes.delete(oldestSessionId);
|
|
479
|
+
latestLiveCompletedAt.delete(oldestSessionId);
|
|
480
|
+
latestLiveCompletion.delete(oldestSessionId);
|
|
481
|
+
latestUsableLiveCompletion.delete(oldestSessionId);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
startedSteps.delete(key);
|
|
485
|
+
startedSteps.set(key, started);
|
|
486
|
+
while (startedSteps.size > CACHE_OBSERVER_MAX_STARTED_STEPS) {
|
|
487
|
+
const oldestKey = startedSteps.keys().next().value;
|
|
488
|
+
if (oldestKey === undefined)
|
|
489
|
+
break;
|
|
490
|
+
startedSteps.delete(oldestKey);
|
|
491
|
+
}
|
|
492
|
+
const pendingEnd = pendingEndedSteps.get(key);
|
|
493
|
+
if (pendingEnd !== undefined) {
|
|
494
|
+
pendingEndedSteps.delete(key);
|
|
495
|
+
// The Ended may have arrived first on the shared stream. Re-ingest only
|
|
496
|
+
// its content-free projected DTO once exact session/message correlation
|
|
497
|
+
// is now available.
|
|
498
|
+
ingestEvent(pendingEnd.event, source);
|
|
499
|
+
}
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
const update = cacheObserverUpdateFromOpenCodeEvent(event);
|
|
503
|
+
if (update === undefined)
|
|
504
|
+
return;
|
|
505
|
+
if (update.kind === "created") {
|
|
506
|
+
clearPendingSteps(update.sessionId);
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
if (update.kind !== "invocation") {
|
|
510
|
+
clearPendingSteps(update.sessionId);
|
|
511
|
+
clearRecheckTimer(update.sessionId);
|
|
512
|
+
if (source === "live") {
|
|
513
|
+
clearLiveContext(update.sessionId);
|
|
514
|
+
}
|
|
515
|
+
if (states.delete(update.sessionId))
|
|
516
|
+
notify(update.sessionId);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const sessionId = update.observation.sessionId;
|
|
520
|
+
const startedKey = startedStepKey(sessionId, update.observation.order.messageId);
|
|
521
|
+
if (source === "live") {
|
|
522
|
+
rememberLiveStep(startedKey, sessionId);
|
|
523
|
+
const previousCompletedAt = latestLiveCompletedAt.get(sessionId);
|
|
524
|
+
latestLiveCompletedAt.set(sessionId, Math.max(previousCompletedAt ?? 0, update.observation.order.completedAtMs));
|
|
525
|
+
rememberLiveCompletion(sessionId, {
|
|
526
|
+
messageId: update.observation.order.messageId,
|
|
527
|
+
completedAtMs: update.observation.order.completedAtMs,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
const startedEvidence = startedSteps.get(startedKey);
|
|
531
|
+
startedSteps.delete(startedKey);
|
|
532
|
+
const endedEvent = {
|
|
533
|
+
type: "session.step.ended",
|
|
534
|
+
created: update.observation.order.completedAtMs,
|
|
535
|
+
data: {
|
|
536
|
+
sessionID: sessionId,
|
|
537
|
+
assistantMessageID: update.observation.order.messageId,
|
|
538
|
+
tokens: {
|
|
539
|
+
...(update.observation.counts.fresh === undefined
|
|
540
|
+
? {}
|
|
541
|
+
: { input: update.observation.counts.fresh }),
|
|
542
|
+
...(update.observation.counts.read === undefined &&
|
|
543
|
+
update.observation.counts.write === undefined
|
|
544
|
+
? {}
|
|
545
|
+
: {
|
|
546
|
+
cache: {
|
|
547
|
+
...(update.observation.counts.read === undefined
|
|
548
|
+
? {}
|
|
549
|
+
: { read: update.observation.counts.read }),
|
|
550
|
+
...(update.observation.counts.write === undefined
|
|
551
|
+
? {}
|
|
552
|
+
: { write: update.observation.counts.write }),
|
|
553
|
+
},
|
|
554
|
+
}),
|
|
555
|
+
},
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
if (startedEvidence === undefined) {
|
|
559
|
+
pendingEndedSteps.delete(startedKey);
|
|
560
|
+
pendingEndedSteps.set(startedKey, { sessionId, event: endedEvent });
|
|
561
|
+
while (pendingEndedSteps.size > CACHE_OBSERVER_MAX_STARTED_STEPS) {
|
|
562
|
+
const oldestKey = pendingEndedSteps.keys().next().value;
|
|
563
|
+
if (oldestKey === undefined)
|
|
564
|
+
break;
|
|
565
|
+
pendingEndedSteps.delete(oldestKey);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
pendingEndedSteps.delete(startedKey);
|
|
570
|
+
}
|
|
571
|
+
let state = states.get(sessionId);
|
|
572
|
+
if (state?.scope.route !== undefined &&
|
|
573
|
+
startedEvidence?.route !== undefined &&
|
|
574
|
+
!sameRouteProvenance(state.scope.route, startedEvidence.route) &&
|
|
575
|
+
update.observation.order.completedAtMs >= (state.invocations.at(-1)?.order.completedAtMs ?? 0)) {
|
|
576
|
+
state = createCacheObserverState({ sessionId, route: startedEvidence.route });
|
|
577
|
+
}
|
|
578
|
+
if (state === undefined) {
|
|
579
|
+
state = createCacheObserverState({
|
|
580
|
+
sessionId,
|
|
581
|
+
...(startedEvidence?.route === undefined ? {} : { route: startedEvidence.route }),
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
else if (state.scope.route === undefined && startedEvidence?.route !== undefined) {
|
|
585
|
+
state = { ...state, scope: { ...state.scope, route: startedEvidence.route } };
|
|
586
|
+
}
|
|
587
|
+
const previousInvocation = state.invocations.find((entry) => entry.order.messageId === update.observation.order.messageId);
|
|
588
|
+
if (source === "live" &&
|
|
589
|
+
startedEvidence !== undefined &&
|
|
590
|
+
hasObservedCounts(update.observation.counts)) {
|
|
591
|
+
rememberUsableLiveCompletion(sessionId, {
|
|
592
|
+
messageId: update.observation.order.messageId,
|
|
593
|
+
completedAtMs: update.observation.order.completedAtMs,
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
const previousHasCounts = previousInvocation !== undefined &&
|
|
597
|
+
(previousInvocation.counts.fresh !== undefined ||
|
|
598
|
+
previousInvocation.counts.read !== undefined ||
|
|
599
|
+
previousInvocation.counts.write !== undefined);
|
|
600
|
+
if (previousInvocation !== undefined && (startedEvidence === undefined || previousHasCounts))
|
|
601
|
+
return;
|
|
602
|
+
// Ended counters are useful only after an exact Started correlation. Keep
|
|
603
|
+
// the event receipt, but do not treat its untrusted zero-normalized values
|
|
604
|
+
// as a real cache-read denominator.
|
|
605
|
+
const observation = startedEvidence === undefined ? { ...update.observation, counts: {} } : update.observation;
|
|
606
|
+
const matchedRoute = startedEvidence?.route !== undefined &&
|
|
607
|
+
sameRouteProvenance(state.scope.route, startedEvidence.route)
|
|
608
|
+
? startedEvidence.route
|
|
609
|
+
: undefined;
|
|
610
|
+
state = observeCacheInvocation(state, {
|
|
611
|
+
...observation,
|
|
612
|
+
...(startedEvidence?.dispatchAtMs === undefined
|
|
613
|
+
? {}
|
|
614
|
+
: { dispatchAtMs: startedEvidence.dispatchAtMs }),
|
|
615
|
+
...(matchedRoute === undefined ? {} : { route: matchedRoute }),
|
|
616
|
+
...(startedEvidence?.configuredTtlMs === undefined
|
|
617
|
+
? {}
|
|
618
|
+
: { configuredTtlMs: startedEvidence.configuredTtlMs }),
|
|
619
|
+
...(startedEvidence?.connectionMethod === undefined
|
|
620
|
+
? {}
|
|
621
|
+
: { connectionMethod: startedEvidence.connectionMethod }),
|
|
622
|
+
});
|
|
623
|
+
if (!states.has(sessionId) && states.size >= CACHE_OBSERVER_MAX_SESSIONS) {
|
|
624
|
+
const oldestSessionId = states.keys().next().value;
|
|
625
|
+
if (oldestSessionId !== undefined) {
|
|
626
|
+
states.delete(oldestSessionId);
|
|
627
|
+
clearRecheckTimer(oldestSessionId);
|
|
628
|
+
notify(oldestSessionId);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
states.delete(sessionId);
|
|
632
|
+
states.set(sessionId, state);
|
|
633
|
+
notify(sessionId);
|
|
634
|
+
}
|
|
635
|
+
/** Applies only to the newest retained, claude-agent-routed invocation with this exact message id. */
|
|
636
|
+
function applyObservedTtl(data) {
|
|
637
|
+
if (!isRecord(data) || data.ttlMs !== 3_600_000)
|
|
638
|
+
return;
|
|
639
|
+
const sessionId = nonEmptyString(data.sessionID);
|
|
640
|
+
const messageId = nonEmptyString(data.assistantMessageID);
|
|
641
|
+
const state = sessionId === undefined ? undefined : states.get(sessionId);
|
|
642
|
+
const latest = state?.invocations.at(-1);
|
|
643
|
+
if (sessionId === undefined ||
|
|
644
|
+
state === undefined ||
|
|
645
|
+
latest === undefined ||
|
|
646
|
+
latest.order.messageId !== messageId ||
|
|
647
|
+
latest.route?.providerId !== "claude-agent" ||
|
|
648
|
+
latest.observedTtlMs !== undefined) {
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
states.set(sessionId, {
|
|
652
|
+
...state,
|
|
653
|
+
invocations: [...state.invocations.slice(0, -1), { ...latest, observedTtlMs: 3_600_000 }],
|
|
654
|
+
});
|
|
655
|
+
notify(sessionId);
|
|
656
|
+
}
|
|
657
|
+
function rememberLiveStep(key, sessionId) {
|
|
658
|
+
liveStepKeys.delete(key);
|
|
659
|
+
liveStepKeys.set(key, sessionId);
|
|
660
|
+
while (liveStepKeys.size > CACHE_OBSERVER_MAX_STARTED_STEPS) {
|
|
661
|
+
const oldestKey = liveStepKeys.keys().next().value;
|
|
662
|
+
if (oldestKey === undefined)
|
|
663
|
+
break;
|
|
664
|
+
liveStepKeys.delete(oldestKey);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
function clearLiveContext(sessionId) {
|
|
668
|
+
for (const [key, ownerSessionId] of liveStepKeys) {
|
|
669
|
+
if (ownerSessionId === sessionId)
|
|
670
|
+
liveStepKeys.delete(key);
|
|
671
|
+
}
|
|
672
|
+
latestLiveRoutes.delete(sessionId);
|
|
673
|
+
latestLiveCompletedAt.delete(sessionId);
|
|
674
|
+
latestLiveCompletion.delete(sessionId);
|
|
675
|
+
latestUsableLiveCompletion.delete(sessionId);
|
|
676
|
+
}
|
|
677
|
+
function rememberLiveCompletion(sessionId, completion) {
|
|
678
|
+
rememberNewestCompletion(latestLiveCompletion, sessionId, completion);
|
|
679
|
+
}
|
|
680
|
+
function rememberUsableLiveCompletion(sessionId, completion) {
|
|
681
|
+
rememberNewestCompletion(latestUsableLiveCompletion, sessionId, completion);
|
|
682
|
+
}
|
|
683
|
+
function rememberNewestCompletion(completions, sessionId, completion) {
|
|
684
|
+
const previous = completions.get(sessionId);
|
|
685
|
+
if (previous !== undefined && compareLiveCompletion(completion, previous) < 0)
|
|
686
|
+
return;
|
|
687
|
+
completions.delete(sessionId);
|
|
688
|
+
completions.set(sessionId, completion);
|
|
689
|
+
while (completions.size > CACHE_OBSERVER_MAX_SESSIONS) {
|
|
690
|
+
const oldestSessionId = completions.keys().next().value;
|
|
691
|
+
if (oldestSessionId === undefined)
|
|
692
|
+
break;
|
|
693
|
+
completions.delete(oldestSessionId);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function hasUsableLiveObservation(sessionId) {
|
|
697
|
+
const latest = latestLiveCompletion.get(sessionId);
|
|
698
|
+
const usable = latestUsableLiveCompletion.get(sessionId);
|
|
699
|
+
return (latest !== undefined &&
|
|
700
|
+
usable !== undefined &&
|
|
701
|
+
latest.messageId === usable.messageId &&
|
|
702
|
+
latest.completedAtMs === usable.completedAtMs);
|
|
703
|
+
}
|
|
704
|
+
function ingestHistory(invocations) {
|
|
705
|
+
if (disposed)
|
|
706
|
+
return;
|
|
707
|
+
for (const invocation of invocations) {
|
|
708
|
+
const key = startedStepKey(invocation.sessionId, invocation.messageId);
|
|
709
|
+
const pendingLiveEnd = pendingEndedSteps.get(key);
|
|
710
|
+
const recoveringUnmatchedLiveEnd = pendingLiveEnd !== undefined && !startedSteps.has(key);
|
|
711
|
+
if (liveStepKeys.has(key) && !recoveringUnmatchedLiveEnd)
|
|
712
|
+
continue;
|
|
713
|
+
const liveCompletedAt = latestLiveCompletedAt.get(invocation.sessionId);
|
|
714
|
+
if (!recoveringUnmatchedLiveEnd &&
|
|
715
|
+
liveCompletedAt !== undefined &&
|
|
716
|
+
invocation.completedAtMs >= liveCompletedAt) {
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
const liveRoute = liveCompletedAt === undefined ? undefined : states.get(invocation.sessionId)?.scope.route;
|
|
720
|
+
if (!recoveringUnmatchedLiveEnd &&
|
|
721
|
+
liveRoute !== undefined &&
|
|
722
|
+
!sameRouteProvenance(liveRoute, invocation.route)) {
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
const startedEvent = {
|
|
726
|
+
type: "session.step.started",
|
|
727
|
+
created: invocation.completedAtMs,
|
|
728
|
+
data: {
|
|
729
|
+
sessionID: invocation.sessionId,
|
|
730
|
+
assistantMessageID: invocation.messageId,
|
|
731
|
+
model: {
|
|
732
|
+
providerID: invocation.route.providerId,
|
|
733
|
+
id: invocation.route.modelId,
|
|
734
|
+
...(invocation.route.variantId === undefined
|
|
735
|
+
? {}
|
|
736
|
+
: { variant: invocation.route.variantId }),
|
|
737
|
+
},
|
|
738
|
+
...(invocation.dispatchAtMs === undefined ? {} : { started: invocation.dispatchAtMs }),
|
|
739
|
+
},
|
|
740
|
+
};
|
|
741
|
+
const { fresh, read, write } = invocation.counts;
|
|
742
|
+
const endedEvent = {
|
|
743
|
+
type: "session.step.ended",
|
|
744
|
+
created: invocation.completedAtMs,
|
|
745
|
+
data: {
|
|
746
|
+
sessionID: invocation.sessionId,
|
|
747
|
+
assistantMessageID: invocation.messageId,
|
|
748
|
+
tokens: {
|
|
749
|
+
...(fresh === undefined ? {} : { input: fresh }),
|
|
750
|
+
...(read === undefined && write === undefined
|
|
751
|
+
? {}
|
|
752
|
+
: {
|
|
753
|
+
cache: {
|
|
754
|
+
...(read === undefined ? {} : { read }),
|
|
755
|
+
...(write === undefined ? {} : { write }),
|
|
756
|
+
},
|
|
757
|
+
}),
|
|
758
|
+
},
|
|
759
|
+
},
|
|
760
|
+
};
|
|
761
|
+
if (recoveringUnmatchedLiveEnd && pendingLiveEnd !== undefined) {
|
|
762
|
+
pendingEndedSteps.set(key, {
|
|
763
|
+
sessionId: invocation.sessionId,
|
|
764
|
+
event: mergeHistoricalCountersIntoLiveEnd(pendingLiveEnd.event, endedEvent),
|
|
765
|
+
});
|
|
766
|
+
ingestEvent(startedEvent, "history");
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
ingestEvent(startedEvent, "history");
|
|
770
|
+
ingestEvent(endedEvent, "history");
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
function subscribe(sessionId, listener) {
|
|
774
|
+
if (disposed || !sessionId.trim())
|
|
775
|
+
return () => undefined;
|
|
776
|
+
let sessionListeners = listeners.get(sessionId);
|
|
777
|
+
if (sessionListeners === undefined) {
|
|
778
|
+
sessionListeners = new Set();
|
|
779
|
+
listeners.set(sessionId, sessionListeners);
|
|
780
|
+
}
|
|
781
|
+
sessionListeners.add(listener);
|
|
782
|
+
if (sessionListeners.size === 1)
|
|
783
|
+
scheduleRecheck(sessionId, query(sessionId));
|
|
784
|
+
return () => {
|
|
785
|
+
sessionListeners?.delete(listener);
|
|
786
|
+
if (sessionListeners?.size === 0) {
|
|
787
|
+
listeners.delete(sessionId);
|
|
788
|
+
clearRecheckTimer(sessionId);
|
|
789
|
+
}
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
function dispose() {
|
|
793
|
+
disposed = true;
|
|
794
|
+
states.clear();
|
|
795
|
+
listeners.clear();
|
|
796
|
+
startedSteps.clear();
|
|
797
|
+
pendingEndedSteps.clear();
|
|
798
|
+
liveStepKeys.clear();
|
|
799
|
+
latestLiveRoutes.clear();
|
|
800
|
+
latestLiveCompletedAt.clear();
|
|
801
|
+
latestLiveCompletion.clear();
|
|
802
|
+
latestUsableLiveCompletion.clear();
|
|
803
|
+
for (const timer of recheckTimers.values())
|
|
804
|
+
clearTimeout(timer);
|
|
805
|
+
recheckTimers.clear();
|
|
806
|
+
}
|
|
807
|
+
return {
|
|
808
|
+
query,
|
|
809
|
+
route,
|
|
810
|
+
subscribe,
|
|
811
|
+
markObservationGap,
|
|
812
|
+
ingest,
|
|
813
|
+
ingestHistory,
|
|
814
|
+
captureConfiguration,
|
|
815
|
+
hasUsableLiveObservation,
|
|
816
|
+
dispose,
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
function projectStartedStep(event) {
|
|
820
|
+
if (!isRecord(event) ||
|
|
821
|
+
event.type !== "session.step.started" ||
|
|
822
|
+
!isRecord(event.data) ||
|
|
823
|
+
typeof event.created !== "number" ||
|
|
824
|
+
!Number.isFinite(event.created)) {
|
|
825
|
+
return undefined;
|
|
826
|
+
}
|
|
827
|
+
const sessionId = nonEmptyString(event.data.sessionID);
|
|
828
|
+
const messageId = nonEmptyString(event.data.assistantMessageID);
|
|
829
|
+
const model = isRecord(event.data.model) ? event.data.model : undefined;
|
|
830
|
+
const providerId = model === undefined ? undefined : nonEmptyString(model.providerID);
|
|
831
|
+
const modelId = model === undefined ? undefined : nonEmptyString(model.id);
|
|
832
|
+
if (sessionId === undefined ||
|
|
833
|
+
messageId === undefined ||
|
|
834
|
+
providerId === undefined ||
|
|
835
|
+
modelId === undefined)
|
|
836
|
+
return undefined;
|
|
837
|
+
const variantId = model === undefined ? undefined : normalizedVariantId(model.variant);
|
|
838
|
+
const dispatchAtMs = ownFiniteNumber(event.data, "started");
|
|
839
|
+
return {
|
|
840
|
+
type: "session.step.started",
|
|
841
|
+
created: event.created,
|
|
842
|
+
data: {
|
|
843
|
+
sessionID: sessionId,
|
|
844
|
+
assistantMessageID: messageId,
|
|
845
|
+
model: {
|
|
846
|
+
providerID: providerId,
|
|
847
|
+
id: modelId,
|
|
848
|
+
...(variantId === undefined ? {} : { variant: variantId }),
|
|
849
|
+
},
|
|
850
|
+
...(dispatchAtMs === undefined || dispatchAtMs < 0 ? {} : { started: dispatchAtMs }),
|
|
851
|
+
},
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
function startedStepFromDto(event) {
|
|
855
|
+
if (!isRecord(event) ||
|
|
856
|
+
event.type !== "session.step.started" ||
|
|
857
|
+
!isRecord(event.data) ||
|
|
858
|
+
!isRecord(event.data.model)) {
|
|
859
|
+
return undefined;
|
|
860
|
+
}
|
|
861
|
+
const sessionId = nonEmptyString(event.data.sessionID);
|
|
862
|
+
const messageId = nonEmptyString(event.data.assistantMessageID);
|
|
863
|
+
const providerId = nonEmptyString(event.data.model.providerID);
|
|
864
|
+
const modelId = nonEmptyString(event.data.model.id);
|
|
865
|
+
if (sessionId === undefined ||
|
|
866
|
+
messageId === undefined ||
|
|
867
|
+
providerId === undefined ||
|
|
868
|
+
modelId === undefined)
|
|
869
|
+
return undefined;
|
|
870
|
+
const variantId = normalizedVariantId(event.data.model.variant);
|
|
871
|
+
const dispatchAtMs = ownFiniteNumber(event.data, "started");
|
|
872
|
+
const basis = {
|
|
873
|
+
source: "OpenCode session.step.started selected model identity",
|
|
874
|
+
reference: messageId,
|
|
875
|
+
};
|
|
876
|
+
return {
|
|
877
|
+
sessionId,
|
|
878
|
+
messageId,
|
|
879
|
+
route: {
|
|
880
|
+
providerId,
|
|
881
|
+
modelId,
|
|
882
|
+
...(variantId === undefined ? {} : { variantId }),
|
|
883
|
+
basis,
|
|
884
|
+
},
|
|
885
|
+
...(dispatchAtMs === undefined || dispatchAtMs < 0 ? {} : { dispatchAtMs }),
|
|
886
|
+
...(event.data.connectionMethod === "oauth" ||
|
|
887
|
+
event.data.connectionMethod === "key" ||
|
|
888
|
+
event.data.connectionMethod === "external"
|
|
889
|
+
? { connectionMethod: event.data.connectionMethod }
|
|
890
|
+
: {}),
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
function startedStepKey(sessionId, messageId) {
|
|
894
|
+
return JSON.stringify([sessionId, messageId]);
|
|
895
|
+
}
|
|
896
|
+
function sameRouteProvenance(left, right) {
|
|
897
|
+
return (left !== undefined &&
|
|
898
|
+
right !== undefined &&
|
|
899
|
+
left.providerId === right.providerId &&
|
|
900
|
+
left.modelId === right.modelId &&
|
|
901
|
+
left.variantId === right.variantId &&
|
|
902
|
+
left.protocolId === right.protocolId);
|
|
903
|
+
}
|
|
904
|
+
function isRecord(value) {
|
|
905
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
906
|
+
}
|
|
907
|
+
function nonEmptyString(value) {
|
|
908
|
+
return typeof value === "string" && value.trim() ? value : undefined;
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* A successful primary request: `stop`, or `tool-calls` handing off to tools.
|
|
912
|
+
* Length-truncated, content-filtered, errored, and unknown finishes are not
|
|
913
|
+
* successful requests and never start a retention estimate.
|
|
914
|
+
*/
|
|
915
|
+
const ELIGIBLE_STEP_FINISHES = new Set(["stop", "tool-calls"]);
|
|
916
|
+
function isEligibleStepFinish(finish) {
|
|
917
|
+
return ELIGIBLE_STEP_FINISHES.has(finish);
|
|
918
|
+
}
|
|
919
|
+
/** OpenCode v2.2.0 `ModelResolver.withVariant` maps `default` to an omitted variant. */
|
|
920
|
+
function normalizedVariantId(value) {
|
|
921
|
+
const variantId = nonEmptyString(value);
|
|
922
|
+
return variantId === "default" ? undefined : variantId;
|
|
923
|
+
}
|
|
924
|
+
function ownFiniteNumber(record, key) {
|
|
925
|
+
if (!Object.hasOwn(record, key))
|
|
926
|
+
return undefined;
|
|
927
|
+
const value = record[key];
|
|
928
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
929
|
+
}
|
|
930
|
+
function ownNonNegativeFiniteNumber(record, key) {
|
|
931
|
+
const value = ownFiniteNumber(record, key);
|
|
932
|
+
return value !== undefined && value >= 0 ? value : undefined;
|
|
933
|
+
}
|
|
934
|
+
function hasObservedCounts(counts) {
|
|
935
|
+
return counts.fresh !== undefined || counts.read !== undefined || counts.write !== undefined;
|
|
936
|
+
}
|
|
937
|
+
function compareLiveCompletion(left, right) {
|
|
938
|
+
if (left.completedAtMs !== right.completedAtMs) {
|
|
939
|
+
return left.completedAtMs - right.completedAtMs;
|
|
940
|
+
}
|
|
941
|
+
return left.messageId < right.messageId ? -1 : left.messageId > right.messageId ? 1 : 0;
|
|
942
|
+
}
|
|
943
|
+
function mergeHistoricalCountersIntoLiveEnd(liveEvent, historyEvent) {
|
|
944
|
+
const liveTokens = liveEvent.data.tokens;
|
|
945
|
+
const historyTokens = historyEvent.data.tokens;
|
|
946
|
+
const liveCache = isRecord(liveTokens.cache) ? liveTokens.cache : undefined;
|
|
947
|
+
const historyCache = isRecord(historyTokens.cache) ? historyTokens.cache : undefined;
|
|
948
|
+
const fresh = ownFiniteNumber(liveTokens, "input") ?? ownFiniteNumber(historyTokens, "input");
|
|
949
|
+
const read = (liveCache === undefined ? undefined : ownFiniteNumber(liveCache, "read")) ??
|
|
950
|
+
(historyCache === undefined ? undefined : ownFiniteNumber(historyCache, "read"));
|
|
951
|
+
const write = (liveCache === undefined ? undefined : ownFiniteNumber(liveCache, "write")) ??
|
|
952
|
+
(historyCache === undefined ? undefined : ownFiniteNumber(historyCache, "write"));
|
|
953
|
+
return {
|
|
954
|
+
type: "session.step.ended",
|
|
955
|
+
created: liveEvent.created,
|
|
956
|
+
data: {
|
|
957
|
+
sessionID: liveEvent.data.sessionID,
|
|
958
|
+
assistantMessageID: liveEvent.data.assistantMessageID,
|
|
959
|
+
tokens: {
|
|
960
|
+
...(fresh === undefined ? {} : { input: fresh }),
|
|
961
|
+
...(read === undefined && write === undefined
|
|
962
|
+
? {}
|
|
963
|
+
: {
|
|
964
|
+
cache: {
|
|
965
|
+
...(read === undefined ? {} : { read }),
|
|
966
|
+
...(write === undefined ? {} : { write }),
|
|
967
|
+
},
|
|
968
|
+
}),
|
|
969
|
+
},
|
|
970
|
+
},
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
function eventOrder(event, messageId) {
|
|
974
|
+
if (messageId === undefined ||
|
|
975
|
+
typeof event.created !== "number" ||
|
|
976
|
+
!Number.isFinite(event.created)) {
|
|
977
|
+
return undefined;
|
|
978
|
+
}
|
|
979
|
+
return { completedAtMs: event.created, messageId };
|
|
980
|
+
}
|
|
981
|
+
//# sourceMappingURL=cache-observer-ingestion.js.map
|