diff-chat 0.1.0__py3-none-any.whl
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.
- adapters/README.md +28 -0
- adapters/__init__.py +48 -0
- adapters/_base.py +102 -0
- adapters/_cli.py +405 -0
- adapters/claude.py +141 -0
- adapters/gemini.py +323 -0
- adapters/gpt.py +217 -0
- adapters/local.py +146 -0
- adapters/registry.py +33 -0
- api_fallback.py +189 -0
- app.py +827 -0
- app_preferences.py +205 -0
- archive_schema.py +142 -0
- attachments.py +129 -0
- chat_titles.py +60 -0
- connection_handoff.py +64 -0
- context_engine.py +256 -0
- conversation_actions.py +160 -0
- diff_chat-0.1.0.dist-info/METADATA +101 -0
- diff_chat-0.1.0.dist-info/RECORD +91 -0
- diff_chat-0.1.0.dist-info/WHEEL +4 -0
- diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
- diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
- diff_chat_assets/memory.example.md +1 -0
- diff_chat_assets/prompts/about_you_export.md +19 -0
- diff_chat_assets/settings.json +6 -0
- diff_chat_assets/static/about-you-parser.js +46 -0
- diff_chat_assets/static/about-you.js +171 -0
- diff_chat_assets/static/actions.css +275 -0
- diff_chat_assets/static/actions.js +650 -0
- diff_chat_assets/static/app.css +345 -0
- diff_chat_assets/static/app.js +1344 -0
- diff_chat_assets/static/attachments.js +80 -0
- diff_chat_assets/static/brand/favicon-32.png +0 -0
- diff_chat_assets/static/brand/icon.svg +11 -0
- diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
- diff_chat_assets/static/brand/wordmark-light.svg +13 -0
- diff_chat_assets/static/characters/CREDITS.md +7 -0
- diff_chat_assets/static/characters/characters.css +37 -0
- diff_chat_assets/static/characters/claude.json +507 -0
- diff_chat_assets/static/characters/claude.png +0 -0
- diff_chat_assets/static/characters/claude.webp +0 -0
- diff_chat_assets/static/characters/gemini.json +54 -0
- diff_chat_assets/static/characters/gemini.png +0 -0
- diff_chat_assets/static/characters/gemini.webp +0 -0
- diff_chat_assets/static/characters/gpt.json +507 -0
- diff_chat_assets/static/characters/gpt.png +0 -0
- diff_chat_assets/static/characters/gpt.webp +0 -0
- diff_chat_assets/static/characters/local.json +387 -0
- diff_chat_assets/static/characters/local.png +0 -0
- diff_chat_assets/static/characters/local.webp +0 -0
- diff_chat_assets/static/characters/player.js +318 -0
- diff_chat_assets/static/chat-filing.js +84 -0
- diff_chat_assets/static/controls.js +194 -0
- diff_chat_assets/static/corners.css +59 -0
- diff_chat_assets/static/craft.css +246 -0
- diff_chat_assets/static/drafts.js +41 -0
- diff_chat_assets/static/index.html +208 -0
- diff_chat_assets/static/library.css +30 -0
- diff_chat_assets/static/library.js +181 -0
- diff_chat_assets/static/memory.js +81 -0
- diff_chat_assets/static/preference-dialog.js +21 -0
- diff_chat_assets/static/preferences.css +56 -0
- diff_chat_assets/static/session.js +46 -0
- diff_chat_assets/static/settings.css +111 -0
- diff_chat_assets/static/settings.js +463 -0
- diff_chat_assets/static/setup.js +238 -0
- diff_chat_assets/static/utility.js +64 -0
- diff_chat_assets/static/vendor/LICENSES.txt +531 -0
- diff_chat_assets/static/vendor/highlight.min.js +1262 -0
- diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
- diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
- diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
- diff_launcher.py +93 -0
- discussion.py +239 -0
- history_search.py +68 -0
- library_manager.py +251 -0
- model_options.py +132 -0
- plan_usage.py +72 -0
- private_store.py +71 -0
- probe.py +195 -0
- runtime_paths.py +195 -0
- server_security.py +100 -0
- setup_status.py +123 -0
- shared_memory.py +189 -0
- storage.py +185 -0
- usage_budget.py +77 -0
- usage_claude.py +110 -0
- usage_codex.py +170 -0
- usage_gemini.py +70 -0
- utility_models.py +104 -0
shared_memory.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""User-edited notes for participants, scoped to one chat or all chats."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from threading import Lock
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from fastapi import APIRouter, HTTPException
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
12
|
+
import private_store
|
|
13
|
+
import storage
|
|
14
|
+
|
|
15
|
+
router = APIRouter()
|
|
16
|
+
|
|
17
|
+
_global_lock = Lock()
|
|
18
|
+
MEMORY_LIMIT = 4000
|
|
19
|
+
IMPORT_START = "<!-- diff:about-you -->"
|
|
20
|
+
IMPORT_END = "<!-- /diff:about-you -->"
|
|
21
|
+
IMPORT_BLOCK = re.compile("^" + re.escape(IMPORT_START) + r"$.*?^" + re.escape(IMPORT_END) + r"$", re.M | re.S)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def global_note():
|
|
25
|
+
path = storage.CHAT_DIR / ".preferences" / "memory.md"
|
|
26
|
+
try:
|
|
27
|
+
return path.read_text(encoding="utf-8")
|
|
28
|
+
except FileNotFoundError:
|
|
29
|
+
return private_store.read("memory", "")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def save_global(text, revision):
|
|
33
|
+
with _global_lock:
|
|
34
|
+
if private_store.snapshot(global_note())["revision"] != revision:
|
|
35
|
+
raise HTTPException(409, "Memory changed in another window. Reopen it to load the latest text.")
|
|
36
|
+
directory = storage.CHAT_DIR / ".preferences"
|
|
37
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
38
|
+
with tempfile.NamedTemporaryFile(dir=directory, mode="w", encoding="utf-8", delete=False) as file:
|
|
39
|
+
temp = Path(file.name)
|
|
40
|
+
try:
|
|
41
|
+
file.write(text)
|
|
42
|
+
file.flush()
|
|
43
|
+
os.fsync(file.fileno())
|
|
44
|
+
except BaseException:
|
|
45
|
+
temp.unlink(missing_ok=True)
|
|
46
|
+
raise
|
|
47
|
+
try:
|
|
48
|
+
os.replace(temp, directory / "memory.md")
|
|
49
|
+
finally:
|
|
50
|
+
temp.unlink(missing_ok=True)
|
|
51
|
+
(directory / "memory.json").unlink(missing_ok=True)
|
|
52
|
+
return private_store.snapshot(text)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def context(chat):
|
|
56
|
+
notes = {}
|
|
57
|
+
for scope, key in (("All chats", "memory"), ("This chat", "memory-" + chat["id"])):
|
|
58
|
+
value = global_note() if scope == "All chats" else private_store.read(key, "")
|
|
59
|
+
if scope == "All chats" and value:
|
|
60
|
+
value = "\n".join(line for line in value.split("\n") if line not in {IMPORT_START, IMPORT_END})
|
|
61
|
+
if value:
|
|
62
|
+
notes[scope] = value
|
|
63
|
+
if not notes:
|
|
64
|
+
return ""
|
|
65
|
+
return ("[User-maintained shared notes. Use as background for the conversation. "
|
|
66
|
+
"More recent user messages take precedence.]\n" + json.dumps(notes, ensure_ascii=False))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _require_chat(chat_id):
|
|
70
|
+
try:
|
|
71
|
+
return storage.read(chat_id)
|
|
72
|
+
except FileNotFoundError:
|
|
73
|
+
raise HTTPException(404, "Chat not found.")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class MemoryEdit(BaseModel):
|
|
77
|
+
scope: Literal["chat", "all"]
|
|
78
|
+
text: str = Field(max_length=MEMORY_LIMIT)
|
|
79
|
+
revision: str = Field(min_length=64, max_length=64)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class FactGroup(BaseModel):
|
|
83
|
+
heading: str = ""
|
|
84
|
+
facts: list[str] = Field(min_length=1)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ProfileImport(BaseModel):
|
|
88
|
+
groups: list[FactGroup] = Field(min_length=1)
|
|
89
|
+
revision: str = Field(min_length=64, max_length=64)
|
|
90
|
+
replace: bool = False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def import_parts(text):
|
|
94
|
+
blocks = list(IMPORT_BLOCK.finditer(text))
|
|
95
|
+
markers = [line for line in text.splitlines() if line in {IMPORT_START, IMPORT_END}]
|
|
96
|
+
if markers and (markers != [IMPORT_START, IMPORT_END] or len(blocks) != 1):
|
|
97
|
+
raise HTTPException(409, "The import markers in memory.md were edited. Fix or remove the marker lines before importing.")
|
|
98
|
+
if blocks:
|
|
99
|
+
block = blocks[0]
|
|
100
|
+
return text[:block.start()], text[block.end():], True
|
|
101
|
+
separator = "" if not text or text.endswith("\n\n") else "\n" if text.endswith("\n") else "\n\n"
|
|
102
|
+
return text + separator, "", False
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def import_layout(text):
|
|
106
|
+
before, after, replacing = import_parts(text)
|
|
107
|
+
return before + IMPORT_START + "\n## About me\n", "\n" + IMPORT_END + after, replacing
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@router.get("/api/settings/memory/import")
|
|
111
|
+
def import_details():
|
|
112
|
+
text = global_note()
|
|
113
|
+
prefix, suffix, replacing = import_layout(text)
|
|
114
|
+
prompt = (storage.ROOT / "prompts" / "about_you_export.md").read_text(encoding="utf-8").rstrip("\n")
|
|
115
|
+
return {"prompt": prompt, "revision": private_store.snapshot(text)["revision"], "replace": replacing,
|
|
116
|
+
"limit": MEMORY_LIMIT, "fixed_chars": len(prefix) + len(suffix)}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def single_line(value):
|
|
120
|
+
value = value.strip()
|
|
121
|
+
if len(value.splitlines()) > 1 or any(ord(c) < 32 or 0xD800 <= ord(c) <= 0xDFFF for c in value):
|
|
122
|
+
raise HTTPException(400, "Keep each heading and fact on a single line.")
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@router.post("/api/settings/memory/import")
|
|
127
|
+
def import_profile(change: ProfileImport):
|
|
128
|
+
text = global_note()
|
|
129
|
+
if private_store.snapshot(text)["revision"] != change.revision:
|
|
130
|
+
raise HTTPException(409, "Shared memory changed in another window. Review the updated size before saving.")
|
|
131
|
+
prefix, suffix, replacing = import_layout(text)
|
|
132
|
+
if replacing and not change.replace:
|
|
133
|
+
raise HTTPException(409, "Confirm replacement of the previous import.")
|
|
134
|
+
groups = []
|
|
135
|
+
for group in change.groups:
|
|
136
|
+
heading = single_line(group.heading)
|
|
137
|
+
facts = [single_line(value) for value in group.facts]
|
|
138
|
+
if not all(facts):
|
|
139
|
+
raise HTTPException(400, "Edit or untick each empty fact.")
|
|
140
|
+
lines = ["### " + heading] if heading else []
|
|
141
|
+
groups.append("\n".join(lines + ["- " + fact for fact in facts]))
|
|
142
|
+
result = prefix + "\n" + "\n\n".join(groups) + suffix
|
|
143
|
+
if len(result) > MEMORY_LIMIT:
|
|
144
|
+
raise HTTPException(400, f"Trim {len(result) - MEMORY_LIMIT:,} characters before saving.")
|
|
145
|
+
return save_global(result, change.revision)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@router.get("/api/chats/{chat_id}/memory")
|
|
149
|
+
def get_memory(chat_id: str):
|
|
150
|
+
chat = _require_chat(chat_id)
|
|
151
|
+
return {"chat": private_store.snapshot(private_store.read("memory-" + chat_id, "")),
|
|
152
|
+
"all": private_store.snapshot(global_note()),
|
|
153
|
+
"summary": chat.get("context_summary")}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@router.patch("/api/chats/{chat_id}/memory")
|
|
157
|
+
def save_memory(chat_id: str, change: MemoryEdit):
|
|
158
|
+
_require_chat(chat_id)
|
|
159
|
+
key = "memory-" + chat_id if change.scope == "chat" else "memory"
|
|
160
|
+
if any(0xD800 <= ord(c) <= 0xDFFF for c in change.text):
|
|
161
|
+
raise HTTPException(400, "The note contains an invalid character.")
|
|
162
|
+
if change.scope == "all":
|
|
163
|
+
return save_global(change.text.strip(), change.revision)
|
|
164
|
+
return private_store.update(key, change.text.strip(), "", change.revision)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@router.post("/api/settings/memory/clear")
|
|
168
|
+
def clear_memory(confirm: dict):
|
|
169
|
+
if confirm.get("confirmation") != "CLEAR MEMORY":
|
|
170
|
+
raise HTTPException(400, "Confirm before clearing all shared and chat-specific notes.")
|
|
171
|
+
directory = storage.CHAT_DIR / ".preferences"
|
|
172
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
173
|
+
# Lock both scopes while staging the files, so another editor cannot
|
|
174
|
+
# rewrite a note between the directory scan and the clear operation.
|
|
175
|
+
with _global_lock, private_store._edit, tempfile.TemporaryDirectory(dir=directory) as staging:
|
|
176
|
+
candidates = [directory / name for name in ("memory.md", "memory.json")]
|
|
177
|
+
candidates.extend(p for p in directory.glob("memory-*.json") if
|
|
178
|
+
len(p.stem) == 39 and all(char in "0123456789abcdef" for char in p.stem[7:]))
|
|
179
|
+
moved = []
|
|
180
|
+
try:
|
|
181
|
+
for path in candidates:
|
|
182
|
+
if path.exists():
|
|
183
|
+
os.replace(path, Path(staging) / path.name)
|
|
184
|
+
moved.append(path)
|
|
185
|
+
except OSError:
|
|
186
|
+
for path in moved:
|
|
187
|
+
os.replace(Path(staging) / path.name, path)
|
|
188
|
+
raise
|
|
189
|
+
return private_store.snapshot("")
|
storage.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Local, atomic JSON storage and the plain transcript sent to each participant."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
import unicodedata
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
import chat_titles
|
|
11
|
+
from adapters import REGISTRY
|
|
12
|
+
from attachments import display_message, text_for_attachment
|
|
13
|
+
from runtime_paths import RESOURCE_ROOT, data_root
|
|
14
|
+
|
|
15
|
+
ROOT = RESOURCE_ROOT
|
|
16
|
+
CHAT_DIR = data_root(ROOT) / "chats"
|
|
17
|
+
SPEAKERS = {"me": "User", **{key: adapter.label for key, adapter in REGISTRY.items()}}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def now():
|
|
21
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def clean_name(value):
|
|
25
|
+
if not isinstance(value, str):
|
|
26
|
+
return ""
|
|
27
|
+
name = unicodedata.normalize("NFC", value.strip())
|
|
28
|
+
if (not 1 <= len(name) <= 60 or not any(c.isalnum() for c in name)
|
|
29
|
+
or not all(c.isalnum() or unicodedata.category(c).startswith("M") or c in " ._-'’" for c in name)):
|
|
30
|
+
return ""
|
|
31
|
+
return name
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def display_name():
|
|
35
|
+
import private_store
|
|
36
|
+
stored = private_store.read("application", {}).get("display_name", SETTINGS["display_name"])
|
|
37
|
+
name = clean_name(stored)
|
|
38
|
+
return name if name and name.casefold() != "you" else "you"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def transcript(messages):
|
|
42
|
+
name = display_name()
|
|
43
|
+
lines = []
|
|
44
|
+
for message in messages:
|
|
45
|
+
role = SPEAKERS[message["speaker"]]
|
|
46
|
+
if message["speaker"] == "me" and name != "you":
|
|
47
|
+
role = f"User ({name})"
|
|
48
|
+
body = message["text"]
|
|
49
|
+
for item in message.get("attachments", []):
|
|
50
|
+
body += "\n\n" + text_for_attachment(item)
|
|
51
|
+
if message.get("mode") == "synthesis":
|
|
52
|
+
body = f"[Synthesis by {role}]\n" + body
|
|
53
|
+
elif message.get("mode") == "stress":
|
|
54
|
+
phase = message.get("phase") or ("critique" if message["speaker"] == next(iter(REGISTRY)) else "evaluation")
|
|
55
|
+
body = f"[Pressure test, {phase}]\n" + body
|
|
56
|
+
for source in message.get("sources", []):
|
|
57
|
+
url = source.get("url") if isinstance(source, dict) else None
|
|
58
|
+
if isinstance(url, str) and url not in body:
|
|
59
|
+
title = source.get("title")
|
|
60
|
+
title = " ".join(title.split()) if isinstance(title, str) else ""
|
|
61
|
+
body += f"\nSource: {title} — {url}" if title else "\n" + url
|
|
62
|
+
if message.get("error"):
|
|
63
|
+
body = (body + "\n" if body else "") + "[Reply incomplete.]"
|
|
64
|
+
lines.append(f"{role}: {body}")
|
|
65
|
+
return "\n\n".join(lines)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def turn_starts(messages):
|
|
69
|
+
"""Legacy chats lack action IDs. Recover groups from discussion IDs and speaker order."""
|
|
70
|
+
starts = []
|
|
71
|
+
previous = None
|
|
72
|
+
seen = set()
|
|
73
|
+
for index, item in enumerate(messages):
|
|
74
|
+
speaker = item["speaker"]
|
|
75
|
+
key = item.get("turn_id") or item.get("discussion_id")
|
|
76
|
+
if (index == 0 or key != previous or (key is None and
|
|
77
|
+
(speaker == "me" or speaker in seen or item.get("mode") == "synthesis"))):
|
|
78
|
+
starts.append(index)
|
|
79
|
+
seen.clear()
|
|
80
|
+
seen.add(speaker)
|
|
81
|
+
previous = key
|
|
82
|
+
return starts
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def load_settings():
|
|
86
|
+
private = data_root(ROOT)
|
|
87
|
+
settings = private / "settings.json"
|
|
88
|
+
if not settings.is_file():
|
|
89
|
+
settings = ROOT / "settings.json"
|
|
90
|
+
values = json.loads(settings.read_text(encoding="utf-8"))
|
|
91
|
+
for name in ("timeout_seconds", "summary_threshold"):
|
|
92
|
+
if type(values.get(name)) is not int or values[name] < 1:
|
|
93
|
+
raise ValueError(f"settings.json requires a positive integer for {name}")
|
|
94
|
+
# A private, machine-local label can override the shareable default.
|
|
95
|
+
name = values.get("display_name", "you")
|
|
96
|
+
try:
|
|
97
|
+
local = json.loads((private / "settings.local.json").read_text(encoding="utf-8"))
|
|
98
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
99
|
+
local = {}
|
|
100
|
+
if isinstance(local, dict):
|
|
101
|
+
name = local.get("display_name", name)
|
|
102
|
+
name = clean_name(name) or "you"
|
|
103
|
+
rolling = values.get("rolling_threshold", 40_000)
|
|
104
|
+
if type(rolling) is not int or rolling < 1:
|
|
105
|
+
raise ValueError("settings.json requires a positive integer for rolling_threshold")
|
|
106
|
+
return {"timeout_seconds": values["timeout_seconds"], "summary_threshold": values["summary_threshold"],
|
|
107
|
+
"rolling_threshold": rolling,
|
|
108
|
+
"display_name": name}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
SETTINGS = load_settings()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def new_chat(title="New chat", messages=None):
|
|
115
|
+
import app_preferences
|
|
116
|
+
defaults = app_preferences.get()
|
|
117
|
+
choices = {p: {k: defaults[p][k] for k in ("model", "effort")} for p in REGISTRY if defaults[p]["model"]}
|
|
118
|
+
return {"id": uuid4().hex, "title": title, "updated_at": now(), "messages": messages or [],
|
|
119
|
+
"preferences": choices, "web_search": defaults["web_search"], "sessions": {},
|
|
120
|
+
"roles": {p: defaults[p]["role"] for p in REGISTRY},
|
|
121
|
+
"stats": {"turns": 0, "chars_sent": 0, "legacy": False}}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def save(chat, *, preserve_timestamp=False):
|
|
125
|
+
CHAT_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
126
|
+
timestamp = (chat.get("updated_at") or now()) if preserve_timestamp else now()
|
|
127
|
+
chat["title"] = chat_titles.for_chat(chat)
|
|
128
|
+
data = {**chat, "updated_at": timestamp}
|
|
129
|
+
with tempfile.NamedTemporaryFile(mode="w", prefix=".saving-", dir=CHAT_DIR,
|
|
130
|
+
encoding="utf-8", delete=False) as handle:
|
|
131
|
+
path = Path(handle.name)
|
|
132
|
+
try:
|
|
133
|
+
json.dump(data, handle, ensure_ascii=False, indent=2)
|
|
134
|
+
handle.write("\n")
|
|
135
|
+
handle.flush()
|
|
136
|
+
os.fsync(handle.fileno())
|
|
137
|
+
except BaseException:
|
|
138
|
+
path.unlink(missing_ok=True)
|
|
139
|
+
raise
|
|
140
|
+
try:
|
|
141
|
+
os.replace(path, CHAT_DIR / (chat["id"] + ".json"))
|
|
142
|
+
finally:
|
|
143
|
+
path.unlink(missing_ok=True)
|
|
144
|
+
chat["updated_at"] = data["updated_at"]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def read(chat_id):
|
|
148
|
+
if len(chat_id) != 32 or any(char not in "0123456789abcdef" for char in chat_id):
|
|
149
|
+
raise FileNotFoundError
|
|
150
|
+
data = json.loads((CHAT_DIR / (chat_id + ".json")).read_text(encoding="utf-8"))
|
|
151
|
+
if (not isinstance(data, dict) or data.get("id") != chat_id or not isinstance(data.get("title"), str)
|
|
152
|
+
or not isinstance(data.get("updated_at"), str) or not isinstance(data.get("messages"), list)):
|
|
153
|
+
raise ValueError("Invalid chat record")
|
|
154
|
+
for entry in data["messages"]:
|
|
155
|
+
if (not isinstance(entry, dict) or entry.get("speaker") not in SPEAKERS
|
|
156
|
+
or not isinstance(entry.get("text"), str)):
|
|
157
|
+
raise ValueError("Invalid message record")
|
|
158
|
+
data["title"] = chat_titles.for_chat(data)
|
|
159
|
+
if not isinstance(data.get("sessions"), dict):
|
|
160
|
+
data["sessions"] = {}
|
|
161
|
+
if not isinstance(data.get("stats"), dict) or any(
|
|
162
|
+
type(data["stats"].get(key)) is not int or data["stats"][key] < 0 for key in ("turns", "chars_sent")
|
|
163
|
+
):
|
|
164
|
+
data["stats"] = {"turns": len(turn_starts(data["messages"])), "chars_sent": 0, "legacy": bool(data["messages"])}
|
|
165
|
+
return data
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def view(chat):
|
|
169
|
+
public = {key: value for key, value in chat.items() if key != "sessions"}
|
|
170
|
+
return {**public, "messages": [display_message(m) for m in chat["messages"]], "preferences": chat.get("preferences", {}), "web_search": chat.get("web_search", True),
|
|
171
|
+
"discussions": chat.get("discussions", []), "chars": len(transcript(chat["messages"]))}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def list_chats():
|
|
175
|
+
result = []
|
|
176
|
+
for path in CHAT_DIR.glob("*.json"):
|
|
177
|
+
try:
|
|
178
|
+
chat = view(read(path.stem))
|
|
179
|
+
result.append({**{key: chat[key] for key in ("id", "title", "updated_at", "chars")},
|
|
180
|
+
"pinned": bool(chat.get("pinned"))})
|
|
181
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
182
|
+
# Keep other chats accessible and leave the original file available for repair.
|
|
183
|
+
result.append({"id": path.stem, "title": f"Unreadable chat ({path.stem[:8]})",
|
|
184
|
+
"updated_at": "", "chars": -1})
|
|
185
|
+
return sorted(result, key=lambda item: item["updated_at"], reverse=True)
|
usage_budget.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Estimate a plan action from observed same-window meter changes per completed reply."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from statistics import median
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, HTTPException
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
import app_preferences
|
|
9
|
+
import private_store
|
|
10
|
+
|
|
11
|
+
router = APIRouter()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def modify(provider, transform):
|
|
15
|
+
key = "usage-samples-" + provider
|
|
16
|
+
old = private_store.read(key, {})
|
|
17
|
+
new = transform(dict(old))
|
|
18
|
+
if new != old:
|
|
19
|
+
try:
|
|
20
|
+
private_store.update(key, new, {}, private_store.snapshot(old)["revision"])
|
|
21
|
+
except (OSError, HTTPException):
|
|
22
|
+
# A quota estimate is optional; the conversation still finishes if it cannot be saved.
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def completed(providers):
|
|
27
|
+
for provider in set(providers):
|
|
28
|
+
def advance(record):
|
|
29
|
+
record["replies"] = record.get("replies", 0) + providers.count(provider)
|
|
30
|
+
return record
|
|
31
|
+
modify(provider, advance)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def observe(provider, data):
|
|
35
|
+
window = next((w for w in data.get("windows", []) if w["label"].startswith("5-hour")), None)
|
|
36
|
+
if not window or not window.get("reset_at"):
|
|
37
|
+
return
|
|
38
|
+
def update(record):
|
|
39
|
+
remaining = window["remaining_percent"]
|
|
40
|
+
same = record.get("window") == window["reset_at"]
|
|
41
|
+
count = record.get("replies", 0)
|
|
42
|
+
used = record.get("remaining", remaining) - remaining
|
|
43
|
+
if same and used == 0:
|
|
44
|
+
return record
|
|
45
|
+
samples = record.get("samples", [])
|
|
46
|
+
if same and count and used > 0:
|
|
47
|
+
samples = (samples + [used / count])[-12:]
|
|
48
|
+
return {"remaining": remaining, "window": window["reset_at"], "replies": 0, "samples": samples}
|
|
49
|
+
modify(provider, update)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Estimate(BaseModel):
|
|
53
|
+
replies: list[app_preferences.Provider] = Field(max_length=6 * len(app_preferences.REGISTRY))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@router.post("/api/usage/estimate")
|
|
57
|
+
async def estimate(request: Estimate):
|
|
58
|
+
from plan_usage import read_provider
|
|
59
|
+
threshold = app_preferences.get()["usage_warning"]
|
|
60
|
+
warnings = []
|
|
61
|
+
if threshold > 0:
|
|
62
|
+
providers = sorted(set(request.replies))
|
|
63
|
+
results = await asyncio.gather(*(read_provider(p, False) for p in providers))
|
|
64
|
+
for provider, result in zip(providers, results):
|
|
65
|
+
window = next((w for w in result.get("windows", []) if w["label"].startswith("5-hour")), None)
|
|
66
|
+
if not window:
|
|
67
|
+
continue
|
|
68
|
+
remaining = window["remaining_percent"]
|
|
69
|
+
record = private_store.read("usage-samples-" + provider, {})
|
|
70
|
+
samples = record.get("samples", [])
|
|
71
|
+
if remaining <= 0:
|
|
72
|
+
warnings.append({"provider": provider, "remaining": 0, "fraction": None})
|
|
73
|
+
elif samples:
|
|
74
|
+
fraction = median(samples) * request.replies.count(provider) * 100 / remaining
|
|
75
|
+
if fraction >= threshold:
|
|
76
|
+
warnings.append({"provider": provider, "remaining": remaining, "fraction": round(fraction, 1)})
|
|
77
|
+
return {"warnings": warnings}
|
usage_claude.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Read Claude plan windows through the pinned CLI's get_usage control request."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import tempfile
|
|
8
|
+
|
|
9
|
+
from adapters import CLAUDE_CONTROL, ModelError, VERSIONS, _check_login, _environment, _Invocation
|
|
10
|
+
from probe import find_cli
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
WINDOW_NAMES = {
|
|
14
|
+
"five_hour": "5-hour limit",
|
|
15
|
+
"seven_day": "Weekly limit",
|
|
16
|
+
"seven_day_opus": "Weekly · Opus",
|
|
17
|
+
"seven_day_sonnet": "Weekly · Sonnet",
|
|
18
|
+
"seven_day_oauth_apps": "Weekly · OAuth apps",
|
|
19
|
+
"seven_day_cowork": "Weekly · Cowork",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _result(windows, detail=None):
|
|
24
|
+
return {"status": "available" if windows else "unavailable", "windows": windows,
|
|
25
|
+
"detail": detail, "checked_at": datetime.now(timezone.utc).isoformat()}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _reset_iso(value):
|
|
29
|
+
try:
|
|
30
|
+
stamp = datetime.fromisoformat(value) if isinstance(value, str) else None
|
|
31
|
+
if stamp is None and type(value) in (int, float):
|
|
32
|
+
stamp = datetime.fromtimestamp(value, tz=timezone.utc)
|
|
33
|
+
if stamp is not None and stamp.tzinfo is not None:
|
|
34
|
+
return stamp.astimezone(timezone.utc).isoformat()
|
|
35
|
+
except (ValueError, OverflowError, OSError):
|
|
36
|
+
pass
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _read_windows(report):
|
|
41
|
+
limits = report.get("rate_limits")
|
|
42
|
+
if not isinstance(limits, dict):
|
|
43
|
+
return []
|
|
44
|
+
rows = [(label, limits.get(key)) for key, label in WINDOW_NAMES.items()]
|
|
45
|
+
extra = limits.get("model_scoped")
|
|
46
|
+
if isinstance(extra, list):
|
|
47
|
+
for model in extra:
|
|
48
|
+
if isinstance(model, dict) and isinstance(model.get("display_name"), str):
|
|
49
|
+
label = model["display_name"].strip()
|
|
50
|
+
if label:
|
|
51
|
+
rows.append((f"Weekly · {label}", model))
|
|
52
|
+
windows = []
|
|
53
|
+
seen = set()
|
|
54
|
+
for label, row in rows:
|
|
55
|
+
if not isinstance(row, dict) or label.casefold() in seen:
|
|
56
|
+
continue
|
|
57
|
+
used = row.get("utilization")
|
|
58
|
+
if type(used) not in (float, int) or not math.isfinite(used) or used < 0:
|
|
59
|
+
continue
|
|
60
|
+
seen.add(label.casefold())
|
|
61
|
+
windows.append({"label": label, "remaining_percent": round(max(0.0, 100.0 - used), 2),
|
|
62
|
+
"reset_at": _reset_iso(row.get("resets_at"))})
|
|
63
|
+
return windows
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def get_claude_usage():
|
|
67
|
+
binary = find_cli("claude")
|
|
68
|
+
if not binary:
|
|
69
|
+
return _result([], "Install Claude Code to check its subscription limits.")
|
|
70
|
+
try:
|
|
71
|
+
async with asyncio.timeout(12):
|
|
72
|
+
with tempfile.TemporaryDirectory(prefix="transcript-claude-usage-") as td:
|
|
73
|
+
root = Path(td)
|
|
74
|
+
cwd = root / "workspace"
|
|
75
|
+
cwd.mkdir()
|
|
76
|
+
call = _Invocation(binary, cwd, _environment(root, "claude"))
|
|
77
|
+
code, version = await call.execute(["--version"])
|
|
78
|
+
if code or version.decode(errors="replace").strip() != VERSIONS["claude"]:
|
|
79
|
+
return _result([], "Subscription usage requires the app’s verified Claude Code version.")
|
|
80
|
+
await _check_login(call, "claude")
|
|
81
|
+
# This aggregate switch also suppresses the requested account-usage fetch.
|
|
82
|
+
# Keep telemetry and error reporting off while allowing the CLI to fetch it.
|
|
83
|
+
call.env.pop("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", None)
|
|
84
|
+
call.env.update(DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1")
|
|
85
|
+
args = [*CLAUDE_CONTROL, "-p", "--input-format", "stream-json",
|
|
86
|
+
"--output-format", "stream-json", "--verbose", "--tools", "",
|
|
87
|
+
"--permission-mode", "dontAsk", "--no-session-persistence",
|
|
88
|
+
"--no-chrome", "--disable-slash-commands", "--strict-mcp-config",
|
|
89
|
+
"--mcp-config", '{"mcpServers":{}}']
|
|
90
|
+
# A control message alone runs no inference. skip_behaviors also tells the
|
|
91
|
+
# CLI to omit its local transcript analysis when preparing the usage report.
|
|
92
|
+
request = {"type": "control_request", "request_id": "plan-usage",
|
|
93
|
+
"request": {"subtype": "get_usage", "skip_behaviors": True}}
|
|
94
|
+
code, output = await call.execute(args, json.dumps(request) + "\n")
|
|
95
|
+
if not code:
|
|
96
|
+
for line in output.splitlines():
|
|
97
|
+
event = json.loads(line)
|
|
98
|
+
reply = event.get("response") or {}
|
|
99
|
+
if (event.get("type") == "control_response" and reply.get("request_id") == "plan-usage"
|
|
100
|
+
and reply.get("subtype") == "success" and isinstance(reply.get("response"), dict)):
|
|
101
|
+
windows = _read_windows(reply["response"])
|
|
102
|
+
if windows:
|
|
103
|
+
return _result(windows)
|
|
104
|
+
return _result([], "Claude Code returned no subscription limits. Try refreshing later.")
|
|
105
|
+
except ModelError as error:
|
|
106
|
+
return _result([], error.message)
|
|
107
|
+
except TimeoutError:
|
|
108
|
+
return _result([], "Claude Code timed out while checking subscription usage.")
|
|
109
|
+
except (OSError, ValueError, ExceptionGroup):
|
|
110
|
+
return _result([], "Could not read usage from Claude Code. Try refreshing later.")
|