Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Path from "effect/Path";
4import * as Schema from "effect/Schema";
5
6import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
7import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
8import {
9 tokenCount,
10 totalTokens,
11 type ProviderUsageReader,
12 type TranscriptUsageFormat,
13 type UsageRecord,
14} from "@t3tools/provider-core/server/usage";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import type { MuseSettings } from "../settings.ts";
17import { makeMuseEnvironment } from "./sdk.ts";
18import * as MuseUsageHome from "./MuseUsageHome.ts";
19
20const Entry = Schema.Struct({
21 schema_version: Schema.Literal(1),
22 record_type: Schema.Literal("event"),
23 payload_type: Schema.Literal("runtime.session"),
24 // Native automated review completions use session payload version 3.
25 payload_schema_version: Schema.Literals([1, 3]),
26 id: Schema.NonEmptyString,
27 recorded_at: Schema.Number,
28 stream: Schema.Struct({ kind: Schema.Literal("session"), id: Schema.NonEmptyString }),
29 payload: Schema.Struct({
30 source_run_record_id: Schema.optional(Schema.NonEmptyString),
31 event: Schema.Struct({
32 kind: Schema.Literals(["model_completed", "automated_review_completed"]),
33 model: Schema.Union([
34 Schema.NonEmptyString,
35 Schema.Struct({ model_id: Schema.NonEmptyString }),
36 ]),
37 usage: Schema.Struct({
38 input_tokens: Schema.optional(Schema.Unknown),
39 output_tokens: Schema.optional(Schema.Unknown),
40 cached_tokens: Schema.optional(Schema.Unknown),
41 cached_input_tokens: Schema.optional(Schema.Unknown),
42 cache_read_tokens: Schema.optional(Schema.Unknown),
43 cache_write_tokens: Schema.optional(Schema.Unknown),
44 reasoning_tokens: Schema.optional(Schema.Unknown),
45 }),
46 }),
47 }),
48});
49const decodeEntry = Schema.decodeUnknownOption(Entry);
50
51function parseRecord(parsed: unknown): readonly UsageRecord[] {
52 const decoded = decodeEntry(parsed);
53 if (Option.isNone(decoded)) return [];
54 const entry = decoded.value;
55 if (!Number.isSafeInteger(entry.recorded_at) || entry.recorded_at < 0) return [];
56 const { event } = entry.payload;
57 const { usage } = event;
58 const input = tokenCount(usage.input_tokens);
59 const cachedInputTokens = Math.min(
60 input,
61 tokenCount(usage.cache_read_tokens ?? usage.cached_input_tokens ?? usage.cached_tokens),
62 );
63 const cacheCreationTokens = Math.min(
64 input - cachedInputTokens,
65 tokenCount(usage.cache_write_tokens),
66 );
67 const outputTokens = tokenCount(usage.output_tokens);
68 const totals = {
69 // Muse's cache counters are subsets of input; reasoning is a subset of output.
70 uncachedInputTokens: input - cachedInputTokens - cacheCreationTokens,
71 cachedInputTokens,
72 cacheCreationTokens,
73 outputTokens,
74 reasoningTokens: Math.min(outputTokens, tokenCount(usage.reasoning_tokens)),
75 };
76 if (totalTokens(totals) === 0) return [];
77 return [
78 {
79 provider: "muse",
80 timestampMs: Math.trunc(entry.recorded_at / 1_000),
81 model: typeof event.model === "string" ? event.model : event.model.model_id,
82 sessionId: entry.stream.id,
83 totals,
84 reportedCostUsd: null,
85 speed: "standard",
86 // Runtime envelopes can be copied into another session. The source record
87 // identifies the inference even when the enclosing envelope has a new ID.
88 dedupeKey: JSON.stringify(["muse", entry.payload.source_run_record_id ?? entry.id]),
89 },
90 ];
91}
92
93export const museUsageFormat: TranscriptUsageFormat<unknown> = {
94 selectFields: {
95 schema_version: true,
96 record_type: true,
97 payload_type: true,
98 payload_schema_version: true,
99 id: true,
100 recorded_at: true,
101 stream: { kind: true, id: true },
102 payload: { source_run_record_id: true, event: { kind: true, model: true, usage: true } },
103 },
104 usageMarkers: ['"model_completed"', '"automated_review_completed"'],
105 parseLine: (line) => {
106 let parsed: unknown;
107 try {
108 parsed = JSON.parse(line);
109 } catch {
110 return [];
111 }
112 return parseRecord(parsed);
113 },
114 parseProjected: parseRecord,
115};
116
117export const museUsageReader: ProviderUsageReader<
118 MuseSettings,
119 Path.Path | MuseUsageHome.MuseUsageHome
120> = {
121 kind: "transcripts",
122 provider: "muse",
123 format: museUsageFormat,
124 directories: Effect.fn("museUsageReader.directories")(function* (
125 { config, environment },
126 { awaitRefresh },
127 ) {
128 const path = yield* Path.Path;
129 const home = yield* HostProcess.HomeDirectory;
130 const usageHome = yield* MuseUsageHome.MuseUsageHome;
131 const processEnvironment = yield* mergeProviderInstanceEnvironment(
132 Object.entries(environment).flatMap(([name, value]) =>
133 value === undefined ? [] : [{ name, value, sensitive: false }],
134 ),
135 yield* HostProcess.Environment,
136 );
137 const binaryPath = expandHomePath(config?.binaryPath ?? "muse", home);
138 const museHome = yield* usageHome.resolve({
139 binaryPath,
140 environment: makeMuseEnvironment(processEnvironment),
141 awaitRefresh,
142 });
143 if (Option.isNone(museHome)) return [{ dir: binaryPath, refreshing: true }];
144 return museHome.value
145 ? [{ dir: path.join(museHome.value, "sessions"), fileName: "session.jsonl" }]
146 : [];
147 }),
148};