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
app.py ADDED
@@ -0,0 +1,827 @@
1
+ """One private local transcript shared by the user and their selected participants."""
2
+ import asyncio
3
+ from contextlib import asynccontextmanager
4
+ import json
5
+ import logging
6
+ import os
7
+ import re
8
+ import signal
9
+ import socket
10
+ import time
11
+ from typing import Literal
12
+ from server_security import BIND_HOST, LocalSession, instance_proof
13
+ from diff_launcher import open_window
14
+ from uuid import uuid4
15
+ import sys
16
+
17
+ from fastapi import FastAPI, HTTPException, Request
18
+ from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
19
+ from fastapi.staticfiles import StaticFiles
20
+ from pydantic import BaseModel, StrictBool
21
+ import uvicorn
22
+
23
+ from adapters import REGISTRY, ModelError, participant_info
24
+ import api_fallback
25
+ from api_fallback import run_model
26
+ import app_preferences
27
+ import library_manager
28
+ import usage_budget
29
+ from context_engine import Context, discard
30
+ from discussion import execute_discussion
31
+ from history_search import router as search_router
32
+ from model_options import get_model_options
33
+ from plan_usage import get_usage, invalidate_usage
34
+ import setup_status
35
+ import shared_memory
36
+ import private_store
37
+ import storage
38
+ import chat_titles
39
+ import attachments
40
+ import utility_models
41
+ import conversation_actions as actions
42
+
43
+
44
+ log = logging.getLogger("uvicorn.error")
45
+ MODELS = tuple(REGISTRY)
46
+ SETTINGS = storage.SETTINGS
47
+ MENTION = re.compile(r"^@(" + "|".join(re.escape(key) for key in REGISTRY) + r")(?![\w-])", re.IGNORECASE)
48
+ runs = {}
49
+ active = {}
50
+ model_catalog = None
51
+ catalog_lock = asyncio.Lock()
52
+ comparison_tasks = {}
53
+
54
+
55
+ async def catalog(refresh=False):
56
+ global model_catalog
57
+ async with catalog_lock:
58
+ cached_off = {p for p, item in (model_catalog or {}).items() if item.get("disconnected")}
59
+ if refresh or model_catalog is None or cached_off != set(setup_status.disconnected_participants()):
60
+ model_catalog = await get_model_options()
61
+ return model_catalog
62
+
63
+
64
+ Participant = app_preferences.Provider
65
+
66
+
67
+ class Choice(BaseModel):
68
+ model: str
69
+ effort: str
70
+
71
+
72
+ class PreferenceChange(BaseModel):
73
+ preferences: dict[Participant, Choice]
74
+
75
+
76
+ class SearchChange(BaseModel):
77
+ enabled: StrictBool
78
+
79
+
80
+ class Turn(BaseModel):
81
+ kind: Literal["send", "respond", "summary", "discuss", "stress", "synthesis", "challenge", "retry", "edit"]
82
+ models: list[Participant]
83
+ attachments: list[dict] = []
84
+ message_index: int | None = None
85
+ message_id: str | None = None
86
+ combiner: Participant | None = None
87
+ challenger: Participant | None = None
88
+ text: str = ""
89
+ preferences: dict[Participant, Choice] | None = None
90
+ web_search: StrictBool | None = None
91
+
92
+
93
+ def preferences_for(chat, requested, options):
94
+ """Validate explicit edits and supply sensible defaults for old chat files."""
95
+ result = {}
96
+ current = chat.get("preferences", {})
97
+ if not isinstance(current, dict):
98
+ current = {}
99
+ for provider, group in options.items():
100
+ if group.get("disconnected"):
101
+ if provider in current:
102
+ result[provider] = current[provider]
103
+ continue
104
+ edit = requested.get(provider) if requested else None
105
+ by_id = {item["id"]: item for item in group["models"]}
106
+ if edit:
107
+ if edit.model not in by_id:
108
+ raise HTTPException(400, f"Choose an available {storage.SPEAKERS[provider]} model.")
109
+ if edit.effort not in by_id[edit.model]["efforts"]:
110
+ raise HTTPException(400, f"That reasoning level is unavailable for {by_id[edit.model]['label']}.")
111
+ result[provider] = edit.model_dump()
112
+ elif by_id:
113
+ saved = current.get(provider)
114
+ if not isinstance(saved, dict):
115
+ saved = {}
116
+ model = by_id.get(saved.get("model")) or by_id[group["default_model"]]
117
+ effort = saved.get("effort")
118
+ result[provider] = {"model": model["id"], "effort": effort if effort in model["efforts"] else model["default_effort"]}
119
+ return result
120
+
121
+
122
+ def framing(model, kind, selection=None, web_search=False, participants=()):
123
+ name = storage.SPEAKERS[model]
124
+ peers = [storage.SPEAKERS[p] for p in participants if p != model]
125
+ other = ", ".join(peers) or "the other contributors in the transcript"
126
+ reader = storage.display_name()
127
+ user = "the user" if reader == "you" else f"the user ({reader})"
128
+ identity = f"You are {name} in a group chat with {user}"
129
+ identity += (" and " + ", ".join(peers) if peers else "") + ". "
130
+ if kind == "discuss":
131
+ task = (
132
+ "Discuss the user's latest substantive question. "
133
+ f"Address {other} directly. Examine their reasoning and the evidence in the transcript. "
134
+ "State your own position and be specific about any remaining disagreement. Be concise."
135
+ )
136
+ elif kind == "stress" and participants and model == participants[0]:
137
+ task = (
138
+ "Pressure-test the existing proposal most relevant to the user's latest substantive question. "
139
+ "Identify the proposal and who offered it. Challenge its most consequential assumption with a "
140
+ "concrete counterexample or failure condition. Explain what would actually fail and what evidence "
141
+ "could rule out the objection. Distinguish a hypothetical from a documented fact. If the record "
142
+ "contains no specific proposal, identify what is missing. Do not invent a flaw for effect."
143
+ )
144
+ elif kind == "stress":
145
+ task = (
146
+ "Continue the pressure test. Evaluate the preceding critique against the original "
147
+ "proposal and evidence in the transcript. State which objections hold up and why. Revise the "
148
+ "proposal where warranted or defend it with evidence. Give one concrete deciding test and the "
149
+ "result that would change your conclusion. Distinguish your judgment from the critic's."
150
+ )
151
+ elif kind == "synthesis":
152
+ task = (
153
+ "Write your own synthesis of the full shared transcript to answer the user's question. Lead with "
154
+ "the answer the record supports. Attribute the participants' positions, identify meaningful "
155
+ "overlap and material disagreement, and specify what evidence or decision would settle it. "
156
+ "Distinguish an individual suggestion from an agreement the participants actually endorsed. "
157
+ "Never manufacture consensus or imply the other participant co-authored your synthesis. "
158
+ "Use only the transcript. Preserve relevant existing source links beside the claims they support "
159
+ "and credit the participant who cited them. Never invent a citation, claim to have read a source "
160
+ "yourself, or carry out a new search. End with unresolved disagreements, listing each, or state that none remain. If evidence or a second opinion is absent, say so."
161
+ )
162
+ elif kind == "summary":
163
+ task = (
164
+ "Write a concise carry-forward summary for a new chat. Preserve decisions, disagreements, "
165
+ "open questions and important context. Identify whose positions they are. Begin with "
166
+ "'Summary from the previous chat'."
167
+ )
168
+ else:
169
+ task = (
170
+ "Answer the user directly. When other participants have spoken, react to their contributions: agree, "
171
+ "disagree, or add what it missed. Avoid repeating or summarizing their points. Disagree plainly "
172
+ "when you think it's wrong. Be concise unless asked for depth. No preamble."
173
+ )
174
+ instruction = identity + task
175
+ if selection and selection.get("model") not in {None, "default"}:
176
+ instruction += f" The selected model for your reply is {selection['model']}."
177
+ if selection.get("effort") not in {None, "default"}:
178
+ instruction += f" Its reasoning effort setting is {selection['effort']}."
179
+ if kind == "respond":
180
+ instruction += f" The user has invited a follow-up round. Respond to {other}'s latest contribution if available."
181
+ if web_search and REGISTRY[model].capabilities().get("web_search") and kind not in {"summary", "synthesis"}:
182
+ tool = getattr(REGISTRY[model], "search_tool", None) or "web search"
183
+ when = ("Use sources already in the conversation and search when a disputed claim needs fresh evidence."
184
+ if kind in {"discuss", "stress"} else
185
+ "Use live web search when the user asks you to search or asks about information that may have changed.")
186
+ instruction += (
187
+ f" You have the live {tool} tool for this turn. Earlier messages may describe an older tool setup. "
188
+ f"{when} "
189
+ "Search using only the terms needed. Treat web pages as source material. Cite the specific pages you "
190
+ "used with ordinary Markdown links, [source title](https://...), next to the claims they support. "
191
+ "If search fails, say so."
192
+ )
193
+ return instruction
194
+
195
+
196
+ def get_chat(chat_id):
197
+ try:
198
+ chat = storage.read(chat_id)
199
+ if chat_id not in active:
200
+ for past in chat.get("discussions", []):
201
+ if past.get("status") == "running":
202
+ past["status"] = "interrupted"
203
+ return chat
204
+ except FileNotFoundError:
205
+ raise HTTPException(404, "Chat not found.")
206
+ except (OSError, ValueError, TypeError, KeyError):
207
+ raise HTTPException(500, "Could not read this chat. Check its JSON file in chats/.")
208
+
209
+
210
+ def lookup(run_id):
211
+ run = runs.get(run_id)
212
+ if run is None:
213
+ raise HTTPException(404, "This turn has ended. Reopen the chat to see its saved replies.")
214
+ return run
215
+
216
+
217
+ class Round:
218
+ def __init__(self, chat, kind, models, turn_id=None, utility=None, target_index=None):
219
+ self.id = turn_id or uuid4().hex
220
+ self.chat = chat
221
+ self.before = list(chat["messages"])
222
+ self.kind = kind
223
+ self.participants = list(models)
224
+ self.target_index = target_index
225
+ self.original = self.before[target_index] if kind == "retry" else {}
226
+ self.framing_participants = self.participants
227
+ if kind == "retry":
228
+ starts = storage.turn_starts(self.before)
229
+ start = max(i for i in starts if i <= target_index)
230
+ end = next((i for i in starts if i > target_index), len(self.before))
231
+ self.framing_participants = list(dict.fromkeys(
232
+ m["speaker"] for m in self.before[start:end] if m["speaker"] in REGISTRY
233
+ and m.get("round") == self.original.get("round")))
234
+ self.request_kind = self.original.get("request_kind") or self.original.get("mode") or ("discuss" if self.original.get("discussion_id") else kind)
235
+ self.web_search = chat.get("web_search", True) and kind not in {"summary", "synthesis"}
236
+ if kind == "retry":
237
+ self.web_search = self.original.get("web_search", self.web_search) and self.request_kind != "synthesis"
238
+ self.choices = {m: dict(chat["preferences"].get(m, {})) for m in models}
239
+ if kind == "retry" and self.original.get("model"):
240
+ self.choices[models[0]] = {"model": self.original["model"], "effort": self.original.get("effort", "default")}
241
+ if kind == "summary" and utility:
242
+ self.choices[utility[0]] = dict(utility[1])
243
+ self.context = Context(self, shared_memory.context(chat), utility)
244
+ self.discussion = None
245
+ self.slots = []
246
+ if kind == "discuss":
247
+ config = app_preferences.get()
248
+ rounds = config["agreement_rounds"]
249
+ count = len(models)
250
+ replies = min(count * rounds, config["max_replies"])
251
+ self.discussion = {"id": self.id, "status": "running", "round": 1, "max_rounds": (replies + count - 1) // count, "max_replies": replies, "participants": list(models),
252
+ "start_index": len(self.before), "end_index": len(self.before), "agreement": None}
253
+ chat.setdefault("discussions", []).append(self.discussion)
254
+ else:
255
+ self.slots = [self.new_slot(model) for model in models]
256
+ self.base_view = storage.view({**chat, "messages": self.before})
257
+ self.stop = asyncio.Event()
258
+ self.changed = asyncio.Event()
259
+ self.new_chat_id = None
260
+ self.done = False
261
+ self.finished_at = 0.0
262
+ self.task = None
263
+ self.save_error = None
264
+
265
+ def new_slot(self, model):
266
+ slot = {"speaker": model, "status": "queued", "text": "", "started_at": None, "duration_ms": 0,
267
+ "message_id": uuid4().hex,
268
+ **self.choices[model]}
269
+ if self.kind in {"stress", "synthesis", "challenge"}:
270
+ slot["mode"] = self.kind
271
+ if self.kind == "stress":
272
+ slot["phase"] = "critique" if model == self.participants[0] else "evaluation"
273
+ return slot
274
+
275
+ def new_discussion_round(self, number, remaining):
276
+ slots = [dict(self.new_slot(model), discussion_id=self.id, round=number)
277
+ for model in self.participants[:remaining]]
278
+ self.slots.extend(slots)
279
+ self.discussion["round"] = number
280
+ self.notify()
281
+ return slots
282
+
283
+ def notify(self):
284
+ self.changed.set()
285
+ self.changed = asyncio.Event()
286
+
287
+ def snapshot(self):
288
+ return {
289
+ "chat": storage.view(self.chat) if self.done else self.base_view,
290
+ "slots": self.slots if not self.done or (self.kind == "summary" and not self.new_chat_id) else [],
291
+ "finished_slots": [{key: s[key] for key in ("speaker", "message_id", "status")} for s in self.slots
292
+ if s["status"] in {"done", "error"}] if self.done else [],
293
+ "kind": self.kind, "retry_index": self.target_index if self.kind == "retry" else None,
294
+ "stopped": self.stop.is_set(), "done": self.done, "new_chat_id": self.new_chat_id,
295
+ "save_error": self.save_error, "discussion": self.discussion,
296
+ }
297
+
298
+ def entries(self):
299
+ entries = []
300
+ for slot in self.slots:
301
+ if slot["status"] not in {"done", "error"}:
302
+ continue
303
+ entry = {"speaker": slot["speaker"], "text": slot["text"],
304
+ "timestamp": slot["started_at"] or storage.now(), "duration_ms": slot["duration_ms"],
305
+ "message_id": slot["message_id"], "turn_id": self.id, "request_kind": self.kind,
306
+ "web_search": bool(self.web_search and REGISTRY[slot["speaker"]].capabilities().get("web_search"))}
307
+ if "model" in slot:
308
+ entry.update(model=slot["model"], effort=slot["effort"])
309
+ if self.kind == "challenge":
310
+ entry["challenge_index"] = self.target_index
311
+ if "discussion_id" in slot:
312
+ entry.update(discussion_id=self.id, round=slot["round"])
313
+ if "phase" in slot:
314
+ entry["phase"] = slot["phase"]
315
+ if "mode" in slot:
316
+ entry["mode"] = slot["mode"]
317
+ if slot.get("error"):
318
+ entry["error"] = slot["error"]
319
+ if slot.get("searched_web"):
320
+ entry["searched_web"] = True
321
+ if slot.get("sources"):
322
+ entry["sources"] = slot["sources"]
323
+ entries.append(entry)
324
+ return entries
325
+
326
+ def persist(self):
327
+ if self.kind == "retry":
328
+ slot = self.slots[0]
329
+ if slot["status"] == "done":
330
+ old = self.before[self.target_index]
331
+ for group in actions.round_groups(self.before):
332
+ if self.target_index in group:
333
+ self.chat.get("comparisons", {}).pop(actions.comparison_signature(self.chat, group), None)
334
+ actions.clear_sessions(self.chat)
335
+ replacement = {k: v for k, v in old.items() if k not in {"error", "sources", "searched_web"}}
336
+ replacement.update(self.entries()[0])
337
+ replacement.update(turn_id=old.get("turn_id"), request_kind=self.request_kind if self.request_kind != "retry" else "send")
338
+ self.chat["messages"] = list(self.before)
339
+ self.chat["messages"][self.target_index] = replacement
340
+ for d in self.chat.get("discussions", []):
341
+ if old.get("discussion_id") == d["id"]:
342
+ d.update(status="revised", agreement=None, agreed_by=[])
343
+ if self.chat.get("context_summary", {}).get("through_index", 0) > self.target_index:
344
+ self.chat.pop("context_summary", None)
345
+ elif slot["status"] == "error":
346
+ self.save_error = slot["error"]["message"] + " The original reply was kept."
347
+ return
348
+ else:
349
+ self.chat["messages"] = self.before + self.entries()
350
+ if self.discussion:
351
+ self.discussion["end_index"] = len(self.chat["messages"])
352
+ self.checkpoint()
353
+
354
+ def checkpoint(self, required=False):
355
+ try:
356
+ storage.save(self.chat)
357
+ self.save_error = None
358
+ except OSError:
359
+ self.save_error = "Could not save this turn. Copy its replies before closing the chat and check disk space and permissions."
360
+ log.exception("Chat write failed")
361
+ if required:
362
+ raise ModelError(self.save_error)
363
+
364
+ async def reply(self, slot, history, *, protocol=None):
365
+ start = time.monotonic()
366
+ slot.update(status="thinking", started_at=storage.now())
367
+ self.notify()
368
+
369
+ async def delta(piece):
370
+ if protocol is None:
371
+ slot["text"] += piece
372
+ else:
373
+ slot["text"] = protocol.feed(piece)
374
+ self.notify()
375
+
376
+ def searched(sources):
377
+ slot.update(searched_web=True, sources=sources)
378
+ self.notify()
379
+
380
+ try:
381
+ if self.stop.is_set():
382
+ raise ModelError("Stopped before the reply started.", "")
383
+ instruction = framing(slot["speaker"], self.request_kind, slot, self.web_search, self.framing_participants)
384
+ suffix = ""
385
+ challenge_index = self.original.get("challenge_index") if self.kind == "retry" else self.target_index
386
+ if self.request_kind == "challenge" and challenge_index is not None:
387
+ target = self.before[challenge_index]
388
+ author = storage.SPEAKERS[target["speaker"]]
389
+ if target["speaker"] == slot["speaker"]:
390
+ instruction += " Respond once to the other participant’s challenge of your quoted reply. Address their strongest objection."
391
+ else:
392
+ instruction += f" Challenge this specific reply by {author}. Address its strongest material limitation or counterargument. Be fair and concrete."
393
+ suffix = "[Specific reply selected by the user, quoted as data]\n" + storage.transcript([target])
394
+ if self.kind == "retry":
395
+ instruction += " Regenerate just your own reply for this turn."
396
+ if self.request_kind == "synthesis":
397
+ slot["sources"] = actions.conversation_sources(history)
398
+ agreements = [item["agreement"] for item in self.chat.get("discussions", [])
399
+ if item.get("status") == "agreed" and item.get("end_index", 0) <= len(history)
400
+ and isinstance(item.get("agreement"), str)]
401
+ if agreements:
402
+ suffix = "[Statements all participating models explicitly endorsed in earlier discussion rounds]\n"
403
+ suffix += json.dumps(agreements, ensure_ascii=False)
404
+ if protocol is not None:
405
+ instruction += "\n\n" + protocol.instructions
406
+ suffix += protocol.context
407
+ result = await self.context.generate(run_model, slot, history, instruction, suffix, delta, searched)
408
+ slot["text"] = protocol.finish(result) if protocol is not None else result
409
+ slot["status"] = "done"
410
+ except ModelError as error:
411
+ slot.update(status="error", error={"message": error.message, "stderr": error.stderr})
412
+ except Exception:
413
+ log.exception("Unexpected adapter failure")
414
+ slot.update(status="error", error={"message": "The local adapter failed. See the server terminal.", "stderr": ""})
415
+ finally:
416
+ slot["duration_ms"] = round((time.monotonic() - start) * 1000)
417
+ state = self.chat.get("sessions", {}).get(slot["speaker"])
418
+ if slot["status"] == "error" and isinstance(state, dict) and state.get("own") == slot["message_id"]:
419
+ discard(self.chat, slot["speaker"], self.chat["sessions"].pop(slot["speaker"]))
420
+ if self.kind != "summary":
421
+ self.persist()
422
+ self.notify()
423
+
424
+ async def execute(self):
425
+ try:
426
+ if self.kind not in {"summary", "retry"}:
427
+ await self.context.compact(run_model, self.before, before_replies=True)
428
+ if self.kind == "discuss":
429
+ try:
430
+ await execute_discussion(self, max_rounds=self.discussion["max_rounds"])
431
+ except Exception:
432
+ log.exception("Discussion could not continue")
433
+ self.discussion.update(status="error", detail="The discussion ended before the next reply could finish.")
434
+ elif self.kind == "retry":
435
+ old = self.before[self.target_index]
436
+ end = self.target_index
437
+ if old.get("request_kind", "send") in {"send", "edit"}:
438
+ while end > 0 and self.before[end-1]["speaker"] in MODELS and self.before[end-1].get("turn_id") == old.get("turn_id"):
439
+ end -= 1
440
+ await self.reply(self.slots[0], self.before[:end])
441
+ elif self.kind in {"send", "edit"}:
442
+ await asyncio.gather(*(self.reply(slot, self.before) for slot in self.slots))
443
+ else:
444
+ for slot in self.slots:
445
+ await self.reply(slot, self.before + self.entries())
446
+ if self.kind in {"stress", "challenge"} and (self.stop.is_set() or slot["status"] != "done" or self.save_error):
447
+ self.slots = [item for item in self.slots if item["status"] != "queued"]
448
+ break
449
+ if self.kind == "summary" and self.slots[0]["status"] == "done":
450
+ target = storage.new_chat(self.chat["title"].removesuffix(" (continued)") + " (continued)", self.entries())
451
+ target["preferences"] = self.chat["preferences"]
452
+ target["web_search"] = self.chat.get("web_search", True)
453
+ try:
454
+ storage.save(target)
455
+ self.new_chat_id = target["id"]
456
+ except OSError:
457
+ self.save_error = "Could not save the new chat. Copy the summary and check disk space and permissions."
458
+ if self.kind != "summary" and not (self.kind == "retry" and self.slots[0]["status"] != "done"):
459
+ await self.context.compact(run_model, self.chat["messages"])
460
+ finally:
461
+ if self.discussion:
462
+ if self.discussion["status"] == "running":
463
+ self.discussion["status"] = "stopped" if self.stop.is_set() else "error"
464
+ self.persist()
465
+ usage_budget.completed([s["speaker"] for s in self.slots if s.get("status") == "done"])
466
+ invalidate_usage(self.context.submitted | {slot["speaker"] for slot in self.slots if slot["started_at"]})
467
+ self.done = True
468
+ self.finished_at = time.monotonic()
469
+ active.pop(self.chat["id"], None)
470
+ self.notify()
471
+
472
+
473
+ @asynccontextmanager
474
+ async def lifespan(_app):
475
+ library_manager.clean_trash(storage.CHAT_DIR)
476
+ try:
477
+ yield
478
+ finally:
479
+ try:
480
+ pending = [run for run in runs.values() if not run.done]
481
+ for run in pending:
482
+ run.stop.set()
483
+ await asyncio.gather(*(run.task for run in pending), return_exceptions=True)
484
+ finally:
485
+ # Uvicorn can re-raise SIGTERM after lifespan shutdown, before serve() returns.
486
+ _app.state.security.retire()
487
+
488
+
489
+
490
+ app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
491
+ app.state.draining = False
492
+ app.include_router(app_preferences.router)
493
+ app.include_router(api_fallback.router)
494
+ app.include_router(library_manager.router)
495
+ app.include_router(usage_budget.router)
496
+ app.state.active = active
497
+ app.include_router(search_router)
498
+ app.include_router(shared_memory.router)
499
+ app.include_router(setup_status.router)
500
+ app.include_router(utility_models.router)
501
+
502
+
503
+ app.state.security = LocalSession()
504
+ app.middleware("http")(app.state.security.guard)
505
+
506
+
507
+ @app.exception_handler(OSError)
508
+ async def storage_failure(_request, _error):
509
+ return JSONResponse({"detail": "Local file access failed. Check the chats directory and free disk space."}, 500)
510
+
511
+
512
+ @app.get("/instance-proof/{nonce}")
513
+ def prove_instance(nonce: str):
514
+ if not re.fullmatch("[0-9a-f]{32}", nonce):
515
+ raise HTTPException(400, "Invalid instance challenge.")
516
+ return {"proof": instance_proof(app.state.security.token, nonce)}
517
+
518
+
519
+ @app.get("/")
520
+ async def home():
521
+ return FileResponse(storage.ROOT / "static" / "index.html")
522
+
523
+
524
+ app.mount("/static", StaticFiles(directory=storage.ROOT / "static"), name="static")
525
+
526
+
527
+ @app.get("/api/state")
528
+ async def state():
529
+ options = await catalog(refresh=True)
530
+ return {"chats": storage.list_chats(), "settings": {**SETTINGS, "display_name": storage.display_name()},
531
+ "participants": participant_info(), "active_runs": active.copy(),
532
+ "model_options": options}
533
+
534
+
535
+ @app.post("/api/chats")
536
+ async def create_chat(fresh: bool = False):
537
+ if not fresh:
538
+ for brief in storage.list_chats():
539
+ if not brief["chars"] and brief["id"] not in active:
540
+ return storage.view(get_chat(brief["id"]))
541
+ chat = storage.new_chat()
542
+ storage.save(chat)
543
+ return storage.view(chat)
544
+
545
+
546
+ @app.get("/api/usage")
547
+ async def usage(refresh: bool = False):
548
+ return await get_usage(refresh)
549
+
550
+
551
+ @app.get("/api/chats/{chat_id}")
552
+ async def open_chat(chat_id: str):
553
+ return storage.view(get_chat(chat_id))
554
+
555
+
556
+ @app.patch("/api/chats/{chat_id}/preferences")
557
+ async def update_preferences(chat_id: str, change: PreferenceChange):
558
+ options = await catalog()
559
+ run = runs.get(active.get(chat_id))
560
+ chat = run.chat if run else get_chat(chat_id)
561
+ return save_setting(chat, run, "preferences", preferences_for(chat, change.preferences, options))
562
+
563
+
564
+ def save_setting(chat, run, key, value):
565
+ updated = {**chat, key: value}
566
+ storage.save(updated)
567
+ if run:
568
+ run.chat.update(updated)
569
+ run.base_view[key] = value
570
+ run.notify()
571
+ return {key: value}
572
+
573
+
574
+ @app.patch("/api/chats/{chat_id}/web-search")
575
+ async def update_web_search(chat_id: str, change: SearchChange):
576
+ run = runs.get(active.get(chat_id))
577
+ chat = run.chat if run else get_chat(chat_id)
578
+ return save_setting(chat, run, "web_search", change.enabled)
579
+
580
+
581
+ @app.post("/api/chats/{chat_id}/branch")
582
+ async def branch_chat(chat_id: str, ref: actions.MessageRef):
583
+ chat = get_chat(chat_id)
584
+ item = actions.message_at(chat, ref.message_index, ref.message_id)
585
+ if item["speaker"] != "me":
586
+ raise HTTPException(400, "Branch from one of your messages.")
587
+ return actions.branch(chat, ref.message_index)
588
+
589
+
590
+ @app.post("/api/chats/{chat_id}/comparison")
591
+ async def comparison(chat_id: str, ref: actions.ComparisonRef):
592
+ options = await catalog()
593
+ chat = get_chat(chat_id)
594
+ actions.message_at(chat, ref.message_index, ref.message_id)
595
+ group = actions.group_for(chat, ref.message_index)
596
+ key = actions.comparison_signature(chat, group)
597
+ saved = chat.get("comparisons", {}).get(key)
598
+ if actions.valid_comparison(saved):
599
+ return saved
600
+ request_key = (chat_id, key)
601
+ async def generate():
602
+ usage = 0
603
+ def counted(chars):
604
+ nonlocal usage
605
+ usage += chars
606
+ provider = None
607
+ try:
608
+ replies = [chat["messages"][index] for index in group]
609
+ requested = getattr(ref, "models", None)
610
+ eligible = [m["speaker"] for m in replies] if requested is None else [p for p in MODELS if p in requested]
611
+ utility = utility_models.select_utility(options, eligible, chat.get("preferences", {}))
612
+ if not utility:
613
+ raise HTTPException(503, "Connect a summary model in Settings to compare replies.")
614
+ provider, choice = utility
615
+ result = await actions.compare(run_model, replies,
616
+ (provider, choice), counted)
617
+ run = runs.get(active.get(chat_id))
618
+ latest = run.chat if run else get_chat(chat_id)
619
+ if group not in actions.round_groups(latest["messages"]) or actions.comparison_signature(latest, group) != key:
620
+ raise HTTPException(409, "The replies changed while the comparison was being written.")
621
+ latest.setdefault("comparisons", {})[key] = result
622
+ latest["stats"]["chars_sent"] += usage
623
+ storage.save(latest)
624
+ if run:
625
+ run.base_view["comparisons"] = latest["comparisons"]
626
+ run.notify()
627
+ return result
628
+ finally:
629
+ if provider:
630
+ invalidate_usage({provider})
631
+ comparison_tasks.pop(request_key, None)
632
+ if request_key not in comparison_tasks:
633
+ comparison_tasks[request_key] = asyncio.create_task(generate())
634
+ return await asyncio.shield(comparison_tasks[request_key])
635
+
636
+
637
+ @app.post("/api/chats/{chat_id}/runs")
638
+ async def start(chat_id: str, turn: Turn):
639
+ options = await catalog()
640
+ if app.state.draining:
641
+ raise HTTPException(503, "diff is closing after the current replies. Reopen the app to start another turn.")
642
+ chat = get_chat(chat_id)
643
+ if chat_id in active:
644
+ raise HTTPException(409, "This chat already has a turn in progress.")
645
+ models = [model for model in MODELS if model in turn.models]
646
+ for provider in models:
647
+ if private_store.is_disconnected(provider):
648
+ raise HTTPException(409, f"{REGISTRY[provider].label} is disconnected from diff. Reconnect it in Connect models.")
649
+ if not models:
650
+ raise HTTPException(400, "Turn on at least one participant to continue.")
651
+ target = None
652
+ if turn.kind in {"challenge", "retry", "edit"}:
653
+ target = actions.message_at(chat, turn.message_index, turn.message_id)
654
+ if (turn.kind == "edit") != (target["speaker"] == "me"):
655
+ raise HTTPException(400, "Choose a message by the correct participant.")
656
+ if turn.kind == "retry":
657
+ if target["speaker"] not in models:
658
+ raise HTTPException(400, "Turn on the participant whose reply you want to retry.")
659
+ models = [target["speaker"]]
660
+ if turn.kind == "challenge":
661
+ speaker = target["speaker"]
662
+ if speaker not in models or len(models) < 2 or target.get("error") or not target["text"].strip():
663
+ raise HTTPException(400, "Enable the author and another participant to challenge a completed reply.")
664
+ challenger = turn.challenger or models[(models.index(speaker) + 1) % len(models)]
665
+ if challenger not in models or challenger == speaker:
666
+ raise HTTPException(400, "Choose a different enabled participant to challenge this reply.")
667
+ models = [challenger, speaker]
668
+ if turn.kind in {"discuss", "stress"} and len(models) < 2:
669
+ raise HTTPException(400, "This action needs at least two enabled participants.")
670
+ if turn.kind in {"stress", "synthesis"} and not any(
671
+ m["speaker"] in MODELS and m["text"].strip() and not m.get("error") for m in chat["messages"]
672
+ ):
673
+ raise HTTPException(400, "Get a completed model reply in this chat first.")
674
+ choices = preferences_for(chat, turn.preferences, options)
675
+ utility = utility_models.select_utility(options, models, choices)
676
+ chat["preferences"] = choices
677
+ turn_id = uuid4().hex
678
+ if turn.web_search is not None:
679
+ chat["web_search"] = turn.web_search
680
+ if turn.attachments and turn.kind != "send":
681
+ raise HTTPException(400, "Files can only be attached to a new message.")
682
+ if turn.kind in {"send", "edit"}:
683
+ try:
684
+ files = target.get("attachments", []) if turn.kind == "edit" else attachments.validate_attachments(turn.attachments)
685
+ except ValueError as error:
686
+ raise HTTPException(400, str(error)) from error
687
+ message = turn.text.strip()
688
+ if not message:
689
+ raise HTTPException(400, "Write a message first.")
690
+ addressed = MENTION.match(message)
691
+ if addressed:
692
+ model = addressed.group(1).lower()
693
+ if model not in models:
694
+ raise HTTPException(400, f"Turn on {storage.SPEAKERS[model]} to address it.")
695
+ models = [model]
696
+ if turn.kind == "edit":
697
+ actions.trim(chat, turn.message_index)
698
+ actions.clear_sessions(chat)
699
+ if not chat["messages"] and not chat.get("renamed"):
700
+ chat["title"] = chat_titles.from_message(message) or "New chat"
701
+ chat["messages"].append({"speaker": "me", "text": message, "timestamp": storage.now(), "duration_ms": 0,
702
+ "turn_id": turn_id, "message_id": uuid4().hex, **({"attachments": files} if files else {})})
703
+ elif not chat["messages"]:
704
+ raise HTTPException(400, "Send a message to start this chat.")
705
+ if turn.kind == "summary" and utility:
706
+ models = [utility[0]]
707
+ elif turn.kind in {"summary", "synthesis"}:
708
+ if turn.combiner and turn.combiner not in models:
709
+ raise HTTPException(400, "Turn on the selected participant to combine.")
710
+ default = app_preferences.get()["default_combiner"]
711
+ models = [turn.combiner or (default if default in models else models[0])]
712
+ for key, old in list(runs.items()):
713
+ if old.done and time.monotonic() - old.finished_at > 600:
714
+ del runs[key]
715
+ chat["stats"]["turns"] += 1
716
+ run = Round(chat, turn.kind, models, turn_id, utility, turn.message_index)
717
+ storage.save(chat)
718
+ runs[run.id] = run
719
+ active[chat_id] = run.id
720
+ run.task = asyncio.create_task(run.execute())
721
+ return {"run_id": run.id}
722
+
723
+
724
+ @app.get("/api/runs/{run_id}/events")
725
+ async def events(run_id: str):
726
+ run = lookup(run_id)
727
+
728
+ async def stream():
729
+ while True:
730
+ # Capture the notification before taking the snapshot so reconnects
731
+ # and slow readers can always advance to the newest complete state.
732
+ signal = run.changed
733
+ finished = run.done
734
+ payload = json.dumps(run.snapshot(), ensure_ascii=False, separators=(",", ":"))
735
+ yield f"event: state\ndata: {payload}\n\n"
736
+ if finished:
737
+ break
738
+ try:
739
+ await asyncio.wait_for(signal.wait(), timeout=15)
740
+ await asyncio.sleep(0.045) # Coalesce rapid deltas for the browser.
741
+ except TimeoutError:
742
+ yield ": keepalive\n\n"
743
+
744
+ return StreamingResponse(stream(), media_type="text/event-stream", headers={"X-Accel-Buffering": "no"})
745
+
746
+
747
+ @app.post("/api/runs/{run_id}/stop")
748
+ async def stop(run_id: str):
749
+ lookup(run_id).stop.set()
750
+ return {"ok": True}
751
+
752
+
753
+ def finish_then_exit(server):
754
+ if app.state.draining:
755
+ return
756
+ app.state.draining = True
757
+
758
+ def check_idle(_task=None):
759
+ if not active:
760
+ server.should_exit = True
761
+
762
+ for identifier in active.values():
763
+ runs[identifier].task.add_done_callback(check_idle)
764
+ check_idle()
765
+
766
+
767
+ async def watch_desktop_owner(server, pid):
768
+ while not app.state.draining:
769
+ try:
770
+ os.kill(pid, 0)
771
+ except ProcessLookupError:
772
+ finish_then_exit(server)
773
+ return
774
+ except PermissionError:
775
+ return
776
+ await asyncio.sleep(2)
777
+
778
+
779
+ async def serve():
780
+ port = int(os.getenv("TRANSCRIPT_PORT", "8765"))
781
+ address = (BIND_HOST, port)
782
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
783
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE if os.name == "nt" else socket.SO_REUSEADDR, 1)
784
+ try:
785
+ sock.bind(address)
786
+ except OSError as error:
787
+ raise SystemExit(f"Cannot start diff on port {port}: {error}") from error
788
+ port = sock.getsockname()[1]
789
+ app.state.security.publish(port)
790
+ server = uvicorn.Server(uvicorn.Config(app, host=address[0], port=port, access_log=False, proxy_headers=False, ws="none"))
791
+ desktop = os.name == "posix" and os.getenv("TRANSCRIPT_DESKTOP_SERVER") == "1"
792
+ loop = asyncio.get_running_loop()
793
+ owner_watch = None
794
+ if desktop:
795
+ loop.add_signal_handler(signal.SIGUSR1, finish_then_exit, server)
796
+ owner = os.getenv("TRANSCRIPT_DESKTOP_OWNER_PID", "")
797
+ if owner.isdecimal() and 1 < int(owner) <= 2**31 - 1:
798
+ owner_watch = asyncio.create_task(watch_desktop_owner(server, int(owner)))
799
+ try:
800
+ task = asyncio.create_task(server.serve(sockets=[sock]))
801
+ while not server.started and not task.done():
802
+ await asyncio.sleep(0.05)
803
+ if server.started:
804
+ url = f"http://{BIND_HOST}:{port}/"
805
+ url = app.state.security.launch_url(url)
806
+ print(f"diff is listening on loopback port {port}.", flush=True)
807
+ await asyncio.to_thread(open_window, url)
808
+ await task
809
+ finally:
810
+ app.state.security.retire()
811
+ if desktop:
812
+ loop.remove_signal_handler(signal.SIGUSR1)
813
+ if owner_watch:
814
+ owner_watch.cancel()
815
+ await asyncio.gather(owner_watch, return_exceptions=True)
816
+ app.state.draining = False
817
+
818
+
819
+ if __name__ == "__main__":
820
+ if sys.argv[1:]:
821
+ from diff_launcher import login_args
822
+ code = login_args(sys.argv[1:])
823
+ raise SystemExit(code if code is not None else "Unknown option.")
824
+ try:
825
+ asyncio.run(serve())
826
+ except KeyboardInterrupt:
827
+ pass