From 927228bd7bc656d6cb0fd456409215ed3ce4e0f9 Mon Sep 17 00:00:00 2001 From: Benjamin Coriou Date: Tue, 27 Oct 2026 19:18:09 +0100 Subject: [PATCH 1/2] feat(fork): show Oh My Pi spend on the usage page Usage had no Oh My Pi source, so OMP spend never reached the daily/hourly history, model breakdown, or cache savings. Read OMP's native session JSONL: per-message usage carries the same cost OMP reports over ACP, and each file's session header supplies the session identity that resume needs. Subagent transcripts are separate sessions beside the session file, so they are counted from their own files; the parent's task aggregate is ignored to avoid counting that spend twice. Records keep the bare model id as rateModel, because the rate table keys on it, while the provider-prefixed id stays the display model. Zero-cost records fall back to T3's model pricing like the other providers. Store resolution follows OMP's own precedence: --session-dir, PI_CODING_AGENT_SESSION_DIR, profile (--profile / OMP_PROFILE / PI_PROFILE), PI_CODING_AGENT_DIR, an XDG root, then PI_CONFIG_DIR and the default root. The OMP adapter also gains a regression test that its end-of-turn usage_update cost reaches the provider thread. --- .../src/features/usage/usageProviders.ts | 3 + .../Adapters/OmpAdapterV2.fixture.mjs | 9 + .../Adapters/OmpAdapterV2.test.ts | 23 ++ apps/server/src/provider/Drivers/OmpDriver.ts | 4 +- .../src/provider/Drivers/ompUsage.test.ts | 345 ++++++++++++++++++ apps/server/src/provider/Drivers/ompUsage.ts | 193 ++++++++++ apps/server/src/provider/builtInDrivers.ts | 4 +- .../src/components/usage/usageProviders.ts | 5 + docs/user/usage.md | 8 +- packages/contracts/src/usage.ts | 2 + 10 files changed, 593 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/provider/Drivers/ompUsage.test.ts create mode 100644 apps/server/src/provider/Drivers/ompUsage.ts diff --git a/apps/mobile/src/features/usage/usageProviders.ts b/apps/mobile/src/features/usage/usageProviders.ts index ce9c778a77762..a3db8f6656b81 100644 --- a/apps/mobile/src/features/usage/usageProviders.ts +++ b/apps/mobile/src/features/usage/usageProviders.ts @@ -10,6 +10,7 @@ export const PROVIDER_ORDER: readonly UsageProviderKind[] = [ "antigravity", "pi", "muse", + "omp", ]; export function usageProviderKind(driver: string): UsageProviderKind | null { @@ -26,6 +27,7 @@ export const PROVIDER_LABEL: Record = { antigravity: "Antigravity", pi: "Pi", muse: "Muse Code", + omp: "Oh My Pi", }; export function useProviderColors(): Record { @@ -39,6 +41,7 @@ export function useProviderColors(): Record { antigravity: "#8c7bd1", pi: "#4d9f8a", muse: "#0866ff", + omp: "#f97316", }; } diff --git a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.fixture.mjs b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.fixture.mjs index d73442b5d5476..bfcbb0f0d5bec 100644 --- a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.fixture.mjs +++ b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.fixture.mjs @@ -67,6 +67,15 @@ const finish = (stopReason = "end_turn", value = "hello from OMP") => { const current = prompt; prompt = undefined; if (value) text(current.params.sessionId, value); + // OMP reports cumulative session cost with the end-of-turn context update. + const usageCost = Number(process.env.OMP_USAGE_COST ?? ""); + if (usageCost > 0) + update(current.params.sessionId, { + sessionUpdate: "usage_update", + size: 1_048_576, + used: 479_761, + cost: { amount: usageCost, currency: "USD" }, + }); result(current.id, { stopReason }); }; NodeReadline.createInterface({ input: process.stdin }).on("line", (line) => { diff --git a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts index f1cfb91b8098e..541c7ce2ccb53 100644 --- a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts @@ -237,6 +237,29 @@ describe("OMP V2 native ACP parity", () => { }).pipe(Effect.provide(layer), Effect.scoped), ); + it.effect("keeps the cumulative session cost OMP reports with its end-of-turn usage", () => + Effect.gen(function* () { + const { runtime, turnInput } = yield* open({ OMP_USAGE_COST: "4.91" }); + yield* runtime.startTurn(turnInput); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const usage = events.findLast( + (event) => event.type === "provider_thread.updated" && event.providerThread.contextUsage, + ); + + assert.deepEqual( + usage?.type === "provider_thread.updated" ? usage.providerThread.contextUsage : undefined, + { + usedTokens: 479_761, + maxTokens: 1_048_576, + cost: { amount: 4.91, currency: "USD" }, + }, + ); + }).pipe(Effect.provide(layer), Effect.scoped), + ); + it.effect( "applies model, thinking and native implementation mode and resumes native sessions", () => diff --git a/apps/server/src/provider/Drivers/OmpDriver.ts b/apps/server/src/provider/Drivers/OmpDriver.ts index a73625f1436f0..18e6fb07daab6 100644 --- a/apps/server/src/provider/Drivers/OmpDriver.ts +++ b/apps/server/src/provider/Drivers/OmpDriver.ts @@ -12,6 +12,7 @@ import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; import { makeOmpTextGeneration } from "../../textGeneration/OmpTextGeneration.ts"; import { ProviderDriverError } from "../Errors.ts"; +import { ompUsageReader, type OmpUsageEnv } from "./ompUsage.ts"; import { OmpAdapterV2Driver, type OmpAdapterV2DriverEnv, @@ -88,12 +89,13 @@ const withInstanceIdentity = continuation: { groupKey: input.continuationGroupKey }, }); -export const OmpDriver: ProviderDriver = { +export const OmpDriver: ProviderDriver = { driverKind: DRIVER_KIND, metadata: { displayName: "Oh My Pi", supportsMultipleInstances: true, }, + usage: ompUsageReader, configSchema: OmpSettings, defaultConfig: (): OmpSettings => decodeOmpSettings({}), create: Effect.fn("OmpDriver.create")(function* ({ diff --git a/apps/server/src/provider/Drivers/ompUsage.test.ts b/apps/server/src/provider/Drivers/ompUsage.test.ts new file mode 100644 index 0000000000000..fb5107146d7a6 --- /dev/null +++ b/apps/server/src/provider/Drivers/ompUsage.test.ts @@ -0,0 +1,345 @@ +// @effect-diagnostics nodeBuiltinImport:off - exercise the real byte reader. +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest"; +import { OmpSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import { readTranscriptRecords } from "../../usage/usageTranscriptReader.ts"; +import { ompUsageDirectories, ompUsageFormat } from "./ompUsage.ts"; + +type ScanState = { sessionId: string }; + +const initial = (): ScanState => ({ sessionId: "" }); + +const session = (id: string, extra: Record = {}) => + JSON.stringify({ + type: "session", + version: 3, + id, + timestamp: "2026-10-24T13:58:52.043Z", + ...extra, + }); + +const assistant = (overrides: { + readonly id: string; + readonly timestamp?: string; + readonly provider?: string; + readonly model?: string; + readonly usage?: Record; +}) => + JSON.stringify({ + type: "message", + id: overrides.id, + parentId: null, + timestamp: overrides.timestamp ?? "2026-10-24T13:59:10.287Z", + message: { + role: "assistant", + content: [{ type: "text", text: "hi" }], + provider: overrides.provider ?? "openrouter", + model: overrides.model ?? "z-ai/glm-5.3-flash", + usage: overrides.usage ?? { + input: 2_400, + output: 425, + cacheRead: 24_320, + cacheWrite: 8, + totalTokens: 27_153, + reasoningTokens: 76, + cost: { + input: 0.0003, + output: 0.0002, + cacheRead: 0.00006, + cacheWrite: 0.0004, + total: 0.001, + }, + }, + }, + }); + +function scan(lines: readonly string[], state: ScanState = initial()) { + const records = lines.flatMap((line) => ompUsageFormat.parseLine(line, state)); + return { records, state }; +} + +describe("ompUsageFormat", () => { + it("attributes assistant token and cost totals to the session header", () => { + const { records, state } = scan([session("01a16e35"), assistant({ id: "a1" })]); + + expect(state.sessionId).toBe("01a16e35"); + expect(records).toEqual([ + { + provider: "omp", + timestampMs: Date.parse("2026-10-24T13:59:10.287Z"), + model: "openrouter/z-ai/glm-5.3-flash", + rateModel: "z-ai/glm-5.3-flash", + sessionId: "01a16e35", + totals: { + uncachedInputTokens: 2_400, + cachedInputTokens: 24_320, + cacheCreationTokens: 8, + outputTokens: 425, + reasoningTokens: 76, + }, + reportedCostUsd: 0.001, + speed: "standard", + dedupeKey: JSON.stringify([ + "omp", + "a1", + "2026-10-24T13:59:10.287Z", + "openrouter/z-ai/glm-5.3-flash", + ]), + }, + ]); + }); + + it("keeps tokens but leaves cost to T3 estimates when OMP had no price", () => { + const { records } = scan([ + session("s1"), + assistant({ id: "a1", usage: { input: 10, output: 2, cacheRead: 0, cacheWrite: 0 } }), + assistant({ + id: "a2", + usage: { input: 10, output: 2, cacheRead: 0, cacheWrite: 0, cost: { total: 0 } }, + }), + ]); + + expect(records.map((record) => record.reportedCostUsd)).toEqual([null, null]); + expect(records.map((record) => record.totals.outputTokens)).toEqual([2, 2]); + }); + + it("ignores task subagent aggregates because child sessions report their own spend", () => { + const taskResult = JSON.stringify({ + type: "message", + id: "t1", + timestamp: "2026-10-24T14:00:00.000Z", + message: { + role: "toolResult", + toolName: "task", + content: [], + details: { results: [], usage: { input: 5, output: 5, cost: { total: 3 } } }, + }, + }); + + expect(scan([session("s1"), taskResult]).records).toEqual([]); + }); + + it("skips entries that carry no usage", () => { + const userMessage = JSON.stringify({ + type: "message", + id: "u1", + timestamp: "2026-10-24T13:58:53.000Z", + message: { role: "user", content: [{ type: "text", text: "hello" }] }, + }); + const modelChange = JSON.stringify({ + type: "model_change", + id: "m1", + timestamp: "2026-10-24T13:58:52.817Z", + model: "openrouter/z-ai/glm-5.3-flash", + }); + + expect(scan([session("s1"), userMessage, modelChange, "{not json"]).records).toEqual([]); + }); + + it("keeps a subagent session's spend apart while a copied fork entry dedupes", () => { + const parentEntry = assistant({ id: "a1" }); + const { records } = scan([ + session("parent"), + parentEntry, + session("child", { parentSession: "/sessions/parent.jsonl" }), + assistant({ id: "c1", timestamp: "2026-10-24T14:01:00.000Z" }), + session("fork"), + parentEntry, + ]); + + expect(records.map((record) => record.sessionId)).toEqual(["parent", "child", "fork"]); + // The fork wrote the same entry verbatim, so one key covers both copies; the child is distinct spend. + expect(records[2]?.dedupeKey).toBe(records[0]?.dedupeKey); + expect(records[1]?.dedupeKey).not.toBe(records[0]?.dedupeKey); + }); +}); + +const readersLayer = NodeServices.layer; +const decodeSettings = Schema.decodeSync(OmpSettings); + +function directories(environment: NodeJS.ProcessEnv, home: string, launchArgs = "") { + return ompUsageDirectories({ + config: decodeSettings({ launchArgs }), + environment, + }).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provideService(HostProcess.Platform, "darwin"), + ); +} + +describe("ompUsageDirectories", () => { + it.effect("defaults to ~/.omp/agent/sessions", () => + Effect.gen(function* () { + expect(yield* directories({}, "/home/tester")).toEqual([ + { dir: "/home/tester/.omp/agent/sessions" }, + ]); + }).pipe(Effect.provide(readersLayer)), + ); + + it.effect("follows PI_CODING_AGENT_DIR, expanding a leading ~ as the other readers do", () => + Effect.gen(function* () { + expect(yield* directories({ PI_CODING_AGENT_DIR: "~/omp-agent" }, "/home/tester")).toEqual([ + { dir: "/home/tester/omp-agent/sessions" }, + ]); + }).pipe(Effect.provide(readersLayer)), + ); + + it.effect("reads a launch-argument profile store, which outranks PI_CODING_AGENT_DIR", () => + Effect.gen(function* () { + expect( + yield* directories({ PI_CODING_AGENT_DIR: "/srv/agent" }, "/home/tester", "--profile work"), + ).toEqual([{ dir: "/home/tester/.omp/profiles/work/agent/sessions" }]); + expect( + yield* directories({ OMP_PROFILE: "work" }, "/home/tester", "--profile default"), + ).toEqual([{ dir: "/home/tester/.omp/agent/sessions" }]); + }).pipe(Effect.provide(readersLayer)), + ); + + it.effect("resolves OMP_PROFILE, including its default-profile sentinels", () => + Effect.gen(function* () { + expect(yield* directories({ OMP_PROFILE: "work" }, "/home/tester")).toEqual([ + { dir: "/home/tester/.omp/profiles/work/agent/sessions" }, + ]); + expect( + yield* directories({ OMP_PROFILE: "default", PI_PROFILE: "work" }, "/home/tester"), + ).toEqual([{ dir: "/home/tester/.omp/agent/sessions" }]); + expect(yield* directories({ OMP_PROFILE: "", PI_PROFILE: "work" }, "/home/tester")).toEqual([ + { dir: "/home/tester/.omp/agent/sessions" }, + ]); + }).pipe(Effect.provide(readersLayer)), + ); + + it.effect("renames the config root with PI_CONFIG_DIR", () => + Effect.gen(function* () { + expect(yield* directories({ PI_CONFIG_DIR: ".omp-canary" }, "/home/tester")).toEqual([ + { dir: "/home/tester/.omp-canary/agent/sessions" }, + ]); + }).pipe(Effect.provide(readersLayer)), + ); + + it.effect("prefers an explicit session directory over the agent directory", () => + Effect.gen(function* () { + expect( + yield* directories( + { PI_CODING_AGENT_DIR: "/srv/agent", PI_CODING_AGENT_SESSION_DIR: "/srv/sessions" }, + "/home/tester", + ), + ).toEqual([{ dir: "/srv/sessions" }]); + expect( + yield* directories( + { PI_CODING_AGENT_SESSION_DIR: "/srv/sessions" }, + "/home/tester", + "--session-dir /srv/run", + ), + ).toEqual([{ dir: "/srv/run" }]); + expect(yield* directories({}, "/home/tester", "--session-dir=/srv/equals")).toEqual([ + { dir: "/srv/equals" }, + ]); + }).pipe(Effect.provide(readersLayer)), + ); + + it.effect("prefers a migrated XDG root over the legacy home", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const migrated = yield* fileSystem.makeTempDirectoryScoped({ prefix: "omp-usage-xdg-" }); + yield* fileSystem.makeDirectory(`${migrated}/omp`); + const notMigrated = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "omp-usage-no-xdg-", + }); + + expect(yield* directories({ XDG_DATA_HOME: migrated }, "/home/tester")).toEqual([ + { dir: path.join(migrated, "omp", "sessions") }, + ]); + + yield* fileSystem.makeDirectory(`${migrated}/omp/profiles/work`, { recursive: true }); + expect( + yield* directories({ XDG_DATA_HOME: migrated, OMP_PROFILE: "work" }, "/home/tester"), + ).toEqual([{ dir: path.join(migrated, "omp", "profiles", "work", "sessions") }]); + expect(yield* directories({ XDG_DATA_HOME: notMigrated }, "/home/tester")).toEqual([ + { dir: "/home/tester/.omp/agent/sessions" }, + ]); + }).pipe(Effect.provide(readersLayer)), + ); +}); + +describe("ompUsageReader transcripts", () => { + let dir: string; + beforeEach(async () => { + dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "omp-usage-")); + }); + afterEach(async () => { + await NodeFSP.rm(dir, { recursive: true, force: true }); + }); + + const largeEntry = (text: string) => + JSON.stringify({ + type: "message", + id: "a123abcd", + timestamp: "2026-08-01T10:00:00Z", + message: { + role: "assistant", + content: [{ type: "text", text }], + provider: "openrouter", + model: "z-ai/glm-5.3-flash", + usage: { input: 100, output: 99, cost: { total: 0.25 } }, + }, + }); + + it("projects lines larger than the streaming threshold identically", async () => { + const path = NodePath.join(dir, "large.jsonl"); + const body = '工具 output \\" usage token_count '.repeat(40_000); + await NodeFSP.writeFile(path, [session("omp-session"), largeEntry(body)].join("\n") + "\n"); + + const projected = await readTranscriptRecords(path, ompUsageFormat, undefined, { + streamingThresholdBytes: 1_024, + }); + const linewise = await readTranscriptRecords(path, ompUsageFormat, undefined, { + streamingThresholdBytes: 64 * 1_024 * 1_024, + }); + + expect(projected?.records).toEqual(linewise?.records); + expect(projected?.position.state).toEqual({ sessionId: "omp-session" }); + expect(projected?.records[0]).toMatchObject({ + sessionId: "omp-session", + rateModel: "z-ai/glm-5.3-flash", + reportedCostUsd: 0.25, + }); + }); + + it("resumes an OMP session header so appended messages keep their session", async () => { + const path = NodePath.join(dir, "resume.jsonl"); + await NodeFSP.writeFile(path, session("omp-session") + "\n"); + const header = await readTranscriptRecords(path, ompUsageFormat); + expect(header?.records).toEqual([]); + + await NodeFSP.appendFile( + path, + JSON.stringify({ + type: "message", + id: "a1", + timestamp: "2026-08-01T10:00:00Z", + message: { + role: "assistant", + provider: "openrouter", + model: "z-ai/glm-5.3-flash", + usage: { input: 7, output: 3, cost: { total: 0.5 } }, + }, + }) + "\n", + ); + + const grown = await readTranscriptRecords(path, ompUsageFormat, header!.position); + expect(grown?.records).toHaveLength(1); + expect(grown?.records[0]).toMatchObject({ sessionId: "omp-session", reportedCostUsd: 0.5 }); + }); +}); diff --git a/apps/server/src/provider/Drivers/ompUsage.ts b/apps/server/src/provider/Drivers/ompUsage.ts new file mode 100644 index 0000000000000..22c166e7412b3 --- /dev/null +++ b/apps/server/src/provider/Drivers/ompUsage.ts @@ -0,0 +1,193 @@ +// Fork-local: upstream has no Oh My Pi provider; this mirrors provider-pi's reader for OMP's format. +import type { OmpSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { ompProfileFromLaunchArgs } from "../acp/OmpAcpSupport.ts"; +import { + parseTimestampMs, + tokenCount, + totalTokens, + type ProviderUsageReader, + type TranscriptUsageFormat, + type UsageRecord, +} from "@t3tools/provider-core/server/usage"; +import { tokenizeCliArgs } from "@t3tools/shared/cliArgs"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +const OmpScanState = Schema.Struct({ sessionId: Schema.mutableKey(Schema.String) }); +const Usage = Schema.Struct({ + input: Schema.optional(Schema.Unknown), + output: Schema.optional(Schema.Unknown), + cacheRead: Schema.optional(Schema.Unknown), + cacheWrite: Schema.optional(Schema.Unknown), + reasoningTokens: Schema.optional(Schema.Unknown), + cost: Schema.optional(Schema.Struct({ total: Schema.Unknown })), +}); +const Entry = Schema.Union([ + Schema.Struct({ type: Schema.Literal("session"), id: Schema.NonEmptyString }), + Schema.Struct({ + type: Schema.Literal("message"), + id: Schema.NonEmptyString, + timestamp: Schema.String, + message: Schema.Struct({ + role: Schema.Literal("assistant"), + provider: Schema.NonEmptyString, + model: Schema.NonEmptyString, + usage: Usage, + }), + }), +]); +const decodeEntry = Schema.decodeUnknownOption(Entry); + +function parseRecord(parsed: unknown, state: typeof OmpScanState.Type): readonly UsageRecord[] { + const decoded = decodeEntry(parsed); + if (Option.isNone(decoded)) return []; + const entry = decoded.value; + if (entry.type === "session") { + // Subagent sessions live in their own file with their own header, so each counts as its own session. + state.sessionId = entry.id; + return []; + } + const timestampMs = parseTimestampMs(entry.timestamp); + if (timestampMs === null) return []; + const usage = entry.message.usage; + const model = `${entry.message.provider}/${entry.message.model}`; + const totals = { + uncachedInputTokens: tokenCount(usage.input), + cachedInputTokens: tokenCount(usage.cacheRead), + cacheCreationTokens: tokenCount(usage.cacheWrite), + outputTokens: tokenCount(usage.output), + reasoningTokens: tokenCount(usage.reasoningTokens), + }; + const cost = usage.cost?.total; + // Zero cost means OMP had no price for the model; let T3 estimate instead of recording free usage. + const reportedCostUsd = + typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null; + if (totalTokens(totals) === 0 && reportedCostUsd === null) return []; + return [ + { + provider: "omp", + timestampMs, + model, + // Pricing tables key on the bare model id OMP stores, not the provider-prefixed display id. + rateModel: entry.message.model, + sessionId: state.sessionId, + totals, + reportedCostUsd, + speed: "standard", + // Copies keep ids and timestamps, so this collapses a fork's copied entries; timestamp and model separate unrelated sessions. + dedupeKey: JSON.stringify(["omp", entry.id, entry.timestamp, model]), + }, + ]; +} + +export const ompUsageFormat: TranscriptUsageFormat = { + selectFields: { + type: true, + id: true, + timestamp: true, + message: { role: true, provider: true, model: true, usage: true }, + }, + usageMarkers: ['"usage"', '"session"'], + parseLine: (line, state) => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + return []; + } + return parseRecord(parsed, state); + }, + parseProjected: parseRecord, + state: { initial: () => ({ sessionId: "" }), schema: OmpScanState }, +}; + +export type OmpUsageEnv = Path.Path | FileSystem.FileSystem; + +const PROFILE_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const WINDOWS_RESERVED_PROFILE = /^(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?$/i; + +/** Empty, `default`, and names OMP rejects all fall back to the default profile instead of failing a scan. */ +function profileName(value: string | undefined): string | undefined { + const normalized = value?.trim(); + if (!normalized || normalized === "default") return undefined; + if (!PROFILE_NAME.test(normalized) || normalized.endsWith(".")) return undefined; + return WINDOWS_RESERVED_PROFILE.test(normalized) ? undefined : normalized; +} + +function sessionDirFromLaunchArgs(launchArgs: string | undefined): string | undefined { + const args = tokenizeCliArgs(launchArgs); + for (let index = 0; index < args.length; index += 1) { + const arg = args[index] ?? ""; + if (arg.startsWith("--session-dir=")) { + const value = arg.slice("--session-dir=".length).trim(); + if (value.length > 0) return value; + continue; + } + if (arg === "--session-dir") { + const value = (args[index + 1] ?? "").trim(); + if (value.length > 0 && !value.startsWith("-")) return value; + } + } + return undefined; +} + +/** Declared apart from the reader so tests can exercise store resolution without narrowing a union. */ +export const ompUsageDirectories = Effect.fn("ompUsageReader.directories")(function* (input: { + readonly config: OmpSettings | undefined; + readonly environment: NodeJS.ProcessEnv; +}) { + const { config, environment } = input; + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const home = yield* HostProcess.HomeDirectory; + const platform = yield* HostProcess.Platform; + const resolve = (value: string) => path.resolve(expandHomePath(value, home)); + const exists = (dir: string) => fileSystem.exists(dir).pipe(Effect.orElseSucceed(() => false)); + + // OMP's own precedence: launch flags, session-dir env, profile, agent dir, XDG, then the config root. + const launchSessionDir = sessionDirFromLaunchArgs(config?.launchArgs); + if (launchSessionDir !== undefined) return [{ dir: resolve(launchSessionDir) }]; + const sessionDir = environment.PI_CODING_AGENT_SESSION_DIR?.trim(); + if (sessionDir) return [{ dir: resolve(sessionDir) }]; + + const configRoot = path.join(home, environment.PI_CONFIG_DIR?.trim() || ".omp"); + // `--profile default` on the command line outranks the env, so it must not fall through to OMP_PROFILE. + const launchProfile = ompProfileFromLaunchArgs(config?.launchArgs ?? undefined); + const profile = + launchProfile !== undefined + ? profileName(launchProfile) + : profileName( + environment.OMP_PROFILE !== undefined ? environment.OMP_PROFILE : environment.PI_PROFILE, + ); + // XDG is a linux/macOS convention and applies only once OMP created its XDG root. + const xdgData = + platform === "linux" || platform === "darwin" ? environment.XDG_DATA_HOME?.trim() : undefined; + + if (profile) { + if (xdgData) { + const xdgProfileRoot = path.join(resolve(xdgData), "omp", "profiles", profile); + if (yield* exists(xdgProfileRoot)) return [{ dir: path.join(xdgProfileRoot, "sessions") }]; + } + return [{ dir: path.join(configRoot, "profiles", profile, "agent", "sessions") }]; + } + const agentDir = environment.PI_CODING_AGENT_DIR?.trim(); + if (agentDir) return [{ dir: path.join(resolve(agentDir), "sessions") }]; + if (xdgData) { + const xdgRoot = path.join(resolve(xdgData), "omp"); + if (yield* exists(xdgRoot)) return [{ dir: path.join(xdgRoot, "sessions") }]; + } + return [{ dir: path.join(configRoot, "agent", "sessions") }]; +}); + +export const ompUsageReader: ProviderUsageReader = { + kind: "transcripts", + provider: "omp", + format: ompUsageFormat, + directories: ompUsageDirectories, +}; diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts index b8542c4febb7b..af40762ffd072 100644 --- a/apps/server/src/provider/builtInDrivers.ts +++ b/apps/server/src/provider/builtInDrivers.ts @@ -49,7 +49,8 @@ export type BuiltInUsageReadersEnv = | ProviderUsageReaderEnv | ProviderUsageReaderEnv | ProviderUsageReaderEnv - | ProviderUsageReaderEnv; + | ProviderUsageReaderEnv + | ProviderUsageReaderEnv; /** Order matters: aggregation keeps the first duplicate record. */ export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray< @@ -63,4 +64,5 @@ export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray< MuseDriver, AntigravityDriver, CursorDriver, + OmpDriver, ]; diff --git a/apps/web/src/components/usage/usageProviders.ts b/apps/web/src/components/usage/usageProviders.ts index 408327f3cc203..3a0a67702ebd3 100644 --- a/apps/web/src/components/usage/usageProviders.ts +++ b/apps/web/src/components/usage/usageProviders.ts @@ -45,6 +45,11 @@ export const PROVIDER_PRESENTATION = { color: "#0866ff", driverKind: ProviderDriverKind.make("muse"), }, + omp: { + label: "Oh My Pi", + color: "#f97316", + driverKind: ProviderDriverKind.make("omp"), + }, } satisfies Record; export const PROVIDER_ORDER = Object.keys(PROVIDER_PRESENTATION) as UsageProviderKind[]; diff --git a/docs/user/usage.md b/docs/user/usage.md index e41e60ca73d76..72fb93eeef6c1 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -8,7 +8,7 @@ On mobile, choose **Usage** in the workspace navigation. ## Understand your usage -**Usage** combines Codex, Claude Code, Grok Build, OpenCode, Antigravity, Pi, Muse Code, and Cursor history +**Usage** combines Codex, Claude Code, Grok Build, OpenCode, Antigravity, Pi, Muse Code, Oh My Pi, and Cursor history from your connected environments. It shows token use, cache savings, model breakdowns, and estimated API-equivalent cost, split by token type and by speed. These estimates are not your subscription bill. **Premium** is what Fast and Ultrafast requests cost above standard rates. Cost that cannot be @@ -36,6 +36,12 @@ variable. Pi reads `~/.pi/agent/sessions`, or the `sessions` directory under `PI_CODING_AGENT_DIR`. Set `PI_CODING_AGENT_SESSION_DIR` to read a different session directory. To include sessions saved through `--session-dir` or Pi's `sessionDir` setting, set this environment variable to the same directory. Pi includes recorded tool and summary costs under `Tools/summaries`. +Oh My Pi reads its native session history, including subagent sessions, from `~/.omp/agent/sessions`, +the `sessions` directory under `PI_CODING_AGENT_DIR`, or `$XDG_DATA_HOME/omp/sessions` once its data +has been migrated there. A `--profile` launch argument or `OMP_PROFILE` reads that profile's store, +`PI_CONFIG_DIR` renames the config directory, and `PI_CODING_AGENT_SESSION_DIR` (or a `--session-dir` +launch argument) overrides the session directory. Pointing Pi and Oh My Pi at one store with +`PI_CODING_AGENT_DIR` counts those sessions under both providers. Muse Code reads native session history, including child sessions, from the home reported by the configured Muse CLI. Its environment settings, including `XDG_DATA_HOME`, apply. Models without known prices still contribute tokens and appear as unpriced; set custom prices to estimate their cost. diff --git a/packages/contracts/src/usage.ts b/packages/contracts/src/usage.ts index 8e34c10eb885e..2492a8203e781 100644 --- a/packages/contracts/src/usage.ts +++ b/packages/contracts/src/usage.ts @@ -16,6 +16,8 @@ export const UsageProviderKind = Schema.Literals([ "antigravity", "pi", "muse", + // Fork-local: the Oh My Pi provider. + "omp", ]); export type UsageProviderKind = typeof UsageProviderKind.Type; From 1c3fcc4605e81d6c5f70a523749727967020b76e Mon Sep 17 00:00:00 2001 From: Benjamin Coriou Date: Tue, 27 Oct 2026 21:25:41 +0100 Subject: [PATCH 2/2] chore(fork): mark the Oh My Pi usage touchpoints --- apps/mobile/src/features/usage/usageProviders.ts | 3 +++ apps/server/src/provider/builtInDrivers.ts | 2 ++ apps/web/src/components/usage/usageProviders.ts | 1 + 3 files changed, 6 insertions(+) diff --git a/apps/mobile/src/features/usage/usageProviders.ts b/apps/mobile/src/features/usage/usageProviders.ts index a3db8f6656b81..a83cee8757167 100644 --- a/apps/mobile/src/features/usage/usageProviders.ts +++ b/apps/mobile/src/features/usage/usageProviders.ts @@ -10,6 +10,7 @@ export const PROVIDER_ORDER: readonly UsageProviderKind[] = [ "antigravity", "pi", "muse", + // Fork-local: the Oh My Pi provider. "omp", ]; @@ -27,6 +28,7 @@ export const PROVIDER_LABEL: Record = { antigravity: "Antigravity", pi: "Pi", muse: "Muse Code", + // Fork-local: the Oh My Pi provider. omp: "Oh My Pi", }; @@ -41,6 +43,7 @@ export function useProviderColors(): Record { antigravity: "#8c7bd1", pi: "#4d9f8a", muse: "#0866ff", + // Fork-local: the Oh My Pi provider. omp: "#f97316", }; } diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts index af40762ffd072..48fa2f26b088b 100644 --- a/apps/server/src/provider/builtInDrivers.ts +++ b/apps/server/src/provider/builtInDrivers.ts @@ -50,6 +50,7 @@ export type BuiltInUsageReadersEnv = | ProviderUsageReaderEnv | ProviderUsageReaderEnv | ProviderUsageReaderEnv + // Fork-local: Oh My Pi usage reader. | ProviderUsageReaderEnv; /** Order matters: aggregation keeps the first duplicate record. */ @@ -64,5 +65,6 @@ export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray< MuseDriver, AntigravityDriver, CursorDriver, + // Fork-local: Oh My Pi usage reader. OmpDriver, ]; diff --git a/apps/web/src/components/usage/usageProviders.ts b/apps/web/src/components/usage/usageProviders.ts index 3a0a67702ebd3..7f71de979557d 100644 --- a/apps/web/src/components/usage/usageProviders.ts +++ b/apps/web/src/components/usage/usageProviders.ts @@ -45,6 +45,7 @@ export const PROVIDER_PRESENTATION = { color: "#0866ff", driverKind: ProviderDriverKind.make("muse"), }, + // Fork-local: the Oh My Pi provider. omp: { label: "Oh My Pi", color: "#f97316",