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.
Files changed (91) hide show
  1. adapters/README.md +28 -0
  2. adapters/__init__.py +48 -0
  3. adapters/_base.py +102 -0
  4. adapters/_cli.py +405 -0
  5. adapters/claude.py +141 -0
  6. adapters/gemini.py +323 -0
  7. adapters/gpt.py +217 -0
  8. adapters/local.py +146 -0
  9. adapters/registry.py +33 -0
  10. api_fallback.py +189 -0
  11. app.py +827 -0
  12. app_preferences.py +205 -0
  13. archive_schema.py +142 -0
  14. attachments.py +129 -0
  15. chat_titles.py +60 -0
  16. connection_handoff.py +64 -0
  17. context_engine.py +256 -0
  18. conversation_actions.py +160 -0
  19. diff_chat-0.1.0.dist-info/METADATA +101 -0
  20. diff_chat-0.1.0.dist-info/RECORD +91 -0
  21. diff_chat-0.1.0.dist-info/WHEEL +4 -0
  22. diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
  23. diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
  24. diff_chat_assets/memory.example.md +1 -0
  25. diff_chat_assets/prompts/about_you_export.md +19 -0
  26. diff_chat_assets/settings.json +6 -0
  27. diff_chat_assets/static/about-you-parser.js +46 -0
  28. diff_chat_assets/static/about-you.js +171 -0
  29. diff_chat_assets/static/actions.css +275 -0
  30. diff_chat_assets/static/actions.js +650 -0
  31. diff_chat_assets/static/app.css +345 -0
  32. diff_chat_assets/static/app.js +1344 -0
  33. diff_chat_assets/static/attachments.js +80 -0
  34. diff_chat_assets/static/brand/favicon-32.png +0 -0
  35. diff_chat_assets/static/brand/icon.svg +11 -0
  36. diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
  37. diff_chat_assets/static/brand/wordmark-light.svg +13 -0
  38. diff_chat_assets/static/characters/CREDITS.md +7 -0
  39. diff_chat_assets/static/characters/characters.css +37 -0
  40. diff_chat_assets/static/characters/claude.json +507 -0
  41. diff_chat_assets/static/characters/claude.png +0 -0
  42. diff_chat_assets/static/characters/claude.webp +0 -0
  43. diff_chat_assets/static/characters/gemini.json +54 -0
  44. diff_chat_assets/static/characters/gemini.png +0 -0
  45. diff_chat_assets/static/characters/gemini.webp +0 -0
  46. diff_chat_assets/static/characters/gpt.json +507 -0
  47. diff_chat_assets/static/characters/gpt.png +0 -0
  48. diff_chat_assets/static/characters/gpt.webp +0 -0
  49. diff_chat_assets/static/characters/local.json +387 -0
  50. diff_chat_assets/static/characters/local.png +0 -0
  51. diff_chat_assets/static/characters/local.webp +0 -0
  52. diff_chat_assets/static/characters/player.js +318 -0
  53. diff_chat_assets/static/chat-filing.js +84 -0
  54. diff_chat_assets/static/controls.js +194 -0
  55. diff_chat_assets/static/corners.css +59 -0
  56. diff_chat_assets/static/craft.css +246 -0
  57. diff_chat_assets/static/drafts.js +41 -0
  58. diff_chat_assets/static/index.html +208 -0
  59. diff_chat_assets/static/library.css +30 -0
  60. diff_chat_assets/static/library.js +181 -0
  61. diff_chat_assets/static/memory.js +81 -0
  62. diff_chat_assets/static/preference-dialog.js +21 -0
  63. diff_chat_assets/static/preferences.css +56 -0
  64. diff_chat_assets/static/session.js +46 -0
  65. diff_chat_assets/static/settings.css +111 -0
  66. diff_chat_assets/static/settings.js +463 -0
  67. diff_chat_assets/static/setup.js +238 -0
  68. diff_chat_assets/static/utility.js +64 -0
  69. diff_chat_assets/static/vendor/LICENSES.txt +531 -0
  70. diff_chat_assets/static/vendor/highlight.min.js +1262 -0
  71. diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
  72. diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
  73. diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
  74. diff_launcher.py +93 -0
  75. discussion.py +239 -0
  76. history_search.py +68 -0
  77. library_manager.py +251 -0
  78. model_options.py +132 -0
  79. plan_usage.py +72 -0
  80. private_store.py +71 -0
  81. probe.py +195 -0
  82. runtime_paths.py +195 -0
  83. server_security.py +100 -0
  84. setup_status.py +123 -0
  85. shared_memory.py +189 -0
  86. storage.py +185 -0
  87. usage_budget.py +77 -0
  88. usage_claude.py +110 -0
  89. usage_codex.py +170 -0
  90. usage_gemini.py +70 -0
  91. utility_models.py +104 -0
history_search.py ADDED
@@ -0,0 +1,68 @@
1
+ """Search saved chat titles and messages on disk. Results link to a stable message index."""
2
+ from pathlib import Path
3
+ import re
4
+
5
+ from fastapi import APIRouter, Query
6
+
7
+ import storage
8
+
9
+
10
+ router = APIRouter()
11
+ PAGE_SIZE = 24
12
+
13
+
14
+ def recent_files():
15
+ dates = []
16
+ for path in storage.CHAT_DIR.glob("*.json"):
17
+ try:
18
+ dates.append((path.stat().st_mtime_ns, path))
19
+ except OSError:
20
+ continue
21
+ return (path for _, path in sorted(dates, reverse=True))
22
+
23
+
24
+ def excerpt(text, match):
25
+ start, end = match.span()
26
+ left = max(0, start - 55)
27
+ right = min(len(text), end + 85)
28
+ return {
29
+ "before": ("…" if left else "") + text[left:start],
30
+ "match": text[start:end],
31
+ "after": text[end:right] + ("…" if right < len(text) else ""),
32
+ }
33
+
34
+
35
+ def chat_matches(path: Path, pattern):
36
+ try:
37
+ chat = storage.read(path.stem)
38
+ except (OSError, ValueError, TypeError, KeyError):
39
+ return
40
+ base = {"chat_id": chat["id"], "title": chat["title"]}
41
+ match = pattern.search(chat["title"])
42
+ if match:
43
+ yield {**base, "message_index": None, "speaker": None, **excerpt(chat["title"], match)}
44
+ for index in range(len(chat["messages"]) - 1, -1, -1):
45
+ message = chat["messages"][index]
46
+ match = pattern.search(message["text"])
47
+ if match:
48
+ yield {**base, "message_index": index, "speaker": message["speaker"],
49
+ **excerpt(message["text"], match)}
50
+
51
+
52
+ @router.get("/api/search")
53
+ def search_history(q: str = Query("", max_length=160), offset: int = Query(0, ge=0)):
54
+ words = q.split()
55
+ if not words:
56
+ return {"items": [], "more": False}
57
+ pattern = re.compile(r"\s+".join(map(re.escape, words)), re.IGNORECASE)
58
+ items = []
59
+ skipped = 0
60
+ for path in recent_files():
61
+ for item in chat_matches(path, pattern):
62
+ if skipped < offset:
63
+ skipped += 1
64
+ continue
65
+ if len(items) == PAGE_SIZE:
66
+ return {"items": items, "more": True}
67
+ items.append(item)
68
+ return {"items": items, "more": False}
library_manager.py ADDED
@@ -0,0 +1,251 @@
1
+ """Chat filing, portable library archives, and local data controls."""
2
+ import asyncio
3
+ import io
4
+ import json
5
+ from pathlib import Path
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from typing import Literal
14
+ from uuid import uuid4
15
+ import zipfile
16
+
17
+ from fastapi import APIRouter, HTTPException, Request
18
+ from fastapi.responses import Response
19
+ from pydantic import BaseModel, Field
20
+
21
+ from archive_schema import ArchiveChat
22
+ from app_preferences import Provider, Role
23
+ import private_store
24
+ import shared_memory
25
+ import storage
26
+
27
+ router = APIRouter()
28
+ _UNDO = {}
29
+ CHAT_ID = re.compile(r"^[a-f0-9]{32}$")
30
+
31
+
32
+ def existing(chat_id, request=None):
33
+ if request and chat_id in request.app.state.active:
34
+ raise HTTPException(409, "Wait for this chat’s current run to finish.")
35
+ try:
36
+ return storage.read(chat_id)
37
+ except FileNotFoundError:
38
+ raise HTTPException(404, "Chat not found.")
39
+
40
+
41
+ class ChatChange(BaseModel):
42
+ title: str | None = Field(default=None, max_length=160)
43
+ pinned: bool | None = None
44
+ roles: dict[Provider, Role] | None = None
45
+
46
+
47
+ @router.patch("/api/chats/{chat_id}/details")
48
+ async def change_chat(chat_id: str, change: ChatChange, request: Request):
49
+ chat = existing(chat_id, request)
50
+ if change.title is not None:
51
+ title = " ".join(change.title.split())
52
+ if not title:
53
+ raise HTTPException(400, "Enter a chat title.")
54
+ chat.update(title=title, renamed=True)
55
+ if change.pinned is not None:
56
+ chat["pinned"] = change.pinned
57
+ if change.roles is not None:
58
+ chat["roles"] = {**chat.get("roles", {}), **{p: role.model_dump() for p, role in change.roles.items()}}
59
+ storage.save(chat)
60
+ return storage.view(chat)
61
+
62
+
63
+ def remove_ancillary(root, chat_id):
64
+ if not CHAT_ID.fullmatch(chat_id):
65
+ return
66
+ for subdir in (".sessions", ".attachments"):
67
+ directory = root / subdir / chat_id
68
+ if directory.is_dir() and not directory.is_symlink():
69
+ shutil.rmtree(directory, ignore_errors=True)
70
+ (root / ".preferences" / ("memory-" + chat_id + ".json")).unlink(missing_ok=True)
71
+
72
+
73
+ def expire(root, chat_id, token):
74
+ item = _UNDO.get((root, chat_id))
75
+ if not item or item[0] != token:
76
+ return
77
+ item[1].unlink(missing_ok=True)
78
+ remove_ancillary(root, chat_id)
79
+ _UNDO.pop((root, chat_id), None)
80
+
81
+
82
+ def clean_trash(root):
83
+ for path in (root / ".trash").glob("*.json"):
84
+ if CHAT_ID.fullmatch(path.stem) and (root, path.stem) not in _UNDO:
85
+ path.unlink(missing_ok=True)
86
+ if not (root / (path.stem + ".json")).exists():
87
+ remove_ancillary(root, path.stem)
88
+
89
+
90
+ @router.post("/api/chats/{chat_id}/delete")
91
+ async def delete_chat(chat_id: str, request: Request):
92
+ existing(chat_id, request)
93
+ root = storage.CHAT_DIR
94
+ clean_trash(root)
95
+ directory = root / ".trash"
96
+ directory.mkdir(mode=0o700, exist_ok=True)
97
+ target = directory / (chat_id + ".json")
98
+ (root / (chat_id + ".json")).replace(target)
99
+ token = uuid4().hex
100
+ _UNDO[(root, chat_id)] = (token, target, time.monotonic() + 5)
101
+ asyncio.get_running_loop().call_later(5, expire, root, chat_id, token)
102
+ return {"token": token}
103
+
104
+
105
+ class Restore(BaseModel):
106
+ token: str
107
+
108
+
109
+ @router.post("/api/chats/{chat_id}/restore")
110
+ async def restore(chat_id: str, change: Restore):
111
+ root = storage.CHAT_DIR
112
+ previous = _UNDO.get((root, chat_id))
113
+ if not previous or previous[0] != change.token or previous[2] < time.monotonic():
114
+ raise HTTPException(410, "The undo period has ended.")
115
+ previous[1].replace(root / (chat_id + ".json"))
116
+ _UNDO.pop((root, chat_id))
117
+ return storage.view(storage.read(chat_id))
118
+
119
+
120
+ def export_one(chat):
121
+ public = storage.view(chat)
122
+ public["messages"] = chat["messages"]
123
+ public.pop("chars", None)
124
+ public["memory"] = private_store.read("memory-" + chat["id"], "")
125
+ return public
126
+
127
+
128
+ @router.get("/api/data/export")
129
+ async def export_library(format: Literal["json", "markdown"] = "json"):
130
+ chats = []
131
+ for path in sorted(storage.CHAT_DIR.glob("*.json")):
132
+ try:
133
+ chats.append(export_one(storage.read(path.stem)))
134
+ except (ValueError, OSError, KeyError):
135
+ raise HTTPException(409, "An unreadable chat needs repair before exporting this library.")
136
+ if format == "json":
137
+ payload = json.dumps({"format": "diff.library", "version": 1, "chats": chats}, ensure_ascii=False).encode()
138
+ return Response(payload, media_type="application/json", headers={"Content-Disposition": 'attachment; filename="diff-chats.json"'})
139
+ stream = io.BytesIO()
140
+ with zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive:
141
+ for chat in chats:
142
+ safe = re.sub(r"[^\w .()-]", "", chat["title"], flags=re.UNICODE).strip()[:80] or "Chat"
143
+ prefix = safe + "-" + chat["id"][:8]
144
+ lines = ["# " + chat["title"]]
145
+ for item in chat["messages"]:
146
+ lines.extend(["## " + storage.SPEAKERS[item["speaker"]], storage.transcript([item]).split(": ", 1)[-1]])
147
+ for attachment in item.get("attachments", []):
148
+ import base64
149
+ from urllib.parse import quote
150
+ leaf = Path(attachment["name"]).name
151
+ member = prefix + "-files/" + uuid4().hex[:8] + "-" + leaf
152
+ archive.writestr(member, base64.b64decode(attachment["data"], validate=True))
153
+ lines.append(f"[Attachment]({quote(member)})")
154
+ for item in chat.get("discussions", []):
155
+ if item.get("agreement"):
156
+ lines.extend(["## Agreement", str(item["agreement"])])
157
+ if chat["memory"]:
158
+ lines.extend(["## Chat memory", chat["memory"]])
159
+ archive.writestr(prefix + ".md", "\n\n".join(lines) + "\n")
160
+ return Response(stream.getvalue(), media_type="application/zip", headers={"Content-Disposition": 'attachment; filename="diff-markdown.zip"'})
161
+
162
+
163
+ def imported_chat(raw):
164
+ validated = ArchiveChat.model_validate(raw)
165
+ data = validated.model_dump(exclude_unset=True, exclude_none=True)
166
+ title = data.pop("title").strip()[:160] or "Imported chat"
167
+ # An archive never restores CLI sessions, the source chat ID, or executable paths.
168
+ chat = storage.new_chat(title)
169
+ memory = data.pop("memory", "")
170
+ chat.update(data)
171
+ if not validated.stats:
172
+ chat["stats"].update(turns=len(storage.turn_starts(chat["messages"])), legacy=bool(chat["messages"]))
173
+ return chat, memory
174
+
175
+ @router.post("/api/data/import")
176
+ async def import_library(archive: dict):
177
+ if archive.get("format") == "diff.library" and archive.get("version") == 1:
178
+ records = archive.get("chats")
179
+ elif "messages" in archive and "title" in archive:
180
+ records = [archive]
181
+ else:
182
+ raise HTTPException(400, "Choose a diff JSON export or an individual chat JSON file.")
183
+ if not isinstance(records, list) or len(records) > 10000:
184
+ raise HTTPException(400, "The library archive has an invalid chat list.")
185
+ try:
186
+ incoming = [imported_chat(record) for record in records]
187
+ except (ValueError, TypeError, KeyError):
188
+ raise HTTPException(400, "The archive contains an invalid chat or attachment.")
189
+ created = []
190
+ try:
191
+ for chat, memory in incoming:
192
+ storage.save(chat, preserve_timestamp=True)
193
+ created.append(chat["id"])
194
+ if memory:
195
+ private_store.update("memory-" + chat["id"], memory, "", private_store.snapshot("")["revision"])
196
+ except Exception:
197
+ for chat_id in created:
198
+ (storage.CHAT_DIR / (chat_id + ".json")).unlink(missing_ok=True)
199
+ remove_ancillary(storage.CHAT_DIR, chat_id)
200
+ raise
201
+ return {"count": len(created), "first": created[0] if created else None}
202
+
203
+
204
+ @router.post("/api/data/reveal")
205
+ async def reveal():
206
+ storage.CHAT_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
207
+ try:
208
+ if sys.platform == "win32":
209
+ await asyncio.to_thread(os.startfile, str(storage.CHAT_DIR))
210
+ else:
211
+ opener = "/usr/bin/open" if sys.platform == "darwin" else "xdg-open"
212
+ proc = await asyncio.create_subprocess_exec(opener, str(storage.CHAT_DIR),
213
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
214
+ if await proc.wait():
215
+ raise OSError("File manager unavailable")
216
+ except OSError as error:
217
+ raise HTTPException(400, "The system file manager could not open the chats folder.") from error
218
+ return {"ok": True}
219
+
220
+
221
+ class Confirmation(BaseModel):
222
+ confirmation: str
223
+
224
+
225
+ @router.post("/api/data/delete-all")
226
+ async def delete_all(change: Confirmation, request: Request):
227
+ if change.confirmation != "DELETE ALL CHATS":
228
+ raise HTTPException(400, "Type DELETE ALL CHATS to confirm.")
229
+ if request.app.state.active:
230
+ raise HTTPException(409, "Wait for all runs to finish before deleting the library.")
231
+ root = storage.CHAT_DIR
232
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
233
+ # Stage removal on the same filesystem. A failed move restores the preceding files.
234
+ with tempfile.TemporaryDirectory(dir=root, prefix=".removing-") as temporary:
235
+ staged = Path(temporary)
236
+ sources = [p for p in root.glob("*.json") if CHAT_ID.fullmatch(p.stem)]
237
+ sources += [root / n for n in (".sessions", ".attachments", ".trash") if (root / n).exists()]
238
+ sources += list((root / ".preferences").glob("memory-*.json"))
239
+ moved = []
240
+ try:
241
+ for source in sources:
242
+ os.rename(source, staged / source.name)
243
+ moved.append(source)
244
+ except OSError:
245
+ for source in reversed(moved):
246
+ os.rename(staged / source.name, source)
247
+ raise
248
+ for token in list(_UNDO):
249
+ if token[0] == root:
250
+ _UNDO.pop(token)
251
+ return {"ok": True}
model_options.py ADDED
@@ -0,0 +1,132 @@
1
+ """Single-agent model and reasoning choices supported by the pinned CLI adapters."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import subprocess
10
+ import tempfile
11
+
12
+ from runtime_paths import cli_path, find_cli
13
+
14
+ CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"]
15
+ CLAUDE_OPTIONS = {
16
+ "default_model": "claude-opus-5-5",
17
+ "models": [
18
+ {"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "efforts": CLAUDE_EFFORTS,
19
+ "default_effort": "medium"},
20
+ {"id": "claude-opus-4-8", "label": "Claude Opus 4.8", "efforts": CLAUDE_EFFORTS,
21
+ "default_effort": "high"},
22
+ {"id": "claude-sonnet-5", "label": "Claude Sonnet 5", "efforts": CLAUDE_EFFORTS,
23
+ "default_effort": "high"},
24
+ {"id": "claude-haiku-4-5-20251001", "label": "Claude Haiku 4.5", "efforts": ["default"],
25
+ "default_effort": "default"},
26
+ {"id": "default", "label": "Account default", "efforts": ["default"],
27
+ "default_effort": "default"},
28
+ ],
29
+ }
30
+ # Ultra and Persistent include automatic delegation. Their wire-level reasoning
31
+ # is a different, lower level when the Codex agent tools have been removed.
32
+ SINGLE_AGENT_LEVELS = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
33
+
34
+
35
+ def _codex_choices(catalog: dict) -> dict:
36
+ options = {}
37
+ entries = catalog.get("models", []) if isinstance(catalog, dict) else []
38
+ if not isinstance(entries, list):
39
+ return {"default_model": "", "models": []}
40
+ for model in entries:
41
+ # The upstream picker uses visibility for ChatGPT subscriptions;
42
+ # supported_in_api is a separate filter for API-key-authenticated users.
43
+ if not isinstance(model, dict) or model.get("visibility") != "list":
44
+ continue
45
+ slug = model.get("slug")
46
+ if not isinstance(slug, str) or not re.fullmatch(r"gpt-[a-z0-9][a-z0-9.-]{0,63}", slug):
47
+ continue
48
+ # 0.166's embedded catalog predates the ChatGPT retirement of GPT-5.5.
49
+ if slug == "gpt-5.5":
50
+ continue
51
+ levels = model.get("supported_reasoning_levels")
52
+ if not isinstance(levels, list):
53
+ continue
54
+ advertised = [item.get("effort") for item in levels if isinstance(item, dict)]
55
+ efforts = [level for level in SINGLE_AGENT_LEVELS if level in advertised]
56
+ if not efforts:
57
+ continue
58
+ default = model.get("default_reasoning_level")
59
+ # Derive the display name from the canonical slug; never expose user
60
+ # instructions, identity fields, or other raw account catalog metadata.
61
+ version, _, family = slug.removeprefix("gpt-").partition("-")
62
+ label = f"GPT-{version}" + (f" {family.replace('-', ' ').title()}" if family else "")
63
+ priority = model.get("priority")
64
+ options[slug] = (priority if type(priority) is int else 9999,
65
+ {"id": slug, "label": label, "efforts": efforts,
66
+ "default_effort": default if default in efforts else efforts[0]})
67
+ models = [pair[1] for pair in sorted(options.values(), key=lambda pair: (pair[0], pair[1]["id"]))]
68
+ return {"default_model": models[0]["id"] if models else "", "models": models}
69
+
70
+
71
+ def _cached_choices() -> dict | None:
72
+ home = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex")).expanduser()
73
+ try:
74
+ path = home / "models_cache.json"
75
+ if path.stat().st_size > 16 * 1024 * 1024:
76
+ return None
77
+ choices = _codex_choices(json.loads(path.read_bytes()))
78
+ except (OSError, ValueError, RecursionError):
79
+ return None
80
+ return choices if choices["models"] else None
81
+
82
+
83
+ def codex_choices(bundled: dict) -> dict:
84
+ """Prefer the current account's CLI model list; the bundle also works offline."""
85
+ return _cached_choices() or _codex_choices(bundled)
86
+
87
+
88
+ def resolve_choice(provider: dict, model_id: str | None, effort: str | None) -> tuple[dict, str]:
89
+ requested = provider["default_model"] if model_id is None else model_id
90
+ model = next((item for item in provider["models"] if item["id"] == requested), None)
91
+ if not model:
92
+ raise ValueError("That model is unavailable. Choose a current model in Model settings.")
93
+ level = model["default_effort"] if effort is None else effort
94
+ if level not in model["efforts"]:
95
+ raise ValueError(f"Choose a supported reasoning level for {model['label']} in Model settings.")
96
+ return model, level
97
+
98
+
99
+ def _list_local_codex() -> dict:
100
+ empty = {"default_model": "", "models": []}
101
+ binary = find_cli("codex")
102
+ if not binary:
103
+ return empty
104
+ if choices := _cached_choices():
105
+ return choices
106
+ # --bundled prints the embedded model list locally without starting a turn.
107
+ try:
108
+ with tempfile.TemporaryDirectory(prefix="transcript-models-") as temporary:
109
+ root = Path(temporary)
110
+ cwd = root / "workspace"
111
+ cwd.mkdir()
112
+ home = root / "codex"
113
+ home.mkdir()
114
+ env = {key: os.environ[key] for key in ("PATH", "SYSTEMROOT", "WINDIR") if key in os.environ}
115
+ env['PATH'] = cli_path()
116
+ env.update(HOME=str(root), CODEX_HOME=str(home), TMPDIR=str(root))
117
+ result = subprocess.run([str(Path(binary).absolute()), "debug", "models", "--bundled"],
118
+ cwd=cwd, env=env, stdin=subprocess.DEVNULL, capture_output=True,
119
+ timeout=5, check=True)
120
+ return _codex_choices(json.loads(result.stdout))
121
+ except (OSError, ValueError, subprocess.SubprocessError):
122
+ return empty
123
+
124
+
125
+ async def get_model_options() -> dict:
126
+ from adapters import REGISTRY
127
+ from private_store import is_disconnected
128
+ async def options(adapter):
129
+ if is_disconnected(adapter.id):
130
+ return {"default_model": "", "models": [], "disconnected": True, "detail": "Disconnected from diff."}
131
+ return await adapter.list_models()
132
+ return dict(zip(REGISTRY, await asyncio.gather(*(options(a) for a in REGISTRY.values()))))
plan_usage.py ADDED
@@ -0,0 +1,72 @@
1
+ """Short-lived, account-level usage snapshots from connected participants."""
2
+ import asyncio
3
+ from datetime import datetime, timezone
4
+ import time
5
+ import usage_budget
6
+ import app_preferences
7
+ import private_store
8
+
9
+ from adapters import REGISTRY
10
+
11
+ READERS = {name: adapter.usage for name, adapter in REGISTRY.items()}
12
+ cache = {}
13
+ locks = {name: asyncio.Lock() for name in READERS}
14
+ generation = {name: 0 for name in READERS}
15
+
16
+
17
+ def invalidate_usage(providers):
18
+ for name in providers:
19
+ generation[name] += 1
20
+ cache.pop(name, None)
21
+
22
+
23
+ async def read_provider(name, force):
24
+ async with locks[name]:
25
+ if private_store.is_disconnected(name):
26
+ return {"status": "disconnected", "windows": [], "detail": "Disconnected from diff."}
27
+ moment = time.monotonic()
28
+ saved = cache.get(name)
29
+ if saved:
30
+ data, checked, expires = saved
31
+ if moment < expires and (not force or moment - checked < 5):
32
+ return data
33
+ revision = generation[name]
34
+ try:
35
+ data = await asyncio.wait_for(READERS[name](), timeout=15)
36
+ except Exception:
37
+ data = {"status": "unavailable", "windows": [], "detail": "Usage could not be refreshed.",
38
+ "checked_at": datetime.now(timezone.utc).isoformat()}
39
+ current = datetime.now(timezone.utc)
40
+ if data is None:
41
+ note = REGISTRY[name].usage_note
42
+ data = {"status": "unmetered" if REGISTRY[name].kind == "http" else "unavailable",
43
+ "detail": note or "This provider does not report plan usage.", "windows": [],
44
+ "checked_at": current.isoformat()}
45
+ windows = []
46
+ ttl = min(60, app_preferences.get()["usage_refresh"]) if data["status"] == "available" else 20
47
+ for window in data["windows"]:
48
+ if window.get("reset_at"):
49
+ try:
50
+ remaining = (datetime.fromisoformat(window["reset_at"]) - current).total_seconds()
51
+ except (TypeError, ValueError, OverflowError):
52
+ window = {**window, "reset_at": None}
53
+ else:
54
+ if remaining <= 0:
55
+ continue
56
+ ttl = min(ttl, remaining)
57
+ windows.append(window)
58
+ if windows != data["windows"]:
59
+ data = {**data, "windows": windows}
60
+ if not windows:
61
+ ttl = 20
62
+ data.update(status="unavailable", detail="Waiting for the provider’s next usage window.")
63
+ checked = time.monotonic()
64
+ if revision == generation[name]:
65
+ cache[name] = data, checked, checked + ttl
66
+ usage_budget.observe(name, data)
67
+ return data
68
+
69
+
70
+ async def get_usage(force=False):
71
+ snapshots = await asyncio.gather(*(read_provider(name, force) for name in READERS))
72
+ return dict(zip(READERS, snapshots))
private_store.py ADDED
@@ -0,0 +1,71 @@
1
+ """Small local preferences, written atomically with optimistic edit checks."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import tempfile
7
+ from threading import Lock
8
+
9
+ from fastapi import HTTPException
10
+ import storage
11
+
12
+ _edit = Lock()
13
+
14
+
15
+ def disconnect_marker(provider):
16
+ # Callers supply an ID from the participant registry. Each provider has its
17
+ # own marker so independent windows cannot overwrite another provider's choice.
18
+ return storage.CHAT_DIR / ".preferences" / ("disconnected-" + provider)
19
+
20
+
21
+ def is_disconnected(provider):
22
+ return disconnect_marker(provider).is_file()
23
+
24
+
25
+ def set_disconnected(provider, disconnected):
26
+ path = disconnect_marker(provider)
27
+ if disconnected:
28
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
29
+ path.touch(mode=0o600, exist_ok=True)
30
+ else:
31
+ path.unlink(missing_ok=True)
32
+
33
+
34
+ def read(key, default):
35
+ path = storage.CHAT_DIR / ".preferences" / (key + ".json")
36
+ try:
37
+ value = json.loads(path.read_text(encoding="utf-8"))
38
+ return value if isinstance(value, type(default)) else default
39
+ except (OSError, ValueError, RecursionError):
40
+ return default
41
+
42
+
43
+ def snapshot(value):
44
+ data = json.dumps(value, sort_keys=True, ensure_ascii=True).encode()
45
+ return {"value": value, "revision": hashlib.sha256(data).hexdigest()}
46
+
47
+
48
+ def update(key, value, default, expected):
49
+ with _edit:
50
+ current = snapshot(read(key, default))
51
+ if current["revision"] != expected:
52
+ raise HTTPException(409, "This setting changed in another window. Reopen it to see the latest version.")
53
+ if current["value"] == value:
54
+ return current
55
+ directory = storage.CHAT_DIR / ".preferences"
56
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
57
+ path = directory / (key + ".json")
58
+ with tempfile.NamedTemporaryFile(dir=directory, mode="w", encoding="utf-8", delete=False) as handle:
59
+ temp = Path(handle.name)
60
+ try:
61
+ json.dump(value, handle, ensure_ascii=True, indent=2)
62
+ handle.flush()
63
+ os.fsync(handle.fileno())
64
+ except BaseException:
65
+ temp.unlink(missing_ok=True)
66
+ raise
67
+ try:
68
+ os.replace(temp, path)
69
+ finally:
70
+ temp.unlink(missing_ok=True)
71
+ return snapshot(value)