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
adapters/gpt.py ADDED
@@ -0,0 +1,217 @@
1
+ """Codex subscription, sanitized tool catalog, session storage and response protocol."""
2
+ import asyncio
3
+ import base64
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ from model_options import _list_local_codex, codex_choices, resolve_choice
9
+ from ._base import CliParticipant
10
+ from ._cli import (CODEX_DISABLE, ModelError, SetupRequired, Reply, _Invocation, _check_login, _private_dir,
11
+ _tail, _uuid)
12
+
13
+ async def _prepare_codex(call: _Invocation, account_home: Path):
14
+ clean_home = Path(call.env["CODEX_HOME"])
15
+ # 0.166.0 always reads CODEX_HOME/AGENTS*.md, even at project_doc_max_bytes=0.
16
+ # Only expose the credential file and its native refresh lock. No token
17
+ # enters Python. The pinned CLI refreshes via open+truncate under that lock.
18
+ for name in ("auth.json", "auth.lock"):
19
+ link = clean_home / name
20
+ if link.is_symlink() and link.readlink() == account_home / name:
21
+ continue
22
+ try:
23
+ link.symlink_to(account_home / name)
24
+ except OSError as error:
25
+ if getattr(error, "winerror", None) == 1314:
26
+ raise SetupRequired("Enable Windows Developer Mode to let Codex securely link its credentials into "
27
+ "a private session, then try again.") from error
28
+ raise
29
+ try:
30
+ await _check_login(call, "gpt")
31
+ return
32
+ except ModelError as file_login:
33
+ if sys.platform != "darwin" or not Path("/usr/bin/sandbox-exec").is_file():
34
+ if (account_home / "auth.json").is_file():
35
+ raise
36
+ raise ModelError(
37
+ "Sign in with codex login. If you use a keyring-only account, "
38
+ "use codex -c 'cli_auth_credentials_store=\"file\"' login "
39
+ "to authorize Codex's private on-disk credential store.",
40
+ file_login.stderr,
41
+ ) from file_login
42
+
43
+ # Keychain IDs are derived from the canonical Codex home. Preserve that
44
+ # ID and deny the CLI access to both global instruction paths at OS level.
45
+ blocked = set()
46
+ for name in ("AGENTS.md", "AGENTS.override.md"):
47
+ path = account_home / name
48
+ blocked.update([str(path), str(path.resolve())])
49
+ rules = " ".join(f"(literal {json.dumps(path)})" for path in sorted(blocked))
50
+ policy = f"(version 1)(allow default)(deny file-read* {rules})"
51
+ call.prefix = ["/usr/bin/sandbox-exec", "-p", policy]
52
+ call.env["CODEX_HOME"] = str(account_home)
53
+ call.codex_store = "keyring"
54
+ try:
55
+ await _check_login(call, "gpt")
56
+ except ModelError:
57
+ raise file_login
58
+
59
+
60
+ async def _codex_command(call: _Invocation, root: Path, framing: str,
61
+ model_id: str | None = None, effort: str | None = None,
62
+ web_search: bool = False, *, session_dir: Path | None = None,
63
+ session_id: str | None = None) -> list[str]:
64
+ code, raw = await call.execute(["debug", "models", "--bundled"])
65
+ if code:
66
+ raise ModelError("Codex could not read its bundled model catalog.", _tail(call.stderr))
67
+ try:
68
+ bundled = json.loads(raw)
69
+ models = sorted((m for m in bundled["models"] if m["visibility"] == "list"),
70
+ key=lambda m: m["priority"])
71
+ if not models:
72
+ raise ValueError("empty bundled catalog")
73
+ except (TypeError, ValueError, KeyError) as error:
74
+ raise ModelError("Codex returned an incompatible model catalog.") from error
75
+ try:
76
+ choice, level = resolve_choice(codex_choices(bundled), model_id, effort)
77
+ except ValueError as error:
78
+ raise ModelError(str(error)) from error
79
+
80
+ # New account models can arrive before a client update. Build their runtime
81
+ # entry from the pinned client's schema, never from a newer client's tool
82
+ # declarations. Prefer the same family's bundled entry when available.
83
+ slug = choice["id"]
84
+ if session_dir is not None:
85
+ # Codex preserves <model_switch> developer messages when a native thread
86
+ # changes models. Start a separate generation to keep old mode framing out.
87
+ binding = session_dir / "model.json"
88
+ if session_id:
89
+ if not binding.is_file() or binding.read_text(encoding="utf-8") != json.dumps(slug):
90
+ raise ModelError("Start a fresh CLI session after changing the GPT model.")
91
+ else:
92
+ binding.write_text(json.dumps(slug), encoding="utf-8")
93
+ binding.chmod(0o600)
94
+ family = slug.rsplit("-", 1)[-1]
95
+ by_slug = {m["slug"]: m for m in models}
96
+ template = by_slug.get(slug) or next((m for m in models if m["slug"].endswith("-" + family)), models[0])
97
+ model = dict(template, slug=slug, display_name=choice["label"],
98
+ default_reasoning_level=choice["default_effort"],
99
+ supported_reasoning_levels=[{"effort": item, "description": item}
100
+ for item in choice["efforts"]],
101
+ shell_type="disabled", tool_mode="direct", apply_patch_tool_type=None,
102
+ experimental_supported_tools=[], supports_search_tool=False, node_repl_disabled=True)
103
+ if web_search or session_dir is not None:
104
+ # Lite omits hosted tools and can persist old developer messages in a
105
+ # resumed thread. Full Responses renders only the current instructions.
106
+ model["use_responses_lite"] = False
107
+
108
+ # Put all support files beside the empty working directory. Pin the model
109
+ # to the sanitized entry so the client cannot select a default tool profile.
110
+ catalog = root / "catalog.json"
111
+ catalog.write_text(json.dumps({"models": [model]}), encoding="utf-8")
112
+ instructions = root / "instructions.txt"
113
+ instructions.write_text(framing, encoding="utf-8")
114
+ settings = [
115
+ 'forced_login_method="chatgpt"', f'cli_auth_credentials_store="{call.codex_store}"',
116
+ f"model_reasoning_effort={json.dumps(level)}",
117
+ f"model_catalog_json={json.dumps(str(catalog))}",
118
+ f"model_instructions_file={json.dumps(str(instructions))}",
119
+ f"sqlite_home={json.dumps(str(session_dir or root))}", f"log_dir={json.dumps(str(root))}",
120
+ 'history.persistence="none"', "tools.update_plan.enabled=false",
121
+ "tools.experimental_request_user_input.enabled=false", "agents.enabled=false",
122
+ 'web_search="live"' if web_search else 'web_search="disabled"', "skills.include_instructions=false",
123
+ "skills.bundled.enabled=false", "mcp_servers={}", "project_doc_max_bytes=0",
124
+ "analytics.enabled=false", "include_environment_context=false",
125
+ "include_environment_context_time=false", "include_apps_instructions=false",
126
+ "include_permissions_instructions=false", "include_collaboration_mode_instructions=false",
127
+ ]
128
+ args = ["--no-daemon", "-a", "never", "exec", "--strict-config", "--json",
129
+ "--ignore-user-config", "--ignore-rules", "--skip-git-repo-check",
130
+ "--sandbox", "read-only", "-m", slug, "--enable", "skip_host_skill_discovery"]
131
+ if session_dir is None:
132
+ args.append("--ephemeral")
133
+ for feature in CODEX_DISABLE:
134
+ args.extend(["--disable", feature])
135
+ for setting in settings:
136
+ args.extend(["-c", setting])
137
+ if session_id:
138
+ args.extend(["resume", session_id])
139
+ return [*args, "-"]
140
+
141
+
142
+ class GPTReply(Reply):
143
+ async def accept_event(self, kind, event):
144
+ if kind == "thread.started":
145
+ self.session_id = _uuid(event.get("thread_id"))
146
+ self.session_started = True
147
+ elif kind in {"item.started", "item.completed"}:
148
+ item = event.get("item") or {}
149
+ if item.get("type") == "web_search":
150
+ action = item.get("action") or {}
151
+ self.search_activity([action] if isinstance(action, dict) and action.get("url") else [])
152
+ if kind == "item.completed" and item.get("type") == "agent_message":
153
+ self.text = item.get("text", "")
154
+ elif kind == "turn.completed":
155
+ self.finished = True
156
+ elif kind == "turn.failed":
157
+ self.error = (event.get("error") or {}).get("message", "Codex could not complete the reply.")
158
+ elif kind == "error":
159
+ # Transient connection notices can precede a successful Codex retry.
160
+ self.error = event.get("message", "")
161
+
162
+
163
+ class GPT(CliParticipant):
164
+ login_args = ("login",)
165
+ id, label, cli_name, order = "gpt", "GPT", "codex", 20
166
+ color, dark_color, fill, dark_fill = "#46674c", "#a5c4a8", "#658368", "#91b295"
167
+ default_enabled = True
168
+ search_tool = "web_search"
169
+ character = "/static/characters/gpt.json"
170
+ reply = GPTReply
171
+ streaming = False
172
+
173
+ async def list_models(self):
174
+ return await asyncio.to_thread(_list_local_codex)
175
+
176
+ async def usage(self):
177
+ from usage_codex import get_codex_usage
178
+ return await get_codex_usage()
179
+
180
+ async def command(self, call, root, framing, transcript, model_id, effort, web_search, images,
181
+ session_dir, session_id, legacy, credential_links):
182
+ native = session_dir is not None
183
+ target_id = session_id
184
+ account_home = Path(call.env["CODEX_HOME"]).expanduser().resolve()
185
+ clean_home = root / "codex"
186
+ clean_home.mkdir(mode=0o700)
187
+ call.env["CODEX_HOME"] = str(clean_home)
188
+ if native:
189
+ private = session_dir / "codex"
190
+ _private_dir(private)
191
+ credential_links.extend(private / name for name in ("auth.json", "auth.lock"))
192
+ call.env["CODEX_HOME"] = str(private)
193
+ await _prepare_codex(call, account_home)
194
+ if native and call.codex_store == "keyring":
195
+ # The keyring identity and rollout location both depend on CODEX_HOME.
196
+ # Keep the keyring-only compatibility route ephemeral.
197
+ if session_id:
198
+ raise ModelError("Codex needs its file-backed ChatGPT login to resume this private session.")
199
+ native = False
200
+ args = await _codex_command(call, root, framing, model_id, effort, web_search=web_search,
201
+ session_dir=session_dir if native else None, session_id=session_id)
202
+ prompt = transcript
203
+ if images:
204
+ # A generated private path avoids interpreting the original filename as a CLI argument.
205
+ files = []
206
+ for index, image in enumerate(images):
207
+ suffix = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}[image["type"]]
208
+ path = root / f"image-{index}{suffix}"
209
+ path.write_bytes(base64.b64decode(image["data"], validate=True))
210
+ files.extend(["--image", str(path)])
211
+ args[-1:-1] = files
212
+ labels = [f"{i}. {img['name']} — {img.get('message_time', '')}" for i, img in enumerate(images, 1)]
213
+ prompt += "\n\n[User images, in attachment order]\n" + "\n".join(labels)
214
+ return args, prompt, native, target_id
215
+
216
+
217
+ ADAPTER = GPT()
adapters/local.py ADDED
@@ -0,0 +1,146 @@
1
+ """Ollama over loopback HTTP. Only installed, on-device models may receive chat data."""
2
+ import asyncio
3
+ import json
4
+ import re
5
+
6
+ import httpx
7
+ from ._base import Participant, transcript_text
8
+ from ._cli import ModelError
9
+
10
+ OLLAMA = "http://127.0.0.1:11434"
11
+ SUGGESTION = "ollama pull gemma3:4b"
12
+ MODEL_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/-]{0,127}")
13
+
14
+
15
+ def client(timeout):
16
+ return httpx.AsyncClient(base_url=OLLAMA, trust_env=False, follow_redirects=False, timeout=timeout)
17
+
18
+
19
+ def model_names(payload):
20
+ rows = payload.get("models") if isinstance(payload, dict) else None
21
+ if not isinstance(rows, list):
22
+ raise ValueError("Unexpected model catalog")
23
+ names = []
24
+ for row in rows:
25
+ if not isinstance(row, dict) or row.get("remote_model") or row.get("remote_host"):
26
+ continue
27
+ name = row.get("name")
28
+ if (not isinstance(name, str) or not MODEL_NAME.fullmatch(name) or
29
+ name.endswith((":cloud", "-cloud")) or name in names):
30
+ continue
31
+ caps = row.get("capabilities")
32
+ if caps and "completion" not in caps:
33
+ continue
34
+ names.append(name)
35
+ return names
36
+
37
+
38
+ async def tags(connection):
39
+ response = await connection.get("/api/tags")
40
+ response.raise_for_status()
41
+ return model_names(response.json())
42
+
43
+
44
+ class Local(Participant):
45
+ id, label, order, kind = "local", "Local", 40, "http"
46
+ color, dark_color = "#A9832F", "#CFA95A"
47
+ character = "/static/characters/local.json"
48
+ usage_note = "Runs on this computer · no plan limits"
49
+
50
+ def setup_action(self, status):
51
+ from connection_handoff import SetupAction
52
+ from runtime_paths import find_cli
53
+ if status in ("missing", "setup") and (binary := find_cli("ollama")):
54
+ if status == "missing":
55
+ return SetupAction("start", "Start Ollama", (binary, "serve"))
56
+ return SetupAction("pull", "Download gemma3:4b", (binary, *SUGGESTION.split()[1:]))
57
+ return None
58
+
59
+ def capabilities(self):
60
+ return {**super().capabilities(), "images": True}
61
+
62
+ async def detect(self):
63
+ try:
64
+ async with client(2) as connection:
65
+ names = await tags(connection)
66
+ response = await connection.get("/api/version")
67
+ version = response.json().get("version") if response.is_success else None
68
+ except (httpx.HTTPError, ValueError, AttributeError):
69
+ return {"status": "missing", "hint": "Install Ollama and start its local server.",
70
+ "command": "ollama serve", "install_url": "https://ollama.com/download",
71
+ "suggestion": SUGGESTION, "version": None}
72
+ if not names:
73
+ return {"status": "setup", "hint": "Ollama is running. Download a chat model.",
74
+ "command": SUGGESTION, "version": version}
75
+ return {"status": "ready", "hint": self.usage_note, "command": None, "version": version}
76
+
77
+ async def list_models(self):
78
+ try:
79
+ async with client(2) as connection:
80
+ names = await tags(connection)
81
+ except (httpx.HTTPError, ValueError):
82
+ names = []
83
+ return {"default_model": names[0] if names else "", "models": [
84
+ {"id": name, "label": name, "efforts": ["default"], "default_effort": "default"}
85
+ for name in names]}
86
+
87
+ async def send(self, messages, model, reasoning, system, attachments, session_id, *,
88
+ timeout=120, on_input=None, **runtime):
89
+ import app_preferences
90
+ if session_id:
91
+ self.resume(session_id)
92
+ text = transcript_text(messages)
93
+ try:
94
+ async with asyncio.timeout(timeout), client(timeout) as connection:
95
+ names = await tags(connection)
96
+ chosen = model or (names[0] if names else "")
97
+ if chosen not in names:
98
+ raise ModelError("Select an installed Ollama chat model in Model settings.")
99
+ # Aliases can point to cloud models. Check the on-device manifest before sending conversation data.
100
+ details = await connection.post("/api/show", json={"model": chosen})
101
+ details.raise_for_status()
102
+ info = details.json()
103
+ if not isinstance(info, dict) or info.get("remote_model") or info.get("remote_host"):
104
+ raise ModelError("Choose an on-device Ollama model. This model is hosted remotely.")
105
+ caps = info.get("capabilities", ())
106
+ if caps and "completion" not in caps:
107
+ raise ModelError("Choose a model that supports chat.")
108
+ user = {"role": "user", "content": text}
109
+ if attachments:
110
+ if "vision" not in caps:
111
+ raise ModelError("This Ollama model cannot accept images. Choose an installed vision model.")
112
+ user["images"] = [item["data"] for item in attachments]
113
+ context = app_preferences.get().get(self.id, {}).get("context_length", 4096)
114
+ body = {"model": chosen, "stream": True, "messages": [{"role": "system", "content": system}, user],
115
+ "options": {"num_ctx": context}}
116
+ if "thinking" in caps:
117
+ # Ollama's GPT-OSS family selects a level rather than a boolean.
118
+ family = (info.get("details") or {}).get("family", "")
119
+ body["think"] = "low" if family == "gptoss" else False
120
+ if on_input:
121
+ on_input(len(system) + len(text))
122
+ async with connection.stream("POST", "/api/chat", json=body) as response:
123
+ response.raise_for_status()
124
+ got_text = False
125
+ async for line in response.aiter_lines():
126
+ if not line:
127
+ continue
128
+ event = json.loads(line)
129
+ if not isinstance(event, dict) or event.get("error"):
130
+ raise ModelError("Ollama could not complete this reply.")
131
+ piece = event.get("message", {}).get("content", "")
132
+ if isinstance(piece, str) and piece:
133
+ got_text = True
134
+ yield piece
135
+ if event.get("done"):
136
+ if not got_text:
137
+ raise ModelError("Ollama finished without a reply.")
138
+ return
139
+ raise ModelError("Ollama disconnected before completing its response.")
140
+ except (httpx.TimeoutException, TimeoutError) as error:
141
+ raise ModelError(f"Ollama timed out after {timeout}s.") from error
142
+ except (ValueError, AttributeError, httpx.HTTPError) as error:
143
+ raise ModelError("Could not read a reply from Ollama. Check that its local server is running.") from error
144
+
145
+
146
+ ADAPTER = Local()
adapters/registry.py ADDED
@@ -0,0 +1,33 @@
1
+ """Discover trusted adapters distributed inside this package, in declared display order."""
2
+ import importlib
3
+ import pkgutil
4
+ import re
5
+ from ._base import Participant
6
+
7
+
8
+ def discover():
9
+ found = []
10
+ for item in pkgutil.iter_modules(importlib.import_module(__package__).__path__):
11
+ if item.name.startswith("_") or item.name == "registry" or item.ispkg:
12
+ continue
13
+ adapter = getattr(importlib.import_module(f"{__package__}.{item.name}"), "ADAPTER", None)
14
+ if not isinstance(adapter, Participant) or item.name != adapter.id or not re.fullmatch("[a-z][a-z0-9_]*", adapter.id):
15
+ raise ValueError(f"Invalid participant registration in {item.name}")
16
+ found.append(adapter)
17
+ return {entry.id: entry for entry in sorted(found, key=lambda entry: (entry.order, entry.id))}
18
+
19
+
20
+ REGISTRY = discover()
21
+
22
+
23
+ def participant_info():
24
+ return [
25
+ {"id": a.id, "label": a.label, "color": a.color, "dark_color": a.dark_color,
26
+ "fill": a.fill or a.color, "dark_fill": a.dark_fill or a.dark_color,
27
+ "character": a.character, "kind": a.kind, "cli_name": a.cli_name, "usage_note": a.usage_note,
28
+ "default_enabled": a.default_enabled, "capabilities": a.capabilities()}
29
+ for a in REGISTRY.values()
30
+ ]
31
+
32
+
33
+ public_registry = participant_info
api_fallback.py ADDED
@@ -0,0 +1,189 @@
1
+ """Opt-in stateless provider transport, using credentials held in the operating system vault."""
2
+ import asyncio
3
+ import re
4
+ import sys
5
+ import time
6
+ from urllib.parse import urlsplit
7
+
8
+ import httpx
9
+ from fastapi import APIRouter, HTTPException
10
+ from pydantic import BaseModel, SecretStr
11
+ from adapters import REGISTRY, ModelError, ResumeUnavailable, require_connection, run_model as cli_model
12
+ import app_preferences
13
+
14
+ router = APIRouter()
15
+ SERVICE = "diff.provider-api"
16
+ ENDPOINTS = {"claude": "https://api.anthropic.com/v1/messages", "gpt": "https://api.openai.com/v1/responses"}
17
+
18
+
19
+ def supports_fallback(provider):
20
+ return provider in ENDPOINTS and REGISTRY[provider].capabilities().get("api_fallback", False)
21
+
22
+
23
+ def vault():
24
+ # Select a real OS credential store explicitly. Third-party plaintext keyrings
25
+ # and environment overrides are never eligible for storing a provider key.
26
+ if sys.platform == "darwin":
27
+ from keyring.backends.macOS import Keyring
28
+ elif sys.platform == "win32":
29
+ from keyring.backends.Windows import WinVaultKeyring as Keyring
30
+ elif sys.platform.startswith("linux"):
31
+ from keyring.backends.SecretService import Keyring
32
+ else:
33
+ raise RuntimeError("No supported system keychain")
34
+ return Keyring()
35
+
36
+
37
+ def credential(provider):
38
+ try:
39
+ return vault().get_password(SERVICE, provider)
40
+ except Exception:
41
+ raise HTTPException(503, "The system keychain is unavailable or locked.")
42
+
43
+
44
+ def require_fallback(provider):
45
+ if not supports_fallback(provider):
46
+ raise HTTPException(400, "This participant has no API-key fallback.")
47
+
48
+
49
+ class KeyChange(BaseModel):
50
+ key: SecretStr
51
+
52
+
53
+ @router.post("/api/settings/keys/{provider}")
54
+ async def save_key(provider: app_preferences.Provider, change: KeyChange):
55
+ require_fallback(provider)
56
+ secret = change.key.get_secret_value().strip()
57
+ if len(secret) > 1024 or not re.fullmatch(r"[!-~]+", secret):
58
+ raise HTTPException(400, "Enter a valid provider API key.")
59
+ try:
60
+ await asyncio.to_thread(lambda: vault().set_password(SERVICE, provider, secret))
61
+ except Exception:
62
+ raise HTTPException(503, "Could not save the key. Unlock the system keychain and try again.")
63
+ return {"stored": True}
64
+
65
+
66
+ @router.post("/api/settings/keys/{provider}/remove")
67
+ async def remove_key(provider: app_preferences.Provider):
68
+ require_fallback(provider)
69
+ await app_preferences.save({provider: {"api_fallback": False}})
70
+ try:
71
+ if await asyncio.to_thread(credential, provider):
72
+ await asyncio.to_thread(lambda: vault().delete_password(SERVICE, provider))
73
+ except Exception:
74
+ raise HTTPException(503, "Could not remove the credential from the system keychain.")
75
+ return {"stored": False}
76
+
77
+
78
+ def request_body(provider, model, effort, instruction, text, images, web):
79
+ if provider == "claude":
80
+ content = [{"type": "image", "source": {"type": "base64", "media_type": item["type"], "data": item["data"]}} for item in images]
81
+ content.append({"type": "text", "text": text})
82
+ body = {"model": model, "system": instruction, "max_tokens": 8192,
83
+ "messages": [{"role": "user", "content": content}]}
84
+ if effort and effort != "default":
85
+ body["output_config"] = {"effort": effort}
86
+ if web:
87
+ body["tools"] = [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}]
88
+ else:
89
+ content = [{"type": "input_image", "image_url": "data:" + item["type"] + ";base64," + item["data"]} for item in images]
90
+ content.append({"type": "input_text", "text": text})
91
+ body = {"model": model, "instructions": instruction, "store": False,
92
+ "input": [{"role": "user", "content": content}]}
93
+ if effort and effort != "default":
94
+ body["reasoning"] = {"effort": effort}
95
+ if web:
96
+ body["tools"] = [{"type": "web_search"}]
97
+ return body
98
+
99
+
100
+ def response_text(provider, result):
101
+ if provider == "gpt":
102
+ if result.get("status") != "completed":
103
+ raise ModelError("The OpenAI API returned an incomplete reply.")
104
+ blocks = [b for item in result.get("output", []) if item.get("type") == "message" for b in item.get("content", [])]
105
+ else:
106
+ if result.get("stop_reason") in {"max_tokens", "pause_turn"}:
107
+ raise ModelError("The Claude API returned an incomplete reply.")
108
+ blocks = result.get("content", [])
109
+ parts, sources = [], {}
110
+ for block in blocks:
111
+ if block.get("type") not in {"text", "output_text"}:
112
+ continue
113
+ parts.append(block.get("text", ""))
114
+ for citation in block.get("citations", []) + block.get("annotations", []):
115
+ url = citation.get("url", "")
116
+ if isinstance(url, str) and urlsplit(url).scheme in {"http", "https"}:
117
+ sources[url] = {"url": url, "title": citation.get("title") or url}
118
+ text = "\n\n".join(parts).strip()
119
+ if not text:
120
+ raise ModelError("The fallback API returned an empty reply.")
121
+ return text, list(sources.values())
122
+
123
+
124
+ async def run_model(provider, framing, transcript, timeout, on_delta, stop, **options):
125
+ settings = app_preferences.get()[provider]
126
+ if not supports_fallback(provider) or not settings["api_fallback"]:
127
+ return await cli_model(provider, framing, transcript, timeout, on_delta, stop, **options)
128
+ began = time.monotonic()
129
+ emitted = False
130
+
131
+ async def cli_delta(piece):
132
+ nonlocal emitted
133
+ emitted = True
134
+ await on_delta(piece)
135
+
136
+ try:
137
+ return await cli_model(provider, framing, transcript, timeout, cli_delta, stop, **options)
138
+ except ResumeUnavailable:
139
+ raise
140
+ except ModelError as error:
141
+ # Never submit a second paid request on stop, after output, or for an
142
+ # ambiguous network failure where the subscription turn may have run.
143
+ eligible = re.search(r"missing from PATH|sign in|login|log in|logged in|keychain|credential|rate.limit|usage.limit|hit your limit|out of credits|quota|verified tool isolation", error.message, re.I)
144
+ if stop.is_set() or emitted or not eligible:
145
+ raise
146
+ if options.get("session_id"):
147
+ raise ResumeUnavailable("Rebuild the recent history before using the API fallback.") from error
148
+ require_connection(provider)
149
+ try:
150
+ key = await asyncio.to_thread(credential, provider)
151
+ except HTTPException as error:
152
+ raise ModelError(error.detail) from error
153
+ if not key:
154
+ raise ModelError("Save the fallback API key in Settings → Models.")
155
+ model = settings["api_model"] or options.get("model_id")
156
+ if not model or model == "default":
157
+ raise ModelError("Choose a fallback API model ID in Settings → Models.")
158
+ body = request_body(provider, model, options.get("effort"), framing, transcript, options.get("images") or [], options.get("web_search", False))
159
+ url = ENDPOINTS[provider]
160
+ headers = {"x-api-key": key, "anthropic-version": "2023-06-01"} if provider == "claude" else {"Authorization": "Bearer " + key}
161
+ remaining = timeout - (time.monotonic() - began)
162
+ if remaining <= 0 or stop.is_set():
163
+ raise ModelError("The turn stopped before the fallback request.")
164
+ async with httpx.AsyncClient(timeout=remaining, trust_env=False) as client:
165
+ require_connection(provider)
166
+ if options.get("on_input"):
167
+ options["on_input"](len(framing) + len(transcript))
168
+ send = asyncio.create_task(client.post(url, json=body, headers=headers))
169
+ cancel = asyncio.create_task(stop.wait())
170
+ try:
171
+ done, _ = await asyncio.wait((send, cancel), timeout=remaining, return_when=asyncio.FIRST_COMPLETED)
172
+ if cancel in done:
173
+ raise ModelError("Stopped.")
174
+ if send not in done:
175
+ raise ModelError("The fallback API timed out.")
176
+ response = send.result()
177
+ if not response.is_success:
178
+ raise ModelError(f"The fallback API returned HTTP {response.status_code}. Check the key, API model and billing in Settings.")
179
+ text, sources = response_text(provider, response.json())
180
+ if sources and options.get("on_search"):
181
+ options["on_search"](sources)
182
+ await on_delta(text)
183
+ return text
184
+ except (httpx.HTTPError, ValueError, TypeError, KeyError) as error:
185
+ raise ModelError("The fallback API could not return a reply.") from error
186
+ finally:
187
+ for task in (send, cancel):
188
+ task.cancel()
189
+ await asyncio.gather(send, cancel, return_exceptions=True)