diff-chat 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- adapters/README.md +28 -0
- adapters/__init__.py +48 -0
- adapters/_base.py +102 -0
- adapters/_cli.py +405 -0
- adapters/claude.py +141 -0
- adapters/gemini.py +323 -0
- adapters/gpt.py +217 -0
- adapters/local.py +146 -0
- adapters/registry.py +33 -0
- api_fallback.py +189 -0
- app.py +827 -0
- app_preferences.py +205 -0
- archive_schema.py +142 -0
- attachments.py +129 -0
- chat_titles.py +60 -0
- connection_handoff.py +64 -0
- context_engine.py +256 -0
- conversation_actions.py +160 -0
- diff_chat-0.1.0.dist-info/METADATA +101 -0
- diff_chat-0.1.0.dist-info/RECORD +91 -0
- diff_chat-0.1.0.dist-info/WHEEL +4 -0
- diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
- diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
- diff_chat_assets/memory.example.md +1 -0
- diff_chat_assets/prompts/about_you_export.md +19 -0
- diff_chat_assets/settings.json +6 -0
- diff_chat_assets/static/about-you-parser.js +46 -0
- diff_chat_assets/static/about-you.js +171 -0
- diff_chat_assets/static/actions.css +275 -0
- diff_chat_assets/static/actions.js +650 -0
- diff_chat_assets/static/app.css +345 -0
- diff_chat_assets/static/app.js +1344 -0
- diff_chat_assets/static/attachments.js +80 -0
- diff_chat_assets/static/brand/favicon-32.png +0 -0
- diff_chat_assets/static/brand/icon.svg +11 -0
- diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
- diff_chat_assets/static/brand/wordmark-light.svg +13 -0
- diff_chat_assets/static/characters/CREDITS.md +7 -0
- diff_chat_assets/static/characters/characters.css +37 -0
- diff_chat_assets/static/characters/claude.json +507 -0
- diff_chat_assets/static/characters/claude.png +0 -0
- diff_chat_assets/static/characters/claude.webp +0 -0
- diff_chat_assets/static/characters/gemini.json +54 -0
- diff_chat_assets/static/characters/gemini.png +0 -0
- diff_chat_assets/static/characters/gemini.webp +0 -0
- diff_chat_assets/static/characters/gpt.json +507 -0
- diff_chat_assets/static/characters/gpt.png +0 -0
- diff_chat_assets/static/characters/gpt.webp +0 -0
- diff_chat_assets/static/characters/local.json +387 -0
- diff_chat_assets/static/characters/local.png +0 -0
- diff_chat_assets/static/characters/local.webp +0 -0
- diff_chat_assets/static/characters/player.js +318 -0
- diff_chat_assets/static/chat-filing.js +84 -0
- diff_chat_assets/static/controls.js +194 -0
- diff_chat_assets/static/corners.css +59 -0
- diff_chat_assets/static/craft.css +246 -0
- diff_chat_assets/static/drafts.js +41 -0
- diff_chat_assets/static/index.html +208 -0
- diff_chat_assets/static/library.css +30 -0
- diff_chat_assets/static/library.js +181 -0
- diff_chat_assets/static/memory.js +81 -0
- diff_chat_assets/static/preference-dialog.js +21 -0
- diff_chat_assets/static/preferences.css +56 -0
- diff_chat_assets/static/session.js +46 -0
- diff_chat_assets/static/settings.css +111 -0
- diff_chat_assets/static/settings.js +463 -0
- diff_chat_assets/static/setup.js +238 -0
- diff_chat_assets/static/utility.js +64 -0
- diff_chat_assets/static/vendor/LICENSES.txt +531 -0
- diff_chat_assets/static/vendor/highlight.min.js +1262 -0
- diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
- diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
- diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
- diff_launcher.py +93 -0
- discussion.py +239 -0
- history_search.py +68 -0
- library_manager.py +251 -0
- model_options.py +132 -0
- plan_usage.py +72 -0
- private_store.py +71 -0
- probe.py +195 -0
- runtime_paths.py +195 -0
- server_security.py +100 -0
- setup_status.py +123 -0
- shared_memory.py +189 -0
- storage.py +185 -0
- usage_budget.py +77 -0
- usage_claude.py +110 -0
- usage_codex.py +170 -0
- usage_gemini.py +70 -0
- utility_models.py +104 -0
app_preferences.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Local application preferences. Provider secrets live exclusively in the system keychain."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Annotated, Literal
|
|
7
|
+
|
|
8
|
+
from fastapi import APIRouter, HTTPException
|
|
9
|
+
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, ValidationError, create_model, field_validator
|
|
10
|
+
|
|
11
|
+
from adapters import REGISTRY
|
|
12
|
+
import private_store
|
|
13
|
+
import storage
|
|
14
|
+
from runtime_paths import cli_override
|
|
15
|
+
|
|
16
|
+
router = APIRouter()
|
|
17
|
+
def known_provider(value):
|
|
18
|
+
if value not in REGISTRY:
|
|
19
|
+
raise ValueError("Unknown participant.")
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
Provider = Annotated[str, AfterValidator(known_provider)]
|
|
24
|
+
VERSION = "0.1.0"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Role(BaseModel):
|
|
28
|
+
mode: Literal["none", "for", "against", "custom"] = "none"
|
|
29
|
+
text: str = Field(default="", max_length=1200)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ProviderSettings(BaseModel):
|
|
33
|
+
model_config = ConfigDict(extra="forbid")
|
|
34
|
+
cli_path: str = Field(default="", max_length=2048)
|
|
35
|
+
model: str = Field(default="", max_length=128)
|
|
36
|
+
effort: str = Field(default="", max_length=32)
|
|
37
|
+
timeout: int = Field(default=120, ge=1, le=3600)
|
|
38
|
+
api_fallback: bool = False
|
|
39
|
+
api_model: str = Field(default="", max_length=128, pattern=r"^[a-zA-Z0-9._-]*$")
|
|
40
|
+
role: Role = Field(default_factory=Role)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LocalSettings(ProviderSettings):
|
|
44
|
+
context_length: int = Field(default=4096, ge=512, le=131072)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class GeneralSettings(BaseModel):
|
|
48
|
+
model_config = ConfigDict(extra="forbid")
|
|
49
|
+
display_name: str = Field(default="you", max_length=60)
|
|
50
|
+
theme: Literal["system", "light", "dark", "codex"] = "system"
|
|
51
|
+
font: Literal["theme", "system", "mono", "serif", "plex"] = "theme"
|
|
52
|
+
accent: Literal["neutral", "blue", "teal", "violet", "amber"] = "neutral"
|
|
53
|
+
characters: bool = True
|
|
54
|
+
send_shortcut: Literal["enter", "mod-enter"] = "enter"
|
|
55
|
+
open_at_login: bool = False
|
|
56
|
+
notify_background: bool = False
|
|
57
|
+
agreement_rounds: int = Field(default=4, ge=2, le=6)
|
|
58
|
+
max_replies: int = Field(default=8, ge=2, le=6 * len(REGISTRY))
|
|
59
|
+
default_combiner: Provider = next(iter(REGISTRY))
|
|
60
|
+
summary_threshold: int = Field(default=40000, ge=1, le=2000000)
|
|
61
|
+
web_search: bool = True
|
|
62
|
+
usage_warning: int = Field(default=20, ge=0, le=100)
|
|
63
|
+
usage_refresh: int = Field(default=120, ge=30, le=3600)
|
|
64
|
+
repository: str = Field(default="aadilchallawala-cloud/diff-chat", max_length=150,
|
|
65
|
+
pattern=r"^$|^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}$")
|
|
66
|
+
@field_validator("display_name")
|
|
67
|
+
@classmethod
|
|
68
|
+
def checked_name(cls, value):
|
|
69
|
+
name = storage.clean_name(value)
|
|
70
|
+
if not name:
|
|
71
|
+
raise ValueError("Enter a single-line name.")
|
|
72
|
+
return name
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# Preserve the settings file/API layout used by earlier versions. Adding an
|
|
76
|
+
# adapter registers a corresponding section without another schema change.
|
|
77
|
+
def settings_fields():
|
|
78
|
+
fields = {}
|
|
79
|
+
for provider in REGISTRY:
|
|
80
|
+
schema = LocalSettings if provider == "local" else ProviderSettings
|
|
81
|
+
fields[provider] = (schema, Field(default_factory=schema))
|
|
82
|
+
return fields
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
Settings = create_model("Settings", __base__=GeneralSettings, **settings_fields())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def get():
|
|
89
|
+
saved = private_store.read("application", {})
|
|
90
|
+
values = {"summary_threshold": storage.SETTINGS["rolling_threshold"], "display_name": storage.display_name()}
|
|
91
|
+
values.update({key: value for key, value in saved.items() if key in Settings.model_fields})
|
|
92
|
+
for provider in REGISTRY:
|
|
93
|
+
override = saved.get(provider, {})
|
|
94
|
+
values[provider] = {"timeout": storage.SETTINGS["timeout_seconds"]}
|
|
95
|
+
if isinstance(override, dict):
|
|
96
|
+
values[provider].update(override)
|
|
97
|
+
try:
|
|
98
|
+
return Settings.model_validate(values).model_dump()
|
|
99
|
+
except ValidationError:
|
|
100
|
+
return Settings().model_dump()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def role_instruction(chat, provider):
|
|
104
|
+
try:
|
|
105
|
+
role = Role.model_validate(chat.get("roles", {}).get(provider, {}))
|
|
106
|
+
except (ValidationError, AttributeError):
|
|
107
|
+
return ""
|
|
108
|
+
if role.mode == "custom":
|
|
109
|
+
return role.text.strip()
|
|
110
|
+
return {"for": "Present the strongest evidence-backed case for the user's proposal.",
|
|
111
|
+
"against": "Present the strongest evidence-backed objections to the user's proposal."}.get(role.mode, "")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@router.get("/api/settings")
|
|
115
|
+
def current():
|
|
116
|
+
try:
|
|
117
|
+
folder_label = "~/" + str(storage.CHAT_DIR.relative_to(Path.home()))
|
|
118
|
+
except ValueError:
|
|
119
|
+
folder_label = str(storage.CHAT_DIR)
|
|
120
|
+
return {"value": get(), "customized": list(private_store.read("application", {})),
|
|
121
|
+
"folder_label": folder_label, "folder": str(storage.CHAT_DIR), "version": VERSION, "platform": sys.platform}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@router.patch("/api/settings")
|
|
125
|
+
async def save(changes: dict):
|
|
126
|
+
previous = private_store.read("application", {})
|
|
127
|
+
values = get()
|
|
128
|
+
for key, change in changes.items():
|
|
129
|
+
if key in REGISTRY and isinstance(change, dict):
|
|
130
|
+
values[key] = {**values[key], **change}
|
|
131
|
+
else:
|
|
132
|
+
values[key] = change
|
|
133
|
+
try:
|
|
134
|
+
validated = Settings.model_validate(values).model_dump()
|
|
135
|
+
except ValidationError:
|
|
136
|
+
raise HTTPException(400, "Choose a valid value for this setting.")
|
|
137
|
+
for p in REGISTRY:
|
|
138
|
+
if p not in changes:
|
|
139
|
+
continue
|
|
140
|
+
override = validated[p]["cli_path"]
|
|
141
|
+
if override and not cli_override(REGISTRY[p].cli_name, override):
|
|
142
|
+
raise HTTPException(400, "Enter the full path to an executable, or leave it empty to auto-detect.")
|
|
143
|
+
if any(k in changes[p] for k in ("model", "effort")) and validated[p]["model"]:
|
|
144
|
+
from model_options import get_model_options
|
|
145
|
+
from utility_models import supported
|
|
146
|
+
if not supported(await get_model_options(), p, validated[p]["model"], validated[p]["effort"]):
|
|
147
|
+
raise HTTPException(400, "Choose a model and reasoning level from the current CLI catalog.")
|
|
148
|
+
if validated[p]["api_fallback"]:
|
|
149
|
+
from api_fallback import credential, require_fallback
|
|
150
|
+
require_fallback(p)
|
|
151
|
+
if not previous.get(p, {}).get("api_fallback") and not await asyncio.to_thread(credential, p):
|
|
152
|
+
raise HTTPException(400, "Save an API key in the system keychain first.")
|
|
153
|
+
updated = {**previous, **{key: validated[key] for key in changes}}
|
|
154
|
+
private_store.update("application", updated, {}, private_store.snapshot(previous)["revision"])
|
|
155
|
+
return current()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@router.get("/api/settings/update")
|
|
159
|
+
async def check_update():
|
|
160
|
+
import httpx
|
|
161
|
+
slug = get()["repository"]
|
|
162
|
+
if not slug:
|
|
163
|
+
raise HTTPException(400, "Enter the project’s GitHub repository first.")
|
|
164
|
+
try:
|
|
165
|
+
async with httpx.AsyncClient(timeout=8) as client:
|
|
166
|
+
response = await client.get(f"https://api.github.com/repos/{slug}/releases/latest",
|
|
167
|
+
headers={"Accept": "application/vnd.github+json", "User-Agent": "diff/" + VERSION})
|
|
168
|
+
if response.status_code == 404:
|
|
169
|
+
return {"message": "No public release found for this repository."}
|
|
170
|
+
response.raise_for_status()
|
|
171
|
+
release = response.json()
|
|
172
|
+
tag = release["tag_name"]
|
|
173
|
+
match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)", tag)
|
|
174
|
+
if not match:
|
|
175
|
+
return {"message": f"Latest release: {str(tag)[:80]}.", "url": f"https://github.com/{slug}/releases/latest"}
|
|
176
|
+
newer = tuple(map(int, match.groups())) > tuple(map(int, VERSION.split(".")))
|
|
177
|
+
return {"message": f"Version {tag} is available." if newer else "You’re up to date.",
|
|
178
|
+
"url": f"https://github.com/{slug}/releases/latest" if newer else None}
|
|
179
|
+
except (httpx.HTTPError, KeyError, ValueError, TypeError):
|
|
180
|
+
raise HTTPException(502, "GitHub could not check for an update. Try again later.")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@router.post("/api/settings/test/{provider}")
|
|
184
|
+
async def test_connection(provider: Provider):
|
|
185
|
+
import setup_status
|
|
186
|
+
return await setup_status.check(provider)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class NoteEdit(BaseModel):
|
|
190
|
+
text: str = Field(max_length=4000)
|
|
191
|
+
revision: str = Field(min_length=64, max_length=64)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@router.get("/api/settings/memory")
|
|
195
|
+
def memory():
|
|
196
|
+
import shared_memory
|
|
197
|
+
return private_store.snapshot(shared_memory.global_note())
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@router.patch("/api/settings/memory")
|
|
201
|
+
def change_memory(change: NoteEdit):
|
|
202
|
+
import shared_memory
|
|
203
|
+
if any(0xD800 <= ord(c) <= 0xDFFF for c in change.text):
|
|
204
|
+
raise HTTPException(400, "Memory contains an invalid character.")
|
|
205
|
+
return shared_memory.save_global(change.text, change.revision)
|
archive_schema.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Validate portable chat data before it enters the user's library."""
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
import re
|
|
4
|
+
from typing import Annotated, Literal
|
|
5
|
+
from urllib.parse import urlsplit
|
|
6
|
+
|
|
7
|
+
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, model_validator
|
|
8
|
+
|
|
9
|
+
from app_preferences import Provider, Role
|
|
10
|
+
from attachments import validate_attachments
|
|
11
|
+
from conversation_actions import valid_comparison
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def valid_time(value):
|
|
15
|
+
if value:
|
|
16
|
+
try:
|
|
17
|
+
return datetime.fromisoformat(value).isoformat(timespec="milliseconds")
|
|
18
|
+
except (ValueError, OverflowError):
|
|
19
|
+
raise ValueError("Invalid timestamp")
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def safe_url(value):
|
|
24
|
+
parts = urlsplit(value)
|
|
25
|
+
if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password:
|
|
26
|
+
raise ValueError("Invalid source URL")
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_comparisons(values):
|
|
31
|
+
if not all(re.fullmatch("[a-f0-9]{64}", key) and valid_comparison(value) for key, value in values.items()):
|
|
32
|
+
raise ValueError("Invalid cached comparison")
|
|
33
|
+
return values
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Record(BaseModel):
|
|
37
|
+
model_config = ConfigDict(strict=True)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
Time = Annotated[str, AfterValidator(valid_time)]
|
|
41
|
+
Identifier = Annotated[str, Field(min_length=1, max_length=200)]
|
|
42
|
+
Positive = Annotated[int, Field(ge=1)]
|
|
43
|
+
Nonnegative = Annotated[int, Field(ge=0)]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Source(Record):
|
|
47
|
+
url: Annotated[str, AfterValidator(safe_url)]
|
|
48
|
+
title: str | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ErrorDetails(Record):
|
|
52
|
+
message: str
|
|
53
|
+
stderr: str = ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Message(Record):
|
|
57
|
+
speaker: Literal["me"] | Provider
|
|
58
|
+
text: str
|
|
59
|
+
timestamp: Time | None = None
|
|
60
|
+
duration_ms: Nonnegative | None = None
|
|
61
|
+
message_id: Identifier | None = None
|
|
62
|
+
turn_id: Identifier | None = None
|
|
63
|
+
round: Positive | None = None
|
|
64
|
+
discussion_id: Identifier | None = None
|
|
65
|
+
mode: str | None = None
|
|
66
|
+
request_kind: str | None = None
|
|
67
|
+
phase: Literal["critique", "evaluation"] | None = None
|
|
68
|
+
model: str | None = None
|
|
69
|
+
effort: str | None = None
|
|
70
|
+
challenge_index: Nonnegative | None = None
|
|
71
|
+
web_search: bool | None = None
|
|
72
|
+
searched_web: bool | None = None
|
|
73
|
+
sources: list[Source] = Field(default_factory=list)
|
|
74
|
+
error: ErrorDetails | None = None
|
|
75
|
+
attachments: Annotated[list[dict], AfterValidator(validate_attachments)] = Field(default_factory=list)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Discussion(Record):
|
|
79
|
+
id: Identifier
|
|
80
|
+
status: Literal["running", "agreed", "limit", "revised", "stopped", "error", "interrupted"]
|
|
81
|
+
start_index: Nonnegative
|
|
82
|
+
end_index: Nonnegative
|
|
83
|
+
round: Positive
|
|
84
|
+
max_rounds: Positive
|
|
85
|
+
max_replies: Positive | None = None
|
|
86
|
+
agreement: str | None = None
|
|
87
|
+
participants: list[Provider] = Field(default_factory=list)
|
|
88
|
+
agreed_by: list[Provider] = Field(default_factory=list)
|
|
89
|
+
detail: str | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Summary(Record):
|
|
93
|
+
text: str
|
|
94
|
+
through_index: Positive
|
|
95
|
+
created_at: Time | None = None
|
|
96
|
+
provider: Provider | None = None
|
|
97
|
+
model: str | None = None
|
|
98
|
+
effort: str | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Stats(Record):
|
|
102
|
+
turns: Nonnegative
|
|
103
|
+
chars_sent: Nonnegative
|
|
104
|
+
legacy: bool = False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Choice(Record):
|
|
108
|
+
model: str
|
|
109
|
+
effort: str
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ArchiveChat(Record):
|
|
113
|
+
title: str
|
|
114
|
+
messages: list[Message]
|
|
115
|
+
updated_at: Time | None = None
|
|
116
|
+
pinned: bool | None = None
|
|
117
|
+
renamed: bool | None = None
|
|
118
|
+
web_search: bool | None = None
|
|
119
|
+
roles: dict[Provider, Role] = Field(default_factory=dict)
|
|
120
|
+
preferences: dict[Provider, Choice] = Field(default_factory=dict)
|
|
121
|
+
stats: Stats | None = None
|
|
122
|
+
comparisons: Annotated[dict, AfterValidator(check_comparisons)] = Field(default_factory=dict)
|
|
123
|
+
discussions: list[Discussion] = Field(default_factory=list)
|
|
124
|
+
context_summary: Summary | None = None
|
|
125
|
+
memory: str = Field(default="", max_length=4000)
|
|
126
|
+
|
|
127
|
+
@model_validator(mode="after")
|
|
128
|
+
def check_indexes(self):
|
|
129
|
+
ids = set()
|
|
130
|
+
for index, message in enumerate(self.messages):
|
|
131
|
+
if message.challenge_index is not None and message.challenge_index >= index:
|
|
132
|
+
raise ValueError("The challenge target must precede the reply")
|
|
133
|
+
if message.message_id:
|
|
134
|
+
if message.message_id in ids:
|
|
135
|
+
raise ValueError("Duplicate message identifier")
|
|
136
|
+
ids.add(message.message_id)
|
|
137
|
+
size = len(self.messages)
|
|
138
|
+
if any(not discussion.start_index <= discussion.end_index <= size for discussion in self.discussions):
|
|
139
|
+
raise ValueError("Invalid discussion range")
|
|
140
|
+
if self.context_summary and self.context_summary.through_index > size:
|
|
141
|
+
raise ValueError("Invalid summary range")
|
|
142
|
+
return self
|
attachments.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Validate explicitly attached files and adapt their contents to the two chat CLIs."""
|
|
2
|
+
import base64
|
|
3
|
+
import binascii
|
|
4
|
+
from io import BytesIO
|
|
5
|
+
from pathlib import PurePath
|
|
6
|
+
import re
|
|
7
|
+
from xml.etree import ElementTree
|
|
8
|
+
from zipfile import BadZipFile, ZipFile
|
|
9
|
+
|
|
10
|
+
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
11
|
+
from pypdf import PdfReader
|
|
12
|
+
|
|
13
|
+
MAX_FILES = 6
|
|
14
|
+
MAX_BYTES = 8 * 1024 * 1024
|
|
15
|
+
MAX_TEXT = 120_000
|
|
16
|
+
IMAGE_TYPES = {"png": "image/png", "jpeg": "image/jpeg", "jpg": "image/jpeg", "webp": "image/webp"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def document_text(raw, extension):
|
|
20
|
+
if extension == "pdf":
|
|
21
|
+
doc = PdfReader(BytesIO(raw), strict=False)
|
|
22
|
+
if doc.is_encrypted or len(doc.pages) > 120:
|
|
23
|
+
raise ValueError("Attach an unlocked PDF of up to 120 pages.")
|
|
24
|
+
text = "\n".join(page.extract_text() or "" for page in doc.pages)
|
|
25
|
+
if not text.strip():
|
|
26
|
+
raise ValueError("This PDF has no text layer. Attach its pages as images.")
|
|
27
|
+
return text
|
|
28
|
+
if extension == "docx":
|
|
29
|
+
with ZipFile(BytesIO(raw)) as doc:
|
|
30
|
+
info = doc.getinfo("word/document.xml")
|
|
31
|
+
if info.file_size > 4 * 1024 * 1024:
|
|
32
|
+
raise ValueError("This document is too large. Attach a shorter excerpt.")
|
|
33
|
+
xml = ElementTree.fromstring(doc.read(info))
|
|
34
|
+
return "\n".join("".join(t.text or "" for t in p.findall(".//{*}t")) for p in xml.findall(".//{*}p"))
|
|
35
|
+
return raw.decode("utf-8-sig")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check_image(raw, mime):
|
|
39
|
+
try:
|
|
40
|
+
with Image.open(BytesIO(raw), formats=("PNG", "JPEG", "WEBP")) as img:
|
|
41
|
+
if img.width * img.height > 32_000_000:
|
|
42
|
+
raise ValueError("Choose an image under 32 megapixels.")
|
|
43
|
+
if getattr(img, "n_frames", 1) > 1:
|
|
44
|
+
raise ValueError("Choose one frame of this animated image.")
|
|
45
|
+
img.verify()
|
|
46
|
+
except (Image.DecompressionBombError, OSError, SyntaxError, UnidentifiedImageError) as error:
|
|
47
|
+
raise ValueError(f"This {mime.split('/')[-1].upper()} image could not be read.") from error
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def image_for_model(image):
|
|
51
|
+
# Keep original bytes for exports. Fit large inputs inside the provider's image envelope.
|
|
52
|
+
if len(image["data"]) <= 6_400_000:
|
|
53
|
+
return image
|
|
54
|
+
with Image.open(BytesIO(base64.b64decode(image["data"]))) as original:
|
|
55
|
+
frame = ImageOps.exif_transpose(original)
|
|
56
|
+
frame.thumbnail((2048, 2048), Image.Resampling.LANCZOS)
|
|
57
|
+
rgba = frame.convert("RGBA")
|
|
58
|
+
background = Image.new("RGB", frame.size, "white")
|
|
59
|
+
background.paste(rgba, mask=rgba.getchannel("A"))
|
|
60
|
+
reduced = BytesIO()
|
|
61
|
+
background.save(reduced, "JPEG", quality=87)
|
|
62
|
+
return {**image, "type": "image/jpeg", "data": base64.b64encode(reduced.getvalue()).decode("ascii")}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def validate_attachments(items):
|
|
66
|
+
"""Canonicalize uploaded/imported records. Client-provided extracted text is never trusted."""
|
|
67
|
+
if not isinstance(items, list) or len(items) > MAX_FILES:
|
|
68
|
+
raise ValueError("Attach up to six files per message.")
|
|
69
|
+
total = text_length = 0
|
|
70
|
+
result = []
|
|
71
|
+
for item in items:
|
|
72
|
+
if not isinstance(item, dict):
|
|
73
|
+
raise ValueError("Invalid attachment.")
|
|
74
|
+
name = item.get("name")
|
|
75
|
+
if not isinstance(name, str) or not name.strip() or len(name) > 255 or re.search(r'[/\\\x00-\x1f\x7f]', name):
|
|
76
|
+
raise ValueError("Choose a file with a valid name.")
|
|
77
|
+
data = item.get("data")
|
|
78
|
+
if not isinstance(data, str) or len(data) > ((MAX_BYTES + 2) // 3) * 4:
|
|
79
|
+
raise ValueError("Attachments must total 8 MB or less per message.")
|
|
80
|
+
try:
|
|
81
|
+
raw = base64.b64decode(data, validate=True)
|
|
82
|
+
except (ValueError, binascii.Error) as error:
|
|
83
|
+
raise ValueError("Invalid attachment encoding.") from error
|
|
84
|
+
total += len(raw)
|
|
85
|
+
if total > MAX_BYTES:
|
|
86
|
+
raise ValueError("Attachments must total 8 MB or less per message.")
|
|
87
|
+
extension = PurePath(name).suffix.lower().lstrip(".")
|
|
88
|
+
signature = ("image/png" if raw.startswith(b"\x89PNG\r\n\x1a\n") else
|
|
89
|
+
"image/jpeg" if raw.startswith(b"\xff\xd8\xff") else
|
|
90
|
+
"image/webp" if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP" else None)
|
|
91
|
+
record = {"name": name, "data": data, "size": len(raw)}
|
|
92
|
+
if signature:
|
|
93
|
+
check_image(raw, signature)
|
|
94
|
+
record["type"] = signature
|
|
95
|
+
else:
|
|
96
|
+
if extension in IMAGE_TYPES or str(item.get("type", "")).startswith("image/"):
|
|
97
|
+
raise ValueError("Attach a PNG, JPEG, or WebP image.")
|
|
98
|
+
try:
|
|
99
|
+
body = document_text(raw, extension)
|
|
100
|
+
except (UnicodeDecodeError, BadZipFile, KeyError, ElementTree.ParseError) as error:
|
|
101
|
+
raise ValueError("Attach a UTF-8 text file, PDF, DOCX, PNG, JPEG, or WebP.") from error
|
|
102
|
+
except ValueError:
|
|
103
|
+
raise
|
|
104
|
+
except Exception as error:
|
|
105
|
+
raise ValueError("This document could not be read. Attach its text or an image.") from error
|
|
106
|
+
if "\0" in body or any(ord(c) < 9 for c in body):
|
|
107
|
+
raise ValueError("This binary format is unsupported. Attach a text or image export.")
|
|
108
|
+
text_length += len(body)
|
|
109
|
+
if text_length > MAX_TEXT:
|
|
110
|
+
raise ValueError("Attach up to 120,000 characters of text per message.")
|
|
111
|
+
record.update(type={"pdf": "application/pdf", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}.get(extension, "text/plain"), text=body)
|
|
112
|
+
result.append(record)
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def text_for_attachment(item):
|
|
117
|
+
label = f"[Attached file: {item['name']}]"
|
|
118
|
+
return label + "\n" + item["text"] if "text" in item else label
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def images_for(messages):
|
|
122
|
+
return [{**image_for_model(item), "message_time": message.get("timestamp", "")} for message in messages
|
|
123
|
+
for item in message.get("attachments", []) if item["type"].startswith("image/")]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def display_message(message):
|
|
127
|
+
if not message.get("attachments"):
|
|
128
|
+
return message
|
|
129
|
+
return {**message, "attachments": [{k: item[k] for k in ("name", "type", "size")} for item in message["attachments"]]}
|
chat_titles.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Human-readable chat titles for new, imported, and previously saved chats."""
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
BLOCK_MARKS = re.compile(r"^(?:(?:>\s*|#{1,6}\s+|(?:[-*+] |\d+[.)]\s+))(?:\[[ xX]\]\s*)?)+")
|
|
5
|
+
SUMMARY_LABEL = re.compile(
|
|
6
|
+
r"^(?:(?:here(?:['’]s| is)\s+)?(?:a |the )?(?:brief |concise |neutral )?"
|
|
7
|
+
r"(?:(?:carry[- ]forward|chat|conversation)\s+)?summary"
|
|
8
|
+
r"(?:\s+(?:from|of) (?:the |our |this |your )?(?:(?:previous|earlier|last) )?"
|
|
9
|
+
r"(?:chat|conversation|discussion)(?: so far)?)?|earlier messages summarized|"
|
|
10
|
+
r"(?:chat |conversation )?title|tl;?dr)"
|
|
11
|
+
r"(?:\s*[:—–]\s*|\s+-\s+|[. …]*$)", re.IGNORECASE
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def plain_title(text, *, skip_labels=True):
|
|
16
|
+
for raw in text.splitlines():
|
|
17
|
+
line = BLOCK_MARKS.sub("", raw.strip())
|
|
18
|
+
if not line or line.startswith(("```", "~~~")) or re.fullmatch(r"[#*_~\s=-]+", line):
|
|
19
|
+
continue
|
|
20
|
+
line = re.sub(r"!?(?:\[([^\]]+)\])\((?:[^()]|\([^()]*\))*\)", r"\1", line)
|
|
21
|
+
line = re.sub(r"(?<!\w)([*_]{1,3}|~~)(?=\S)(.+?)(?<=\S)\1(?!\w)", r"\2", line)
|
|
22
|
+
line = re.sub(r"(`+)(.+?)\1", r"\2", line)
|
|
23
|
+
line = re.sub(r"\s+#+\s*$", "", line)
|
|
24
|
+
# A legacy auto-title may end mid-span after its first 55 characters.
|
|
25
|
+
line = re.sub(r"^([*_]{2,3}|`+)(?=\S)", "", line)
|
|
26
|
+
if skip_labels:
|
|
27
|
+
line = SUMMARY_LABEL.sub("", line).strip()
|
|
28
|
+
line = " ".join(line.split())
|
|
29
|
+
if line:
|
|
30
|
+
return line
|
|
31
|
+
return ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def from_message(text):
|
|
35
|
+
line = plain_title(text)
|
|
36
|
+
sentence = re.split(r"(?<=[.!?])\s", line, maxsplit=1)[0]
|
|
37
|
+
if len(sentence) <= 56:
|
|
38
|
+
return sentence
|
|
39
|
+
prefix = sentence[:55].rstrip()
|
|
40
|
+
if not sentence[55].isspace() and " " in prefix:
|
|
41
|
+
prefix = prefix.rsplit(" ", 1)[0]
|
|
42
|
+
return prefix + "…"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def for_chat(chat):
|
|
46
|
+
title = chat["title"].strip()
|
|
47
|
+
# Branch/continuation identifiers belong to the chat, even if its parent
|
|
48
|
+
# supplied a boilerplate title that needs recovering from the conversation.
|
|
49
|
+
suffix = re.search(r"(?: \((?:branch|continued)\))+$", title)
|
|
50
|
+
base = title[:suffix.start()] if suffix else title
|
|
51
|
+
cleaned = plain_title(base, skip_labels=not chat.get("renamed"))
|
|
52
|
+
if not cleaned or (cleaned == "New chat" and not chat.get("renamed")):
|
|
53
|
+
messages = chat.get("messages", [])
|
|
54
|
+
for message in (m for m in messages if m["speaker"] == "me"):
|
|
55
|
+
cleaned = from_message(message["text"])
|
|
56
|
+
if cleaned:
|
|
57
|
+
break
|
|
58
|
+
if not cleaned:
|
|
59
|
+
cleaned = next((topic for m in messages if (topic := from_message(m["text"]))), "")
|
|
60
|
+
return (cleaned or "New chat") + (suffix.group() if suffix else "")
|
connection_handoff.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Open a participant's interactive setup in a local terminal."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import shlex
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
|
|
11
|
+
from runtime_paths import cli_path, data_root
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class SetupAction:
|
|
16
|
+
id: str
|
|
17
|
+
label: str
|
|
18
|
+
argv: tuple[str, ...]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def profile_environment():
|
|
22
|
+
overrides = {"TRANSCRIPT_DATA_ROOT": str(data_root()), "PATH": cli_path()}
|
|
23
|
+
for key in ("CODEX_HOME", "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"):
|
|
24
|
+
if os.environ.get(key):
|
|
25
|
+
overrides[key] = os.environ[key]
|
|
26
|
+
if "CLAUDE_CONFIG_DIR" in overrides:
|
|
27
|
+
overrides.setdefault("CLAUDE_SECURESTORAGE_CONFIG_DIR", overrides["CLAUDE_CONFIG_DIR"])
|
|
28
|
+
if getattr(sys, "frozen", False):
|
|
29
|
+
overrides["PYINSTALLER_RESET_ENVIRONMENT"] = "1"
|
|
30
|
+
return overrides
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def open_terminal(action):
|
|
34
|
+
overrides = profile_environment()
|
|
35
|
+
if sys.platform == "darwin":
|
|
36
|
+
# LaunchServices opens Terminal without requesting Apple Events access.
|
|
37
|
+
# Only explicit profile paths and adapter-owned arguments enter this file.
|
|
38
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", prefix="diff-connect-",
|
|
39
|
+
suffix=".command", delete=False) as script:
|
|
40
|
+
path = Path(script.name)
|
|
41
|
+
try:
|
|
42
|
+
argv = ["/usr/bin/env", *(f"{k}={v}" for k, v in overrides.items()), *action.argv]
|
|
43
|
+
script.write('#!/bin/sh\n/bin/rm -f "$0"\ncd ' + shlex.quote(tempfile.gettempdir()) +
|
|
44
|
+
' || exit 1\nexec ' + shlex.join(argv) + '\n')
|
|
45
|
+
script.flush()
|
|
46
|
+
path.chmod(0o700)
|
|
47
|
+
subprocess.run(["/usr/bin/open", "-a", "Terminal", str(path)], check=True, timeout=10,
|
|
48
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
49
|
+
except BaseException:
|
|
50
|
+
path.unlink(missing_ok=True)
|
|
51
|
+
raise
|
|
52
|
+
return
|
|
53
|
+
env = os.environ | overrides
|
|
54
|
+
if os.name == "nt":
|
|
55
|
+
subprocess.Popen(action.argv, env=env, cwd=tempfile.gettempdir(),
|
|
56
|
+
creationflags=subprocess.CREATE_NEW_CONSOLE)
|
|
57
|
+
return
|
|
58
|
+
for terminal, flag in (("x-terminal-emulator", "-e"), ("gnome-terminal", "--"),
|
|
59
|
+
("konsole", "-e"), ("xterm", "-e")):
|
|
60
|
+
if binary := shutil.which(terminal):
|
|
61
|
+
subprocess.Popen([binary, flag, *action.argv], env=env, cwd=tempfile.gettempdir(),
|
|
62
|
+
start_new_session=True)
|
|
63
|
+
return
|
|
64
|
+
raise OSError("No graphical terminal available.")
|