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
adapters/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Adding a participant
|
|
2
|
+
|
|
3
|
+
A participant is a Python module in this directory. Copy the structure of `local.py` for a service or `claude.py` for a CLI. Define a `Participant` subclass with a stable lowercase ID matching the filename and export one instance named `ADAPTER`. The registry discovers modules inside the installed package and sorts them by `order` and then ID. Prefix private helper modules with an underscore.
|
|
4
|
+
|
|
5
|
+
Declare `id`, `label`, `order`, `color` and `dark_color`. Optional attributes include `fill`, `dark_fill`, `character` (the URL of a sprite manifest), `cli_name`, `kind` (`cli` or `http`), `usage_note`, `search_tool` and `default_enabled`. The application uses these values for ordering, controls, setup and presentation. New participants default to off. Adding an adapter never installs its underlying service.
|
|
6
|
+
|
|
7
|
+
| Method | Contract |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| `async detect()` | Return a mapping with `status`, `hint`, and optionally `version`, `path`, `command`, `install_url` or `suggestion`. Use `ready` only when the account or local service can be used. Setup checks must not spend model tokens. |
|
|
10
|
+
| `async list_models()` | Return `{"default_model": "...", "models": [...]}`. Each choice supplies `id`, `label`, `efforts` and `default_effort`. Use `["default"]` for an unconfigurable effort and an empty list of models when unavailable. |
|
|
11
|
+
| `send(messages, model, reasoning, system, attachments, session_id, **runtime)` | An async iterator yielding visible strings. Accept a speaker-labelled transcript or a list of role/content dictionaries. Prepared image attachments contain a display name, MIME type and base64 image data. The host has already extracted selected text documents into the transcript. Raise `ModelError` for an incomplete reply and reject unsupported attachments explicitly. |
|
|
12
|
+
| `resume(session_id)` | Validate an explicit, app-owned session handle before using the provider's resume facility. Sessionless participants inherit a `ResumeUnavailable` implementation. The actual resumed turn streams through `send`. |
|
|
13
|
+
| `async usage()` | Return the plan-meter schema used in `plan_usage.py` or `None` if the provider has no such report. |
|
|
14
|
+
| `capabilities()` | Return booleans for streaming, sessions, reasoning_levels, web_search, attachments, images and api_fallback. Describe features usable **through this adapter**. Model-specific restrictions can further narrow capabilities. |
|
|
15
|
+
|
|
16
|
+
`runtime` supplies a timeout, Stop event, optional private session directory and four callbacks. `on_input(count)` records accepted input. `on_session(id)` commits a provider-confirmed session. `on_search(sources)` carries checked citations. `on_final(text)` supplies authoritative final text when a CLI's partial events differ. The host cancels the iterator on timeout or Stop. Close every request or subprocess in a `finally` block. A canceled subprocess must also terminate its children.
|
|
17
|
+
|
|
18
|
+
The CLI launcher uses an empty working directory and an environment restricted to required values. Recheck the actual executable's help before adopting flags. Block model access to local tools, hooks, external plugins and arbitrary files. Keep account sign-in with the official provider client. Do not persist raw keys, automatically open local file paths mentioned in chat, or enable cloud transport in an adapter labelled local.
|
|
19
|
+
|
|
20
|
+
Run `python -m unittest discover -s tests` for offline regression tests. `python probe.py` prints actual CLI help. The optional live `python scripts/sandbox_test.py` sends synthetic canary prompts through installed providers and reports skipped providers separately. It uses provider credits and creates no real chat.
|
|
21
|
+
|
|
22
|
+
## Built-in transports
|
|
23
|
+
|
|
24
|
+
Adapters can also implement `setup_action(status)` to return a `SetupAction(id, label, argv)` for a specific readiness state. diff shows the label in **Connect models** and rechecks that state before opening the local terminal. Supply the executable and each argument separately. The display-only setup command is a manual alternative.
|
|
25
|
+
|
|
26
|
+
- Claude and GPT retain their original subscription command profiles. Claude exposes incremental text. The pinned Codex JSON protocol returns completed agent messages. Both support explicit session IDs, attached images, and optional service-hosted web search.
|
|
27
|
+
- Gemini uses Antigravity CLI 1.5.20. diff owns its Google profile and launches Google's interactive OAuth from setup. The account catalog supplies all selectable model/effort variants. The CLI's framing is an input prefix. Strict tool permissions deny files, commands, MCP and URL actions. Its headless protocol accepts text. Provider-native history lives in the private Google profile, and each chat keeps its own confirmed conversation ID. Deleting a diff chat does not guarantee erasure of the CLI's private native history. See the [headless protocol](https://antigravity.google/docs/cli/headless/) and [CLI permissions](https://antigravity.google/docs/permissions/?tab=cli).
|
|
28
|
+
- Local uses a fixed loopback HTTP connection, ignores proxy variables, and refuses remote-backed models. It discovers installed tags at runtime. Vision requires the selected model to advertise vision. Text is streamed from NDJSON, with no client-side tool execution. It gets the summary and recent turns on each request. `ollama pull gemma3:4b` is an optional starting point, verified in the public catalog. See the [tag API](https://docs.ollama.com/api/tags), [chat API](https://docs.ollama.com/api/chat) and [Gemma 3 4B listing](https://ollama.com/library/gemma3:4b).
|
adapters/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Registered participants and the transport used by diff's conversation engine."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from contextlib import aclosing
|
|
4
|
+
from ._cli import (CLAUDE_CONTROL, CODEX_DISABLE, INSTALL, LOGIN, VERSIONS, ModelError,
|
|
5
|
+
ResumeUnavailable, _Invocation, _check_login, _environment, _terminate)
|
|
6
|
+
from .gpt import _prepare_codex
|
|
7
|
+
from .registry import REGISTRY, participant_info, public_registry
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def require_connection(provider):
|
|
11
|
+
from private_store import is_disconnected
|
|
12
|
+
if is_disconnected(provider):
|
|
13
|
+
raise ModelError(f"{REGISTRY[provider].label} is disconnected from diff. Reconnect it in Connect models.")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def run_model(model, framing, transcript, timeout, on_delta, stop, *,
|
|
17
|
+
model_id=None, effort=None, images=None, session_id=None, **runtime):
|
|
18
|
+
adapter = REGISTRY.get(model)
|
|
19
|
+
if adapter is None:
|
|
20
|
+
raise ModelError("Unknown participant.")
|
|
21
|
+
require_connection(model)
|
|
22
|
+
if stop.is_set():
|
|
23
|
+
raise ModelError("Stopped.")
|
|
24
|
+
complete = []
|
|
25
|
+
chunks = []
|
|
26
|
+
stream = adapter.send(transcript, model_id, effort, framing, images or [], session_id,
|
|
27
|
+
timeout=timeout, stop=stop, on_final=complete.append, **runtime)
|
|
28
|
+
async def consume():
|
|
29
|
+
async with aclosing(stream):
|
|
30
|
+
async for chunk in stream:
|
|
31
|
+
chunks.append(chunk)
|
|
32
|
+
await on_delta(chunk)
|
|
33
|
+
return complete[-1] if complete else "".join(chunks)
|
|
34
|
+
|
|
35
|
+
request = asyncio.create_task(consume())
|
|
36
|
+
stopped = asyncio.create_task(stop.wait())
|
|
37
|
+
try:
|
|
38
|
+
done, _ = await asyncio.wait((request, stopped), timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
|
|
39
|
+
if stopped in done:
|
|
40
|
+
raise ModelError("Stopped.")
|
|
41
|
+
if request not in done:
|
|
42
|
+
raise ModelError(f"Timed out after {timeout}s.")
|
|
43
|
+
return request.result()
|
|
44
|
+
finally:
|
|
45
|
+
for task in (request, stopped):
|
|
46
|
+
if not task.done():
|
|
47
|
+
task.cancel()
|
|
48
|
+
await asyncio.gather(request, stopped, return_exceptions=True)
|
adapters/_base.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Participant contract and shared CLI lifecycle. All participant IO is asynchronous."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
from typing import AsyncIterator
|
|
5
|
+
|
|
6
|
+
from ._cli import ModelError, ResumeUnavailable, _uuid, run_cli
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Participant:
|
|
10
|
+
kind = "cli"
|
|
11
|
+
cli_name = None
|
|
12
|
+
character = None
|
|
13
|
+
usage_note = None
|
|
14
|
+
default_enabled = False
|
|
15
|
+
fill = dark_fill = None
|
|
16
|
+
|
|
17
|
+
def capabilities(self):
|
|
18
|
+
return dict(streaming=True, sessions=False, reasoning_levels=False, web_search=False,
|
|
19
|
+
attachments=True, images=False, api_fallback=False)
|
|
20
|
+
|
|
21
|
+
def resume(self, session_id):
|
|
22
|
+
raise ResumeUnavailable(f"{self.label} uses a fresh context for each turn.")
|
|
23
|
+
|
|
24
|
+
async def usage(self):
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
async def detect(self):
|
|
28
|
+
raise NotImplementedError
|
|
29
|
+
|
|
30
|
+
def setup_action(self, status):
|
|
31
|
+
"""Optional interactive action for the verified connection status."""
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
async def list_models(self):
|
|
35
|
+
raise NotImplementedError
|
|
36
|
+
|
|
37
|
+
def send(self, messages, model, reasoning, system, attachments, session_id, **runtime) -> AsyncIterator[str]:
|
|
38
|
+
raise NotImplementedError
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def transcript_text(messages):
|
|
42
|
+
"""Existing chat framing already labels each speaker; also accept structured callers."""
|
|
43
|
+
if isinstance(messages, str):
|
|
44
|
+
return messages
|
|
45
|
+
return "\n\n".join(f"[{m['role']}]\n{m['content']}" for m in messages)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class CliParticipant(Participant):
|
|
49
|
+
streaming = True
|
|
50
|
+
login_args = ()
|
|
51
|
+
|
|
52
|
+
def setup_action(self, status):
|
|
53
|
+
from connection_handoff import SetupAction
|
|
54
|
+
from runtime_paths import find_cli
|
|
55
|
+
if status == "login" and self.login_args and (binary := find_cli(self.cli_name)):
|
|
56
|
+
return SetupAction("login", "Connect " + self.label, (binary, *self.login_args))
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
def capabilities(self):
|
|
60
|
+
return dict(streaming=self.streaming, sessions=True, reasoning_levels=True, web_search=True,
|
|
61
|
+
attachments=True, images=True, api_fallback=True)
|
|
62
|
+
|
|
63
|
+
def expected_model(self, model_id):
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
def resume(self, session_id):
|
|
67
|
+
if not _uuid(session_id):
|
|
68
|
+
raise ResumeUnavailable("Invalid CLI session reference.")
|
|
69
|
+
return session_id
|
|
70
|
+
|
|
71
|
+
async def detect(self):
|
|
72
|
+
from setup_status import check_subscription
|
|
73
|
+
return await check_subscription(self.id)
|
|
74
|
+
|
|
75
|
+
async def send(self, messages, model, reasoning, system, attachments, session_id, *,
|
|
76
|
+
timeout=120, stop=None, on_final=None, **runtime):
|
|
77
|
+
delta = asyncio.Queue()
|
|
78
|
+
if session_id:
|
|
79
|
+
session_id = self.resume(session_id)
|
|
80
|
+
async def execute():
|
|
81
|
+
try:
|
|
82
|
+
return await run_cli(self, system, transcript_text(messages), timeout, delta.put,
|
|
83
|
+
stop or asyncio.Event(), model_id=model, effort=reasoning,
|
|
84
|
+
images=attachments, session_id=session_id, **runtime)
|
|
85
|
+
finally:
|
|
86
|
+
delta.put_nowait(None)
|
|
87
|
+
task = asyncio.create_task(execute())
|
|
88
|
+
try:
|
|
89
|
+
emitted = False
|
|
90
|
+
while (part := await delta.get()) is not None:
|
|
91
|
+
emitted = True
|
|
92
|
+
yield part
|
|
93
|
+
result = await task
|
|
94
|
+
if on_final:
|
|
95
|
+
on_final(result)
|
|
96
|
+
if not emitted:
|
|
97
|
+
yield result
|
|
98
|
+
finally:
|
|
99
|
+
if not task.done():
|
|
100
|
+
task.cancel()
|
|
101
|
+
with suppress(asyncio.CancelledError):
|
|
102
|
+
await task
|
adapters/_cli.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""Subscription CLI adapters with optional provider-hosted web search."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from contextlib import suppress
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import signal
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
from uuid import UUID, uuid4
|
|
17
|
+
|
|
18
|
+
from runtime_paths import find_cli
|
|
19
|
+
from runtime_paths import cli_path
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ModelError(Exception):
|
|
23
|
+
def __init__(self, message: str, stderr: str = ""):
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
self.message = message
|
|
26
|
+
self.stderr = stderr
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SetupRequired(ModelError):
|
|
30
|
+
"""The operating system or installation requires a configuration change."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ResumeUnavailable(ModelError):
|
|
34
|
+
"""The CLI could not open its saved history before starting a model turn."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _uuid(value):
|
|
38
|
+
try:
|
|
39
|
+
return value if isinstance(value, str) and str(UUID(value)) == value else None
|
|
40
|
+
except ValueError:
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _private_dir(path):
|
|
45
|
+
if not path.parent.exists():
|
|
46
|
+
_private_dir(path.parent)
|
|
47
|
+
path.mkdir(mode=0o700, exist_ok=True)
|
|
48
|
+
info = path.lstat()
|
|
49
|
+
if (not stat.S_ISDIR(info.st_mode)
|
|
50
|
+
or (os.name == "posix" and (info.st_uid != os.getuid() or info.st_mode & 0o077))):
|
|
51
|
+
raise ModelError("The CLI session directory must be a private directory owned by this user.")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _session_exists(directory, model, session_id):
|
|
55
|
+
# Only the generated native transcript can establish that the requested
|
|
56
|
+
# conversation exists. Never let either CLI fall back to its latest session.
|
|
57
|
+
if model == "claude":
|
|
58
|
+
matches = (directory / "claude" / "projects").glob(f"*/{session_id}.jsonl")
|
|
59
|
+
else:
|
|
60
|
+
matches = (directory / "codex" / "sessions").glob(f"*/*/*/rollout-*-{session_id}.jsonl*")
|
|
61
|
+
return any(path.is_file() and not path.is_symlink() for path in matches)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# These builds were checked against a loopback provider. Codex's tool registry
|
|
65
|
+
# and Claude's automatic @file attachments are version-specific.
|
|
66
|
+
VERSIONS = {"claude": "2.1.280 (Claude Code)", "gpt": "codex-cli 0.166.0"}
|
|
67
|
+
LEGACY_CLAUDE = "2.1.202 (Claude Code)"
|
|
68
|
+
INSTALL = {
|
|
69
|
+
"claude": "npm install -g @anthropic-ai/claude-code@2.1.280",
|
|
70
|
+
"gpt": "npm install -g @openai/codex@0.166.0",
|
|
71
|
+
}
|
|
72
|
+
LOGIN = {"claude": "claude auth login --claudeai", "gpt": "codex login"}
|
|
73
|
+
CODEX_DISABLE = (
|
|
74
|
+
"shell_tool unified_exec view_image shell_snapshot code_mode code_mode_only "
|
|
75
|
+
"code_mode_host plugins remote_plugin in_app_browser browser_use browser_use_external "
|
|
76
|
+
"browser_use_full_cdp_access computer_use apps multi_agent multi_agent_v2 memories "
|
|
77
|
+
"hooks tool_suggest sleep_tool goals chronicle workspace_dependencies skill_search "
|
|
78
|
+
"skill_mcp_dependency_install plugin_discovery_prefetch image_generation "
|
|
79
|
+
"request_permissions_tool"
|
|
80
|
+
).split()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _environment(root: Path, model: str) -> dict[str, str]:
|
|
84
|
+
# Never pass API keys, provider endpoints, injected tool hosts, or desktop
|
|
85
|
+
# session identifiers. Leave credential management to the signed-in CLI.
|
|
86
|
+
names = ("HOME", "USER", "LOGNAME", "PATH", "LANG", "LC_ALL", "LC_CTYPE",
|
|
87
|
+
"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "USERPROFILE",
|
|
88
|
+
"SYSTEMROOT", "WINDIR", "PATHEXT", "APPDATA", "LOCALAPPDATA")
|
|
89
|
+
env = {key: os.environ[key] for key in names if key in os.environ}
|
|
90
|
+
env["PATH"] = cli_path()
|
|
91
|
+
env.update(TMPDIR=str(root), TMP=str(root), TEMP=str(root), NO_COLOR="1")
|
|
92
|
+
if model == "claude":
|
|
93
|
+
if "CLAUDE_CONFIG_DIR" in os.environ:
|
|
94
|
+
env["CLAUDE_CONFIG_DIR"] = os.environ["CLAUDE_CONFIG_DIR"]
|
|
95
|
+
env.update(CLAUDE_CODE_DISABLE_ATTACHMENTS="1", DISABLE_AUTOUPDATER="1",
|
|
96
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1",
|
|
97
|
+
ENABLE_CLAUDEAI_MCP_SERVERS="false")
|
|
98
|
+
else:
|
|
99
|
+
env["CODEX_HOME"] = os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))
|
|
100
|
+
return env
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _tail(data: bytes | bytearray) -> str:
|
|
104
|
+
value = data[-8192:].decode("utf-8", "replace").strip()
|
|
105
|
+
value = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", value)
|
|
106
|
+
value = re.sub(r"(?i)(bearer\s+)\S+", r"\1[redacted]", value)
|
|
107
|
+
return re.sub(r"\b(?:sk-|eyJ)[A-Za-z0-9_./-]{12,}", "[redacted]", value)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def _terminate(process: asyncio.subprocess.Process) -> None:
|
|
111
|
+
"""Kill the subprocess group, including children that inherited its pipes."""
|
|
112
|
+
if os.name == "posix":
|
|
113
|
+
with suppress(ProcessLookupError):
|
|
114
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
115
|
+
elif process.returncode is None:
|
|
116
|
+
killer = await asyncio.create_subprocess_exec(
|
|
117
|
+
os.path.join(os.environ["SYSTEMROOT"], "System32", "taskkill.exe"),
|
|
118
|
+
"/pid", str(process.pid), "/t", "/f",
|
|
119
|
+
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
|
|
120
|
+
)
|
|
121
|
+
await killer.wait()
|
|
122
|
+
with suppress(ProcessLookupError):
|
|
123
|
+
process.kill()
|
|
124
|
+
# A failed streaming reader might have left a full pipe. Drain after killing.
|
|
125
|
+
await process.communicate()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class _Invocation:
|
|
129
|
+
def __init__(self, binary: str, cwd: Path, env: dict[str, str]):
|
|
130
|
+
self.binary = binary
|
|
131
|
+
self.cwd = cwd
|
|
132
|
+
self.env = env
|
|
133
|
+
self.stderr = bytearray()
|
|
134
|
+
self.prefix: list[str] = []
|
|
135
|
+
self.codex_store = "file"
|
|
136
|
+
|
|
137
|
+
async def execute(self, args: list[str], prompt: str | None = None,
|
|
138
|
+
on_line: Callable[[bytes], Awaitable[None]] | None = None,
|
|
139
|
+
on_submit=None
|
|
140
|
+
) -> tuple[int, bytes]:
|
|
141
|
+
self.stderr.clear()
|
|
142
|
+
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
|
|
143
|
+
*self.prefix, self.binary, *args, cwd=self.cwd, env=self.env,
|
|
144
|
+
stdin=asyncio.subprocess.PIPE if prompt is not None else asyncio.subprocess.DEVNULL,
|
|
145
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
|
|
146
|
+
start_new_session=os.name == "posix", limit=16 * 1024 * 1024,
|
|
147
|
+
**({"umask": 0o077} if os.name == "posix" else {}),
|
|
148
|
+
))
|
|
149
|
+
try:
|
|
150
|
+
process = await asyncio.shield(spawn)
|
|
151
|
+
except asyncio.CancelledError:
|
|
152
|
+
# Stop may arrive during process creation, before the PID is returned.
|
|
153
|
+
await _terminate(await spawn)
|
|
154
|
+
raise
|
|
155
|
+
|
|
156
|
+
async def feed():
|
|
157
|
+
if prompt is not None:
|
|
158
|
+
try:
|
|
159
|
+
process.stdin.write(prompt.encode("utf-8"))
|
|
160
|
+
await process.stdin.drain()
|
|
161
|
+
if on_submit:
|
|
162
|
+
on_submit()
|
|
163
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
164
|
+
pass
|
|
165
|
+
finally:
|
|
166
|
+
process.stdin.close()
|
|
167
|
+
|
|
168
|
+
async def stdout():
|
|
169
|
+
if on_line is None:
|
|
170
|
+
return await process.stdout.read()
|
|
171
|
+
async for line in process.stdout:
|
|
172
|
+
if line.strip():
|
|
173
|
+
await on_line(line)
|
|
174
|
+
return b""
|
|
175
|
+
|
|
176
|
+
async def stderr():
|
|
177
|
+
while chunk := await process.stderr.read(16384):
|
|
178
|
+
self.stderr.extend(chunk)
|
|
179
|
+
del self.stderr[:-8192]
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
async with asyncio.TaskGroup() as group:
|
|
183
|
+
group.create_task(feed())
|
|
184
|
+
out = group.create_task(stdout())
|
|
185
|
+
group.create_task(stderr())
|
|
186
|
+
return await process.wait(), out.result()
|
|
187
|
+
except BaseException:
|
|
188
|
+
await _terminate(process)
|
|
189
|
+
raise
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
CLAUDE_CONTROL = [
|
|
193
|
+
"--safe-mode", "--setting-sources", "", "--settings", json.dumps({
|
|
194
|
+
"disableAllHooks": True, "forceLoginMethod": "claudeai",
|
|
195
|
+
"permissions": {"deny": ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]},
|
|
196
|
+
}),
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
async def _check_login(call: _Invocation, model: str):
|
|
201
|
+
auth_args = ([*CLAUDE_CONTROL, "auth", "status", "--json"] if model == "claude" else
|
|
202
|
+
["-c", f'cli_auth_credentials_store="{call.codex_store}"', "login", "status"])
|
|
203
|
+
code, raw = await call.execute(auth_args)
|
|
204
|
+
if model == "claude":
|
|
205
|
+
try:
|
|
206
|
+
status = json.loads(raw)
|
|
207
|
+
except ValueError:
|
|
208
|
+
status = {}
|
|
209
|
+
ok = (isinstance(status, dict) and status.get("loggedIn") is True
|
|
210
|
+
and status.get("authMethod") == "claude.ai"
|
|
211
|
+
and status.get("apiProvider") == "firstParty")
|
|
212
|
+
else:
|
|
213
|
+
ok = b"Logged in using ChatGPT" in (raw + call.stderr).splitlines()
|
|
214
|
+
if code or not ok:
|
|
215
|
+
raise ModelError(f"Sign in with your subscription. Run {LOGIN[model]} in Terminal.",
|
|
216
|
+
_tail(call.stderr))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class Reply:
|
|
220
|
+
def __init__(self, model: str, on_delta: Callable[[str], Awaitable[None]],
|
|
221
|
+
expected: str | None = None, on_search=None):
|
|
222
|
+
self.model = model
|
|
223
|
+
self.on_delta = on_delta
|
|
224
|
+
self.expected = expected
|
|
225
|
+
self.reported = ""
|
|
226
|
+
self.text = ""
|
|
227
|
+
self.error = ""
|
|
228
|
+
self.finished = False
|
|
229
|
+
self.on_search = on_search
|
|
230
|
+
self.sources = {}
|
|
231
|
+
self.searched = False
|
|
232
|
+
self.search_ids = set()
|
|
233
|
+
self.session_id = None
|
|
234
|
+
self.session_started = False
|
|
235
|
+
self.saw_event = False
|
|
236
|
+
self.missing_id = None
|
|
237
|
+
|
|
238
|
+
def rejected_resume(self, session_id, stderr):
|
|
239
|
+
if self.model == "claude":
|
|
240
|
+
return self.missing_id == session_id and not self.session_started
|
|
241
|
+
# Pinned Codex emits these local thread-store errors before thread.started.
|
|
242
|
+
# Provider/network errors and unreadable-but-present files cannot trigger a retry.
|
|
243
|
+
return (not self.saw_event and stderr.startswith("Error: thread/resume: thread/resume failed:")
|
|
244
|
+
and (f"no rollout found for thread id {session_id} " in stderr
|
|
245
|
+
or ("failed to read session metadata " in stderr
|
|
246
|
+
and stderr.endswith(f"{session_id}.jsonl is empty (code -32603)"))))
|
|
247
|
+
|
|
248
|
+
def search_activity(self, citations=()):
|
|
249
|
+
if not self.on_search:
|
|
250
|
+
return
|
|
251
|
+
count = len(self.sources)
|
|
252
|
+
for citation in citations:
|
|
253
|
+
if not isinstance(citation, dict):
|
|
254
|
+
continue
|
|
255
|
+
url = citation.get("url")
|
|
256
|
+
if (not isinstance(url, str) or len(url) > 8192 or
|
|
257
|
+
any(char.isspace() or ord(char) < 32 or char == "\\" for char in url)):
|
|
258
|
+
continue
|
|
259
|
+
try:
|
|
260
|
+
parts = urlsplit(url)
|
|
261
|
+
if parts.scheme not in ("https", "http") or not parts.hostname or parts.username is not None:
|
|
262
|
+
continue
|
|
263
|
+
except ValueError:
|
|
264
|
+
continue
|
|
265
|
+
title = citation.get("title")
|
|
266
|
+
self.sources[url] = {"url": url, "title": title[:500] if isinstance(title, str) and title else parts.hostname}
|
|
267
|
+
if not self.searched or len(self.sources) != count:
|
|
268
|
+
self.searched = True
|
|
269
|
+
self.on_search(list(self.sources.values()))
|
|
270
|
+
|
|
271
|
+
def _matches_selection(self) -> bool:
|
|
272
|
+
# A fixed release may be returned with its YYYYMMDD snapshot suffix.
|
|
273
|
+
return self.expected is None or re.fullmatch(
|
|
274
|
+
re.escape(self.expected) + r"(?:-\d{8})?", self.reported
|
|
275
|
+
) is not None
|
|
276
|
+
|
|
277
|
+
async def accept(self, line: bytes):
|
|
278
|
+
try:
|
|
279
|
+
event = json.loads(line)
|
|
280
|
+
except ValueError:
|
|
281
|
+
self.error = "The CLI returned an unreadable response."
|
|
282
|
+
return
|
|
283
|
+
if not isinstance(event, dict):
|
|
284
|
+
self.error = "The CLI returned an unexpected response."
|
|
285
|
+
return
|
|
286
|
+
kind = event.get("type")
|
|
287
|
+
self.saw_event = True
|
|
288
|
+
await self.accept_event(kind, event)
|
|
289
|
+
|
|
290
|
+
async def run_cli(adapter, framing: str, transcript: str, timeout: int,
|
|
291
|
+
on_delta: Callable[[str], Awaitable[None]], stop: asyncio.Event, *,
|
|
292
|
+
model_id: str | None = None, effort: str | None = None,
|
|
293
|
+
web_search: bool = False, on_search=None, session_dir: Path | None = None,
|
|
294
|
+
session_id: str | None = None, on_session: Callable[[str], None] | None = None,
|
|
295
|
+
on_input: Callable[[int], None] | None = None, images=None) -> str:
|
|
296
|
+
model = adapter.id
|
|
297
|
+
if stop.is_set():
|
|
298
|
+
raise ModelError("Stopped.")
|
|
299
|
+
if session_id is not None and (not _uuid(session_id) or session_dir is None):
|
|
300
|
+
raise ModelError("Invalid CLI session reference.")
|
|
301
|
+
if session_dir is not None:
|
|
302
|
+
session_dir = Path(session_dir)
|
|
303
|
+
if not session_dir.is_absolute():
|
|
304
|
+
raise ModelError("The CLI session directory must have an absolute path.")
|
|
305
|
+
try:
|
|
306
|
+
if session_id and not _session_exists(session_dir, model, session_id):
|
|
307
|
+
raise ResumeUnavailable("This CLI's saved session is no longer available.")
|
|
308
|
+
_private_dir(session_dir)
|
|
309
|
+
if session_id is None and any(session_dir.iterdir()):
|
|
310
|
+
raise ModelError("Start a new CLI session in an empty private directory.")
|
|
311
|
+
except OSError as error:
|
|
312
|
+
raise ModelError("Could not access this app's private CLI session directory.") from error
|
|
313
|
+
name = adapter.cli_name
|
|
314
|
+
binary = find_cli(name)
|
|
315
|
+
if not binary:
|
|
316
|
+
raise ModelError(f"{name} is missing from PATH. Install with {INSTALL[model]}.")
|
|
317
|
+
|
|
318
|
+
with tempfile.TemporaryDirectory(prefix="transcript-") as temporary:
|
|
319
|
+
root = Path(temporary).resolve()
|
|
320
|
+
cwd = root / "workspace"
|
|
321
|
+
cwd.mkdir()
|
|
322
|
+
call = _Invocation(str(Path(binary).absolute()), cwd, _environment(root, model))
|
|
323
|
+
confirmed_id = None
|
|
324
|
+
credential_links = []
|
|
325
|
+
|
|
326
|
+
async def invoke():
|
|
327
|
+
nonlocal confirmed_id
|
|
328
|
+
code, version = await call.execute(["--version"])
|
|
329
|
+
installed = version.decode(errors="replace").strip()
|
|
330
|
+
legacy = model == "claude" and installed == LEGACY_CLAUDE
|
|
331
|
+
if code or (installed != VERSIONS[model] and not legacy):
|
|
332
|
+
raise ModelError(f"This app verified tool isolation with {VERSIONS[model]}. "
|
|
333
|
+
f"Install with {INSTALL[model]}.", _tail(call.stderr))
|
|
334
|
+
args, prompt, native, target_id = await adapter.command(
|
|
335
|
+
call, root, framing, transcript, model_id, effort, web_search, images,
|
|
336
|
+
session_dir, session_id, legacy, credential_links)
|
|
337
|
+
reply = adapter.reply(model, on_delta, adapter.expected_model(model_id),
|
|
338
|
+
on_search if web_search else None)
|
|
339
|
+
sent = counted = False
|
|
340
|
+
|
|
341
|
+
def count_input():
|
|
342
|
+
nonlocal counted
|
|
343
|
+
if sent and not counted and on_input:
|
|
344
|
+
counted = True
|
|
345
|
+
on_input(len(framing) + len(transcript))
|
|
346
|
+
|
|
347
|
+
def submitted():
|
|
348
|
+
nonlocal sent
|
|
349
|
+
sent = True
|
|
350
|
+
if not session_id or reply.session_started:
|
|
351
|
+
count_input()
|
|
352
|
+
|
|
353
|
+
async def accept(line):
|
|
354
|
+
await reply.accept(line)
|
|
355
|
+
if reply.session_started:
|
|
356
|
+
count_input()
|
|
357
|
+
|
|
358
|
+
try:
|
|
359
|
+
code, _ = await call.execute(args, prompt, accept, on_submit=submitted)
|
|
360
|
+
except BaseException:
|
|
361
|
+
count_input()
|
|
362
|
+
raise
|
|
363
|
+
details = _tail(call.stderr)
|
|
364
|
+
if code and session_id and reply.rejected_resume(session_id, details):
|
|
365
|
+
raise ResumeUnavailable("This CLI's saved session is no longer available.", details)
|
|
366
|
+
count_input()
|
|
367
|
+
if code or not reply.finished or not isinstance(reply.text, str) or not reply.text.strip():
|
|
368
|
+
error = _tail(str(reply.error).encode()) or f"{name} exited with status {code}."
|
|
369
|
+
if re.search(r"not logged in|not authenticated|login expired|unauthorized|\b401\b",
|
|
370
|
+
f"{details}\n{error}", flags=re.I):
|
|
371
|
+
error = f"Sign in again with {LOGIN[model]}."
|
|
372
|
+
if not code and not reply.error:
|
|
373
|
+
error = f"{name} finished without a complete reply."
|
|
374
|
+
raise ModelError(error, details)
|
|
375
|
+
if native:
|
|
376
|
+
if not reply.session_id or (target_id and reply.session_id != target_id):
|
|
377
|
+
raise ModelError("The CLI did not confirm the requested conversation.")
|
|
378
|
+
if _session_exists(session_dir, model, reply.session_id):
|
|
379
|
+
confirmed_id = reply.session_id
|
|
380
|
+
return reply.text
|
|
381
|
+
|
|
382
|
+
result = asyncio.create_task(invoke())
|
|
383
|
+
stopped = asyncio.create_task(stop.wait())
|
|
384
|
+
try:
|
|
385
|
+
done, _ = await asyncio.wait((result, stopped), timeout=timeout,
|
|
386
|
+
return_when=asyncio.FIRST_COMPLETED)
|
|
387
|
+
if stopped in done:
|
|
388
|
+
raise ModelError("Stopped.", _tail(call.stderr))
|
|
389
|
+
if result not in done:
|
|
390
|
+
raise ModelError(f"Timed out after {timeout}s.", _tail(call.stderr))
|
|
391
|
+
answer = result.result()
|
|
392
|
+
if confirmed_id and on_session:
|
|
393
|
+
on_session(confirmed_id)
|
|
394
|
+
return answer
|
|
395
|
+
except (OSError, ExceptionGroup) as error:
|
|
396
|
+
raise ModelError(f"{name} could not complete the request: {error}",
|
|
397
|
+
_tail(call.stderr)) from error
|
|
398
|
+
finally:
|
|
399
|
+
for task in (result, stopped):
|
|
400
|
+
if not task.done():
|
|
401
|
+
task.cancel()
|
|
402
|
+
await asyncio.gather(result, stopped, return_exceptions=True)
|
|
403
|
+
for link in credential_links:
|
|
404
|
+
if link.is_symlink():
|
|
405
|
+
link.unlink(missing_ok=True)
|