Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.ts

146 lines5.0 KB

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 { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
7import {
8 parseTimestampMs,
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 { PiSettings } from "../settings.ts";
17​
18const PiScanState = Schema.Struct({ sessionId: Schema.mutableKey(Schema.String) });
19const Usage = Schema.Struct({
20 input: Schema.optional(Schema.Unknown),
21 output: Schema.optional(Schema.Unknown),
22 cacheRead: Schema.optional(Schema.Unknown),
23 cacheWrite: Schema.optional(Schema.Unknown),
24 reasoning: Schema.optional(Schema.Unknown),
25 cost: Schema.optional(Schema.Struct({ total: Schema.Unknown })),
26});
27const Identity = { id: Schema.NonEmptyString, timestamp: Schema.String };
28const Model = { provider: Schema.NonEmptyString, model: Schema.NonEmptyString };
29const Entry = Schema.Union([
30 Schema.Struct({ type: Schema.Literal("session"), id: Schema.NonEmptyString }),
31 Schema.Struct({
32 ...Identity,
33 type: Schema.Literal("message"),
34 message: Schema.Union([
35 Schema.Struct({
36 ...Model,
37 role: Schema.Literal("assistant"),
38 responseModel: Schema.optional(Schema.NonEmptyString),
39 usage: Usage,
40 }),
41 Schema.Struct({ role: Schema.Literal("toolResult"), usage: Usage }),
42 ]),
43 }),
44 Schema.Struct({ ...Identity, ...Model, type: Schema.Literal("usage"), usage: Usage }),
45 Schema.Struct({
46 ...Identity,
47 type: Schema.Literals(["compaction", "branch_summary"]),
48 usage: Usage,
49 }),
50]);
51const decodeEntry = Schema.decodeUnknownOption(Entry);
52​
53function parseRecord(parsed: unknown, state: typeof PiScanState.Type): readonly UsageRecord[] {
54 const decoded = decodeEntry(parsed);
55 if (Option.isNone(decoded)) return [];
56 const entry = decoded.value;
57 if (entry.type === "session") {
58 state.sessionId = entry.id;
59 return [];
60 }
61 const timestampMs = parseTimestampMs(entry.timestamp);
62 if (timestampMs === null) return [];
63 const source = entry.type === "message" ? entry.message : entry;
64 const usage = source.usage;
65 // Auxiliary tool/summary records lack model attribution; match Pi's breakdown.
66 const rateModel =
67 "model" in source
68 ? "responseModel" in source
69 ? (source.responseModel ?? source.model)
70 : source.model
71 : undefined;
72 const model = "provider" in source ? `${source.provider}/${rateModel}` : "Tools/summaries";
73 const outputTokens = tokenCount(usage.output);
74 const totals = {
75 // Pi's input/cache counters are already disjoint.
76 uncachedInputTokens: tokenCount(usage.input),
77 cachedInputTokens: tokenCount(usage.cacheRead),
78 cacheCreationTokens: tokenCount(usage.cacheWrite),
79 outputTokens,
80 reasoningTokens: Math.min(outputTokens, tokenCount(usage.reasoning)),
81 };
82 const cost = usage.cost?.total;
83 // Omitted Pi rates default to zero; use shared estimates without positive transcript cost.
84 const reportedCostUsd =
85 typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null;
86 if (totalTokens(totals) === 0 && reportedCostUsd === null) return [];
87 return [
88 {
89 provider: "pi",
90 timestampMs,
91 model,
92 ...(rateModel === undefined ? {} : { rateModel }),
93 sessionId: state.sessionId,
94 totals,
95 reportedCostUsd,
96 speed: "standard",
97 // Forks preserve IDs/timestamps; short random IDs need timestamp/model to avoid cross-session collisions.
98 dedupeKey: JSON.stringify(["pi", entry.id, entry.timestamp, model]),
99 },
100 ];
102​
103export const piUsageFormat: TranscriptUsageFormat<typeof PiScanState.Type> = {
104 selectFields: {
105 type: true,
106 id: true,
107 timestamp: true,
108 provider: true,
109 model: true,
110 usage: true,
111 message: { role: true, provider: true, model: true, responseModel: true, usage: true },
112 },
113 usageMarkers: ['"usage"', '"session"'],
114 parseLine: (line, state) => {
115 let parsed: unknown;
116 try {
117 parsed = JSON.parse(line);
118 } catch {
119 return [];
120 }
121 return parseRecord(parsed, state);
122 },
123 parseProjected: parseRecord,
124 state: { initial: () => ({ sessionId: "" }), schema: PiScanState },
125};
126​
127export const piUsageReader: ProviderUsageReader<PiSettings, Path.Path> = {
128 kind: "transcripts",
129 provider: "pi",
130 format: piUsageFormat,
131 directories: Effect.fn("piUsageReader.directories")(function* ({ environment }) {
132 const path = yield* Path.Path;
133 const home = yield* HostProcess.HomeDirectory;
134 const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim();
135 if (sessionDir) return [{ dir: path.resolve(expandHomePath(sessionDir, home)) }];
136 const agentDir = environment.PI_CODING_AGENT_DIR?.trim();
137 return [
138 {
139 dir: path.resolve(
140 agentDir ? expandHomePath(agentDir, home) : path.join(home, ".pi", "agent"),
141 "sessions",
142 ),
143 },
144 ];
145 }),
146};