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

usage.ts

150 lines5.2 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 // Pi's auxiliary tool and summary records carry no model attribution. Match
66 // Pi's own breakdown rather than assigning them to the conversation model.
67 const rateModel =
68 "model" in source
69 ? "responseModel" in source
70 ? (source.responseModel ?? source.model)
71 : source.model
72 : undefined;
73 const model = "provider" in source ? `${source.provider}/${rateModel}` : "Tools/summaries";
74 const outputTokens = tokenCount(usage.output);
75 const totals = {
76 // Pi's input/cache counters are already disjoint.
77 uncachedInputTokens: tokenCount(usage.input),
78 cachedInputTokens: tokenCount(usage.cacheRead),
79 cacheCreationTokens: tokenCount(usage.cacheWrite),
80 outputTokens,
81 reasoningTokens: Math.min(outputTokens, tokenCount(usage.reasoning)),
82 };
83 const cost = usage.cost?.total;
84 // Pi defaults omitted catalog rates to zero. Let shared pricing estimate
85 // API-equivalent cost when the transcript has no positive cost estimate.
86 const reportedCostUsd =
87 typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null;
88 if (totalTokens(totals) === 0 && reportedCostUsd === null) return [];
89 return [
90 {
91 provider: "pi",
92 timestampMs,
93 model,
94 ...(rateModel === undefined ? {} : { rateModel }),
95 sessionId: state.sessionId,
96 totals,
97 reportedCostUsd,
98 speed: "standard",
99 // Forks copy entries verbatim, including ID/timestamp. Entry IDs are only
100 // eight random hex digits, so retain timestamp/model to avoid collisions
101 // across unrelated sessions.
102 dedupeKey: JSON.stringify(["pi", entry.id, entry.timestamp, model]),
103 },
104 ];
106​
107export const piUsageFormat: TranscriptUsageFormat<typeof PiScanState.Type> = {
108 selectFields: {
109 type: true,
110 id: true,
111 timestamp: true,
112 provider: true,
113 model: true,
114 usage: true,
115 message: { role: true, provider: true, model: true, responseModel: true, usage: true },
116 },
117 usageMarkers: ['"usage"', '"session"'],
118 parseLine: (line, state) => {
119 let parsed: unknown;
120 try {
121 parsed = JSON.parse(line);
122 } catch {
123 return [];
124 }
125 return parseRecord(parsed, state);
126 },
127 parseProjected: parseRecord,
128 state: { initial: () => ({ sessionId: "" }), schema: PiScanState },
129};
130​
131export const piUsageReader: ProviderUsageReader<PiSettings, Path.Path> = {
132 kind: "transcripts",
133 provider: "pi",
134 format: piUsageFormat,
135 directories: Effect.fn("piUsageReader.directories")(function* ({ environment }) {
136 const path = yield* Path.Path;
137 const home = yield* HostProcess.HomeDirectory;
138 const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim();
139 if (sessionDir) return [{ dir: path.resolve(expandHomePath(sessionDir, home)) }];
140 const agentDir = environment.PI_CODING_AGENT_DIR?.trim();
141 return [
142 {
143 dir: path.resolve(
144 agentDir ? expandHomePath(agentDir, home) : path.join(home, ".pi", "agent"),
145 "sessions",
146 ),
147 },
148 ];
149 }),
150};