cost-bubble 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -40
- package/bin/cost-bubble.cjs +11 -4
- package/docs/demo.gif +0 -0
- package/install.sh +42 -35
- package/package.json +12 -12
- package/scripts/signed-release.cjs +20 -0
- package/scripts/unpack-release.sh +15 -0
- package/scripts/verify-release-app.sh +16 -0
- package/signed-release.json +5 -0
- package/Info.plist +0 -26
- package/Sources/ChatLine.swift +0 -101
- package/Sources/CostBreakdown.swift +0 -170
- package/Sources/DesktopNavigation.swift +0 -134
- package/Sources/DesktopSurfaces.swift +0 -116
- package/Sources/HUDController.swift +0 -360
- package/Sources/HUDControls.swift +0 -100
- package/Sources/HUDGestures.swift +0 -81
- package/Sources/SessionData.swift +0 -99
- package/Sources/SessionPresentation.swift +0 -74
- package/Sources/SessionUpdates.swift +0 -182
- package/Sources/main.swift +0 -10
- package/build.sh +0 -13
- package/codex_sessions.py +0 -146
- package/local_database.py +0 -37
- package/reviewer_records.py +0 -87
- package/session_cost.py +0 -392
- package/usage_activity.py +0 -189
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import AppKit
|
|
2
|
-
|
|
3
|
-
func preferredWidth() -> CGFloat {
|
|
4
|
-
336
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
func targetX(_ s: Surface, width: CGFloat) -> CGFloat {
|
|
8
|
-
max(s.frame.minX + 6, min(s.sidebarEdge + 6, s.frame.maxX - width - 6)).rounded()
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
struct SessionHelper: Decodable {
|
|
13
|
-
let id: String
|
|
14
|
-
var reviewer: Bool
|
|
15
|
-
var cost: Double?
|
|
16
|
-
var calls: Int?
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
struct SpendDetail: Decodable {
|
|
20
|
-
let average: Double?, peak: Double?, last: Double?
|
|
21
|
-
let unit: String?
|
|
22
|
-
let recent: [[Double]]?
|
|
23
|
-
let helpers: [SessionHelper]?
|
|
24
|
-
|
|
25
|
-
func recentCost(seconds: Double, now: Double) -> Double {
|
|
26
|
-
(recent ?? []).reduce(0) { sum, event in
|
|
27
|
-
guard event.count == 2, event[0] > now-seconds, event[0] <= now, event[1] > 0 else { return sum }
|
|
28
|
-
return sum + event[1]
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
enum SessionPresentation {
|
|
34
|
-
static func compact(_ chats: [RecentChat], now: Double, metrics: (String) -> SpendDetail?) -> [RecentChat] {
|
|
35
|
-
chats.compactMap { chat -> (RecentChat, Double)? in
|
|
36
|
-
let spent = metrics(chat.id)?.recentCost(seconds: 300, now: now) ?? 0
|
|
37
|
-
return spent > 0 ? (chat, spent) : nil
|
|
38
|
-
}.sorted { a,b in
|
|
39
|
-
if a.1 != b.1 { return a.1 > b.1 }
|
|
40
|
-
if a.0.updated != b.0.updated { return (a.0.updated ?? 0) > (b.0.updated ?? 0) }
|
|
41
|
-
return a.0.id < b.0.id
|
|
42
|
-
}.prefix(2).map { $0.0 }
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
static func helpers(_ metadata: [SessionHelper], _ usage: [SessionHelper]) -> [SessionHelper] {
|
|
46
|
-
var byID = [String: SessionHelper]()
|
|
47
|
-
for var item in metadata + usage {
|
|
48
|
-
if let previous = byID[item.id] {
|
|
49
|
-
item.reviewer = previous.reviewer || item.reviewer
|
|
50
|
-
item.cost = item.cost ?? previous.cost
|
|
51
|
-
item.calls = item.calls ?? previous.calls
|
|
52
|
-
}
|
|
53
|
-
byID[item.id] = item
|
|
54
|
-
}
|
|
55
|
-
return byID.values.sorted { $0.id < $1.id }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
static func helperRows(_ all: [SessionHelper]) -> [BreakdownMetric] {
|
|
59
|
-
[false, true].compactMap { reviewer in
|
|
60
|
-
let group = all.filter { $0.reviewer == reviewer }
|
|
61
|
-
guard !group.isEmpty else { return nil }
|
|
62
|
-
let label = (reviewer ? "Auto-review" : "Subagents") + " ×" + String(group.count)
|
|
63
|
-
var parts: [String] = []
|
|
64
|
-
let calls = group.compactMap { $0.calls }
|
|
65
|
-
if calls.count == group.count {
|
|
66
|
-
let number = calls.reduce(0, +)
|
|
67
|
-
parts.append(number.formatted() + (number == 1 ? " call" : " calls"))
|
|
68
|
-
}
|
|
69
|
-
let costs = group.compactMap { $0.cost }
|
|
70
|
-
parts.append(formattedCost(costs.count == group.count ? costs.reduce(0,+) : nil, pending: false))
|
|
71
|
-
return BreakdownMetric(label, parts.joined(separator: " · "))
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
import AppKit
|
|
2
|
-
|
|
3
|
-
extension Controller {
|
|
4
|
-
func setActive(_ next: String?) {
|
|
5
|
-
guard active != next else { return }
|
|
6
|
-
active = next
|
|
7
|
-
revision += 1
|
|
8
|
-
scope = nil
|
|
9
|
-
nextIdentity = .distantPast
|
|
10
|
-
nextList = .distantPast
|
|
11
|
-
recentChats = []
|
|
12
|
-
lockedDetail = nil
|
|
13
|
-
notice = nil
|
|
14
|
-
rowChats = []
|
|
15
|
-
suppressHover = false
|
|
16
|
-
header.isHidden = true
|
|
17
|
-
detailPanel.orderOut(nil)
|
|
18
|
-
panel.orderOut(nil)
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
func updateIdentity(provider: String, route: String, appID: String) {
|
|
22
|
-
let now = Date()
|
|
23
|
-
let generation = revision
|
|
24
|
-
guard pendingIdentity != generation, now >= nextIdentity else { return }
|
|
25
|
-
pendingIdentity = generation
|
|
26
|
-
nextIdentity = now.addingTimeInterval(provider == "claude" ? 3 : 0.7)
|
|
27
|
-
DispatchQueue.global(qos: .userInitiated).async {
|
|
28
|
-
let value: Snapshot? = readSnapshot([provider, route, "--identity"])
|
|
29
|
-
DispatchQueue.main.async {
|
|
30
|
-
guard self.revision == generation else { return }
|
|
31
|
-
self.pendingIdentity = nil
|
|
32
|
-
guard NSWorkspace.shared.frontmostApplication?.bundleIdentifier == appID,
|
|
33
|
-
let id = value?.id, let label = value?.title else {
|
|
34
|
-
self.nextIdentity = Date().addingTimeInterval(0.35)
|
|
35
|
-
self.scope = nil
|
|
36
|
-
self.detailPanel.orderOut(nil)
|
|
37
|
-
self.panel.orderOut(nil)
|
|
38
|
-
return
|
|
39
|
-
}
|
|
40
|
-
if self.scope != id {
|
|
41
|
-
self.navigationTicket += 1
|
|
42
|
-
self.lockedDetail = nil
|
|
43
|
-
self.nextList = .distantPast
|
|
44
|
-
}
|
|
45
|
-
self.scope = id
|
|
46
|
-
self.currentTitle = label
|
|
47
|
-
self.refreshList(provider)
|
|
48
|
-
if !self.panel.isVisible { self.panel.orderFrontRegardless() }
|
|
49
|
-
self.updateHover()
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
func inclusiveReport(_ raw: [String: Usage], provider: String) -> [String: Usage] {
|
|
55
|
-
// Codex and Antigravity expose independent child-session report rows; Claude uses its own catalog.
|
|
56
|
-
guard provider != "claude", let sessions = activity[provider] else { return raw }
|
|
57
|
-
var result = raw
|
|
58
|
-
for (parent, detail) in sessions {
|
|
59
|
-
let children = (detail.helpers ?? []).compactMap { raw[$0.id] }
|
|
60
|
-
guard !children.isEmpty else { continue }
|
|
61
|
-
let own = raw[parent] ?? Usage(cost: nil, ended: nil, calls: nil, inputTokens: nil,
|
|
62
|
-
outputTokens: nil, cacheReadTokens: nil)
|
|
63
|
-
result[parent] = own.including(children)
|
|
64
|
-
}
|
|
65
|
-
return result
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
func applyReports(_ provider: String, lifetime: [String: Usage]?, today: [String: Usage]?,
|
|
69
|
-
overview: [String: SpendDetail]?) {
|
|
70
|
-
if let overview { activity[provider] = overview }
|
|
71
|
-
if let lifetime {
|
|
72
|
-
reports[provider] = inclusiveReport(lifetime, provider: provider)
|
|
73
|
-
} else if reports[provider] == nil { reports[provider] = [:] }
|
|
74
|
-
if let today {
|
|
75
|
-
dailyReports[provider] = inclusiveReport(today, provider: provider)
|
|
76
|
-
} else if !Calendar.current.isDateInToday(reportTime[provider] ?? .distantPast) {
|
|
77
|
-
dailyReports[provider] = [:]
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
func updateReport(_ provider: String) {
|
|
82
|
-
guard !reportPending.contains(provider),
|
|
83
|
-
Date().timeIntervalSince(reportTime[provider] ?? .distantPast) >= 20 else { return }
|
|
84
|
-
reportPending.insert(provider)
|
|
85
|
-
let needsInitialHelpers = activity[provider] == nil
|
|
86
|
-
DispatchQueue.global(qos: .utility).async {
|
|
87
|
-
let report: [String: Usage]? = readSnapshot(["--report", provider])
|
|
88
|
-
var overview: [String: SpendDetail]? = readSnapshot(["--overview", provider])
|
|
89
|
-
if overview == nil && needsInitialHelpers {
|
|
90
|
-
overview = readSnapshot(["--helpers", provider])
|
|
91
|
-
}
|
|
92
|
-
let snapshot = overview
|
|
93
|
-
let daily: [String: Usage]? = readSnapshot(["--today", provider])
|
|
94
|
-
DispatchQueue.main.async {
|
|
95
|
-
self.applyReports(provider, lifetime: report, today: daily, overview: snapshot)
|
|
96
|
-
self.reportPending.remove(provider)
|
|
97
|
-
self.reportTime[provider] = Date()
|
|
98
|
-
if self.activeProvider == provider { self.updateHover() }
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
extension Controller {
|
|
105
|
-
func requestSpend(_ provider: String, chat: RecentChat) -> SpendDetail? {
|
|
106
|
-
let key = provider + "/" + chat.id
|
|
107
|
-
let cached = spending[key]
|
|
108
|
-
guard !spendInFlight, Date().timeIntervalSince(cached?.time ?? .distantPast) >= 20 else { return cached?.value }
|
|
109
|
-
spendInFlight = true
|
|
110
|
-
DispatchQueue.global(qos: .utility).async {
|
|
111
|
-
let value: SpendDetail? = readSnapshot(["--spend", provider, chat.id])
|
|
112
|
-
DispatchQueue.main.async {
|
|
113
|
-
self.spending[key] = (Date(), value ?? cached?.value)
|
|
114
|
-
self.spendInFlight = false
|
|
115
|
-
self.updateHover()
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
return cached?.value
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
func refreshTokenDetails(_ provider: String, chats: [RecentChat]) {
|
|
122
|
-
let now = Date()
|
|
123
|
-
let missing = chats.filter { chat in
|
|
124
|
-
let key = provider + "/" + chat.id
|
|
125
|
-
let age = now.timeIntervalSince(tokenDetails[key]?.time ?? .distantPast)
|
|
126
|
-
return age >= (chat.id == scope ? 12 : 60) && !detailPending.contains(key)
|
|
127
|
-
}
|
|
128
|
-
guard !missing.isEmpty else { return }
|
|
129
|
-
let ids = missing.map(\.id)
|
|
130
|
-
for id in ids { detailPending.insert(provider + "/" + id) }
|
|
131
|
-
DispatchQueue.global(qos: .utility).async {
|
|
132
|
-
let values: [String: TokenDetail]? = readSnapshot(["--details", provider] + ids)
|
|
133
|
-
DispatchQueue.main.async {
|
|
134
|
-
for id in ids {
|
|
135
|
-
let key = provider + "/" + id
|
|
136
|
-
self.detailPending.remove(key)
|
|
137
|
-
self.tokenDetails[key] = (Date(), values?[id] ?? self.tokenDetails[key]?.detail)
|
|
138
|
-
}
|
|
139
|
-
if self.activeProvider == provider { self.updateHover() }
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
func helpers(_ provider: String, _ id: String) -> [SessionHelper] {
|
|
145
|
-
SessionPresentation.helpers(activity[provider]?[id]?.helpers ?? [],
|
|
146
|
-
spending[provider + "/" + id]?.value?.helpers ?? [])
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
func inlineTokens(_ detail: TokenDetail?, helpers: [SessionHelper], loading: Bool) -> String {
|
|
150
|
-
let tokens = detail?.context.map { $0.formatted(.number.notation(.compactName)) } ?? (loading ? "…" : "—")
|
|
151
|
-
let count = helpers.filter { !$0.reviewer }.count
|
|
152
|
-
return count > 0 ? tokens + " · " + String(count) + " sub" : tokens
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
func refreshList(_ provider: String) {
|
|
156
|
-
let generation = revision
|
|
157
|
-
guard Date() >= nextList, pendingList != generation,
|
|
158
|
-
let route = active?.components(separatedBy: "/").last else { return }
|
|
159
|
-
let now = Date().timeIntervalSince1970
|
|
160
|
-
let activeIDs: [String]
|
|
161
|
-
if provider == "claude" {
|
|
162
|
-
activeIDs = (reports[provider] ?? [:]).compactMap { id, usage in
|
|
163
|
-
(usage.ended ?? 0) >= now - 3600 ? id : nil
|
|
164
|
-
}
|
|
165
|
-
} else {
|
|
166
|
-
activeIDs = (activity[provider] ?? [:]).compactMap { id, usage in
|
|
167
|
-
usage.recentCost(seconds: 300, now: now) > 0 ? id : nil
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
pendingList = generation
|
|
171
|
-
DispatchQueue.global(qos: .userInitiated).async {
|
|
172
|
-
let chats: [RecentChat]? = readSnapshot(["--list", provider, route] + activeIDs)
|
|
173
|
-
DispatchQueue.main.async {
|
|
174
|
-
guard self.revision == generation else { return }
|
|
175
|
-
self.pendingList = nil
|
|
176
|
-
self.nextList = Date().addingTimeInterval(chats == nil ? 2 : 10)
|
|
177
|
-
if let chats { self.recentChats = chats }
|
|
178
|
-
self.updateHover()
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
package/Sources/main.swift
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import AppKit
|
|
2
|
-
|
|
3
|
-
if Array(CommandLine.arguments.dropFirst()) == ["--check-bundle"] {
|
|
4
|
-
let checks: [String: Bool]? = readSnapshot(["--check-bundle"])
|
|
5
|
-
exit(checks?["reader"] == true ? 0 : 1)
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
let controller = Controller()
|
|
9
|
-
NSApplication.shared.delegate = controller
|
|
10
|
-
NSApplication.shared.run()
|
package/build.sh
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
#!/bin/bash
|
|
2
|
-
# Build a locally signed, native app using Apple's Command Line Tools.
|
|
3
|
-
set -euo pipefail
|
|
4
|
-
cd "$(dirname "$0")"
|
|
5
|
-
target=${1:?Usage: ./build.sh /absolute/path/Cost Bubble.app}
|
|
6
|
-
[[ "$target" = /* && ! -e "$target" ]] || { echo "Choose a new, absolute output path." >&2; exit 1; }
|
|
7
|
-
[[ "$(uname -s)" == Darwin ]] || { echo "This app requires macOS." >&2; exit 1; }
|
|
8
|
-
mkdir -p "$target/Contents/MacOS" "$target/Contents/Resources"
|
|
9
|
-
xcrun swiftc -O -target "$(uname -m)-apple-macos14.0" Sources/*.swift -o "$target/Contents/MacOS/SessionHUD"
|
|
10
|
-
install -m 644 Info.plist "$target/Contents/Info.plist"
|
|
11
|
-
install -m 644 session_cost.py codex_sessions.py usage_activity.py reviewer_records.py local_database.py "$target/Contents/Resources/"
|
|
12
|
-
codesign --force --sign - "$target"
|
|
13
|
-
codesign --verify --strict "$target"
|
package/codex_sessions.py
DELETED
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
"""Read Codex Desktop's selected local chat and its SQLite metadata."""
|
|
2
|
-
from contextlib import closing
|
|
3
|
-
from datetime import date, datetime, timedelta, timezone
|
|
4
|
-
import json
|
|
5
|
-
import mmap
|
|
6
|
-
import os
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
import re
|
|
9
|
-
import sqlite3
|
|
10
|
-
from urllib.parse import unquote
|
|
11
|
-
from uuid import UUID
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def codex_home():
|
|
15
|
-
return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def selected_id(home, logs):
|
|
19
|
-
marker = b"IAB_LIFECYCLE received browser sidebar owner sync "
|
|
20
|
-
files = []
|
|
21
|
-
days = {base - timedelta(days=i) for base in (date.today(), datetime.now(timezone.utc).date()) for i in range(3)}
|
|
22
|
-
for day in days:
|
|
23
|
-
for path in (logs / day.strftime("%Y/%m/%d")).glob("*-t0-*.log"):
|
|
24
|
-
try:
|
|
25
|
-
files.append((path.stat().st_mtime, path))
|
|
26
|
-
except OSError:
|
|
27
|
-
continue
|
|
28
|
-
latest = None
|
|
29
|
-
latest_time = None
|
|
30
|
-
for modified, path in sorted(files, reverse=True):
|
|
31
|
-
# Older files cannot contain a more recent event. Allow for coarse filesystem clocks.
|
|
32
|
-
if latest_time is not None and modified + 2 < latest_time:
|
|
33
|
-
break
|
|
34
|
-
try:
|
|
35
|
-
with path.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
|
|
36
|
-
end = len(mapped)
|
|
37
|
-
while end:
|
|
38
|
-
pos = mapped.rfind(marker, 0, end)
|
|
39
|
-
if pos < 0:
|
|
40
|
-
break
|
|
41
|
-
stop = mapped.find(b"\n", pos, end)
|
|
42
|
-
route = re.search(rb"\bownerRoutePath=(\S+)", mapped[pos:end if stop < 0 else stop])
|
|
43
|
-
if route:
|
|
44
|
-
start = mapped.rfind(b"\n", 0, pos) + 1
|
|
45
|
-
candidate = (mapped[start:start + 24], route[1].decode("utf-8"))
|
|
46
|
-
if latest is None or candidate[0] > latest[0]:
|
|
47
|
-
latest = candidate
|
|
48
|
-
try:
|
|
49
|
-
latest_time = datetime.fromisoformat(candidate[0].decode("ascii").replace("Z", "+00:00")).timestamp()
|
|
50
|
-
except (ValueError, UnicodeError):
|
|
51
|
-
latest_time = None
|
|
52
|
-
break
|
|
53
|
-
end = pos
|
|
54
|
-
except (OSError, ValueError):
|
|
55
|
-
continue
|
|
56
|
-
if not latest or not latest[1].startswith("/local/"):
|
|
57
|
-
return None
|
|
58
|
-
key = unquote(latest[1][7:].split("?", 1)[0].split("/", 1)[0])
|
|
59
|
-
if key.startswith("client-new-thread:"):
|
|
60
|
-
with closing(sqlite3.connect((home / ".codex-global-state.sqlite").as_uri() + "?mode=ro", uri=True)) as conn:
|
|
61
|
-
row = conn.execute("SELECT value FROM settings WHERE key='client-thread-bindings-v1'").fetchone()
|
|
62
|
-
key = json.loads(row[0]).get(key) if row else None
|
|
63
|
-
try:
|
|
64
|
-
return str(UUID(key)) if isinstance(key, str) else None
|
|
65
|
-
except ValueError:
|
|
66
|
-
return None
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def connect(home):
|
|
70
|
-
databases = sorted(((int(m[1]), p) for p in home.glob("state_*.sqlite")
|
|
71
|
-
if (m := re.fullmatch(r"state_(\d+)\.sqlite", p.name))), reverse=True)
|
|
72
|
-
if not databases:
|
|
73
|
-
raise sqlite3.OperationalError("No Codex state database")
|
|
74
|
-
return sqlite3.connect(databases[0][1].as_uri() + "?mode=ro", uri=True, timeout=0.4)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
def chats(home, session=None, limit=12, extra_ids=()):
|
|
78
|
-
with closing(connect(home)) as conn:
|
|
79
|
-
columns = {row[1] for row in conn.execute("PRAGMA table_info(threads)")}
|
|
80
|
-
title = "coalesce(nullif(name,''),title)" if "name" in columns else "title"
|
|
81
|
-
updated = "coalesce(updated_at_ms/1000,updated_at)" if "updated_at_ms" in columns else "updated_at"
|
|
82
|
-
filters = ["archived=0"]
|
|
83
|
-
args = []
|
|
84
|
-
if session is None:
|
|
85
|
-
if "source" in columns:
|
|
86
|
-
filters.append("""coalesce(source,'') not like '{"subagent"%'""")
|
|
87
|
-
if "model" in columns:
|
|
88
|
-
filters.append("coalesce(model,'') != 'codex-auto-review'")
|
|
89
|
-
if "thread_source" in columns:
|
|
90
|
-
filters.append("coalesce(thread_source,'') not in ('subagent','guardian_review')")
|
|
91
|
-
if "attached_thread_parent_id" in columns:
|
|
92
|
-
filters.append("coalesce(attached_thread_parent_id,'')=''")
|
|
93
|
-
if conn.execute("SELECT 1 FROM sqlite_master WHERE name='thread_spawn_edges'").fetchone():
|
|
94
|
-
filters.append("not exists(select 1 from thread_spawn_edges where child_thread_id=threads.id)")
|
|
95
|
-
else:
|
|
96
|
-
filters.append("id=?")
|
|
97
|
-
args.append(session)
|
|
98
|
-
rows = conn.execute(f"SELECT id,{title},{updated} FROM threads WHERE " + " AND ".join(filters)
|
|
99
|
-
+ f" ORDER BY {updated} DESC,id LIMIT ?", [*args, -1 if extra_ids else limit])
|
|
100
|
-
return [{"id": key, "title": label or "Codex chat", "updated": stamp} for i, (key, label, stamp) in enumerate(rows)
|
|
101
|
-
if i < limit or key in extra_ids]
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
def detail(home, session):
|
|
105
|
-
with closing(connect(home)) as conn:
|
|
106
|
-
row = conn.execute("SELECT rollout_path, model FROM threads WHERE id=?", (session,)).fetchone()
|
|
107
|
-
if not row:
|
|
108
|
-
return {}
|
|
109
|
-
result = {"model": row[1]}
|
|
110
|
-
path = Path(row[0] or "")
|
|
111
|
-
if not path.is_file() or path.suffix != ".jsonl":
|
|
112
|
-
return result
|
|
113
|
-
with path.open("rb") as stream:
|
|
114
|
-
offset = max(0, path.stat().st_size - 4 * 1024 * 1024)
|
|
115
|
-
stream.seek(offset)
|
|
116
|
-
if offset:
|
|
117
|
-
stream.readline()
|
|
118
|
-
turn = window = None
|
|
119
|
-
for line in stream:
|
|
120
|
-
if not any(marker in line for marker in (b'"token_usage_record"', b'"token_count"', b'"task_started"', b'"turn_context"')):
|
|
121
|
-
continue
|
|
122
|
-
try:
|
|
123
|
-
event = json.loads(line)
|
|
124
|
-
payload = event.get("payload") or {}
|
|
125
|
-
kind = event.get("type")
|
|
126
|
-
event_kind = payload.get("type") if kind == "event_msg" else None
|
|
127
|
-
if kind not in ("turn_context", "token_usage_record") and event_kind not in ("task_started", "token_count"):
|
|
128
|
-
continue
|
|
129
|
-
turn_id = payload.get("turn_id")
|
|
130
|
-
if turn_id and turn_id != turn:
|
|
131
|
-
turn, window = turn_id, None
|
|
132
|
-
info = (payload.get("info") or {}) if event_kind == "token_count" else payload
|
|
133
|
-
limit = info.get("model_context_window")
|
|
134
|
-
if type(limit) is int and limit > 0:
|
|
135
|
-
window = limit
|
|
136
|
-
usage = payload.get("usage") if kind == "token_usage_record" else info.get("last_token_usage")
|
|
137
|
-
count = (usage or {}).get("input_tokens")
|
|
138
|
-
if type(count) is int and count >= 0:
|
|
139
|
-
result["context"] = count
|
|
140
|
-
if window:
|
|
141
|
-
result["contextWindow"] = window
|
|
142
|
-
else:
|
|
143
|
-
result.pop("contextWindow", None)
|
|
144
|
-
except (ValueError, AttributeError):
|
|
145
|
-
continue
|
|
146
|
-
return result
|
package/local_database.py
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
"""Read local desktop databases without creating a journal in the provider's directory."""
|
|
2
|
-
from contextlib import contextmanager, closing
|
|
3
|
-
from pathlib import Path
|
|
4
|
-
import shutil
|
|
5
|
-
import sqlite3
|
|
6
|
-
import tempfile
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
@contextmanager
|
|
10
|
-
def read_database(path):
|
|
11
|
-
uri = path.as_uri() + "?mode=ro"
|
|
12
|
-
conn = sqlite3.connect(uri, uri=True, timeout=0.4)
|
|
13
|
-
try:
|
|
14
|
-
conn.execute("pragma schema_version").fetchone()
|
|
15
|
-
except sqlite3.OperationalError:
|
|
16
|
-
conn.close()
|
|
17
|
-
else:
|
|
18
|
-
with closing(conn):
|
|
19
|
-
yield conn
|
|
20
|
-
return
|
|
21
|
-
# SQLite can require a writable SHM file even after a WAL database was checkpointed.
|
|
22
|
-
# Only take a snapshot when the file and its sidecar state stay stable throughout.
|
|
23
|
-
def fingerprint():
|
|
24
|
-
stat = path.stat()
|
|
25
|
-
return (stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
|
|
26
|
-
def has_journal():
|
|
27
|
-
return any(Path(str(path) + suffix).exists() for suffix in ("-wal", "-journal"))
|
|
28
|
-
before = fingerprint()
|
|
29
|
-
if has_journal():
|
|
30
|
-
raise sqlite3.OperationalError("Live database journal is inaccessible")
|
|
31
|
-
with tempfile.TemporaryDirectory() as directory:
|
|
32
|
-
copy = Path(directory) / "snapshot.db"
|
|
33
|
-
shutil.copyfile(path, copy)
|
|
34
|
-
if has_journal() or before != fingerprint():
|
|
35
|
-
raise sqlite3.OperationalError("Database changed while taking a snapshot")
|
|
36
|
-
with closing(sqlite3.connect(copy.as_uri()+"?immutable=1", uri=True)) as snapshot:
|
|
37
|
-
yield snapshot
|
package/reviewer_records.py
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
"""Cache only parent IDs and request counts from Codex's separate reviewer rollouts."""
|
|
2
|
-
from contextlib import contextmanager
|
|
3
|
-
import json
|
|
4
|
-
import os
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
import shutil
|
|
7
|
-
import subprocess
|
|
8
|
-
import tempfile
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
@contextmanager
|
|
12
|
-
def lines(path):
|
|
13
|
-
if path.suffix != ".zst":
|
|
14
|
-
with path.open("rb") as stream:
|
|
15
|
-
yield stream
|
|
16
|
-
return
|
|
17
|
-
binary = shutil.which("zstd")
|
|
18
|
-
if binary:
|
|
19
|
-
command = [binary, "-dc", "--", str(path)]
|
|
20
|
-
else:
|
|
21
|
-
# The installer already verifies a Node version with a streaming Zstandard decoder.
|
|
22
|
-
command = ["node", "-e", "const fs=require('node:fs'),z=require('node:zlib');"
|
|
23
|
-
"require('node:stream').pipeline(fs.createReadStream(process.argv[1]),"
|
|
24
|
-
"z.createZstdDecompress(),process.stdout,e=>{if(e)process.exitCode=1})", str(path)]
|
|
25
|
-
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as process:
|
|
26
|
-
try:
|
|
27
|
-
yield process.stdout
|
|
28
|
-
finally:
|
|
29
|
-
process.stdout.close()
|
|
30
|
-
if process.wait() != 0:
|
|
31
|
-
raise OSError("Compressed reviewer record could not be read")
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
def scan(path, session):
|
|
35
|
-
parent = None
|
|
36
|
-
modern = legacy = 0
|
|
37
|
-
with lines(path) as stream:
|
|
38
|
-
for line in stream:
|
|
39
|
-
if not any(marker in line for marker in (b'"session_meta"', b'"token_usage_record"', b'"token_count"')):
|
|
40
|
-
continue
|
|
41
|
-
try:
|
|
42
|
-
event = json.loads(line)
|
|
43
|
-
except ValueError:
|
|
44
|
-
continue
|
|
45
|
-
payload = event.get("payload") or {}
|
|
46
|
-
if event.get("type") == "session_meta" and (payload.get("id") or payload.get("session_id")) == session:
|
|
47
|
-
parent = payload.get("parent_thread_id") or payload.get("forked_from_id") or parent
|
|
48
|
-
elif event.get("type") == "token_usage_record":
|
|
49
|
-
modern += 1
|
|
50
|
-
elif event.get("type") == "event_msg" and payload.get("type") == "token_count" and payload.get("info"):
|
|
51
|
-
legacy += 1
|
|
52
|
-
return {"parent": parent, "calls": modern or legacy}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
def review_index(paths, cache):
|
|
56
|
-
try:
|
|
57
|
-
previous = json.loads(cache.read_bytes())
|
|
58
|
-
except (ValueError, OSError):
|
|
59
|
-
previous = {}
|
|
60
|
-
result = {}
|
|
61
|
-
for session, name in paths.items():
|
|
62
|
-
path = Path(name)
|
|
63
|
-
if not path.is_file():
|
|
64
|
-
path = Path(name + ".zst")
|
|
65
|
-
try:
|
|
66
|
-
stat = path.stat()
|
|
67
|
-
signature = [stat.st_ino, stat.st_size, stat.st_mtime_ns]
|
|
68
|
-
entry = previous.get(session, {})
|
|
69
|
-
if entry.get("file") != signature:
|
|
70
|
-
scanned = scan(path, session)
|
|
71
|
-
if not scanned.get("parent") and entry.get("parent"):
|
|
72
|
-
result[session] = entry
|
|
73
|
-
continue
|
|
74
|
-
entry = dict(scanned, file=signature)
|
|
75
|
-
result[session] = entry
|
|
76
|
-
except (ValueError, OSError, AttributeError):
|
|
77
|
-
if session in previous:
|
|
78
|
-
result[session] = previous[session]
|
|
79
|
-
if result != previous:
|
|
80
|
-
try:
|
|
81
|
-
cache.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
82
|
-
with tempfile.NamedTemporaryFile(mode="w", dir=cache.parent, delete=False) as stream:
|
|
83
|
-
json.dump(result, stream, separators=(",", ":"))
|
|
84
|
-
os.replace(stream.name, cache)
|
|
85
|
-
except OSError:
|
|
86
|
-
pass
|
|
87
|
-
return result
|