The best way to control Claude Code, Codex and more from any computer or phone

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