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
probe.py ADDED
@@ -0,0 +1,195 @@
1
+ """Print the installed clients' help and versions without making model requests."""
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+
8
+ from runtime_paths import cli_path, find_cli
9
+
10
+ COMMANDS = (
11
+ ("claude", "--help"), ("codex", "exec", "--help"), ("codex", "exec", "resume", "--help"),
12
+ ("claude", "--version"), ("codex", "--version"),
13
+ ("claude", "auth", "--help"), ("codex", "--help"),
14
+ ("claude", "auth", "login", "--help"), ("claude", "auth", "status", "--help"),
15
+ ("codex", "login", "--help"), ("codex", "features", "list"),
16
+ ("codex", "debug", "models", "--help"),
17
+ )
18
+
19
+ REQUIRED_HELP = {
20
+ ("claude", "--help"): ("--session-id", "--resume", "--system-prompt", "--system-prompt-snapshot",
21
+ "--tools", "--input-format", "--restricted", "--safe-mode", "--strict-mcp-config"),
22
+ ("codex", "exec", "--help"): ("--strict-config", "--ignore-user-config", "--ignore-rules",
23
+ "--sandbox", "--ephemeral", "--json", "--image"),
24
+ ("codex", "exec", "resume", "--help"): ("[SESSION_ID]", "[PROMPT]", "read from stdin", "--json", "--image"),
25
+ }
26
+
27
+ VERIFIED_PROFILES = {
28
+ "2.1.280 (Claude Code)": (
29
+ "Claude replaces its coding prompt with --system-prompt on every turn. "
30
+ "--system-prompt-snapshot off also refreshes it on resume. A short vendor identity remains. "
31
+ "An empty --tools list removes model tools. Safe mode, restricted mode, disabled attachments "
32
+ "and an empty strict MCP configuration keep local integrations out. Search-enabled turns allow only WebSearch."
33
+ ),
34
+ "codex-cli 0.166.0": (
35
+ "Codex replaces its coding instructions using model_instructions_file. For native sessions, "
36
+ "Full Responses keeps the current developer prompt when resuming the same model. "
37
+ "The app supplies a sanitized model catalog and disables local features, including shell, patch and file tools. "
38
+ "Search-off requests have zero tools. Search-on requests have only the provider's live web search."
39
+ ),
40
+ }
41
+
42
+
43
+ def antigravity_report(binary=None):
44
+ """Print the standalone client's version, full help and headless capability findings."""
45
+ binary = binary or find_cli("agy")
46
+ print("Google Antigravity CLI probe")
47
+ print("Executable: agy" if binary else "Executable: agy (not found)")
48
+ if not binary:
49
+ print("Install the standalone CLI from https://antigravity.google/docs/getting-started?tab=cli")
50
+ return 1
51
+ binary = str(Path(binary).absolute())
52
+ with tempfile.TemporaryDirectory(prefix="diff-agy-help-") as scratch:
53
+ root = Path(scratch)
54
+ cwd, clean = root / "workspace", root / "profile"
55
+ cwd.mkdir()
56
+ clean.mkdir()
57
+ env = {k: os.environ[k] for k in ("PATH", "SYSTEMROOT", "WINDIR", "PATHEXT") if k in os.environ}
58
+ env.update(HOME=str(clean), USERPROFILE=str(clean), XDG_CONFIG_HOME=str(clean / ".config"),
59
+ APPDATA=str(clean / "Roaming"), LOCALAPPDATA=str(clean / "Local"), NO_COLOR="1",
60
+ AGY_CLI_DISABLE_AUTO_UPDATE="true", TMPDIR=scratch, TEMP=scratch, TMP=scratch)
61
+ commands = (("--version",), ("--help",), ("--print", "--help"), ("help", "print"),
62
+ ("help", "exec"), ("models", "--help"), ("conversations", "--help"))
63
+ outputs = {}
64
+ for args in commands:
65
+ print("\n$ agy " + " ".join(args), flush=True)
66
+ try:
67
+ proc = subprocess.run([binary, *args], cwd=cwd, env=env,
68
+ stdin=subprocess.DEVNULL, capture_output=True,
69
+ text=True, errors="replace", timeout=12)
70
+ except (OSError, subprocess.TimeoutExpired) as exc:
71
+ print(f"Could not run the probe ({type(exc).__name__}).")
72
+ return 1
73
+ output = (proc.stdout + proc.stderr).rstrip().replace(scratch, "<temporary directory>")
74
+ print(output)
75
+ print(f"[exit {proc.returncode}]")
76
+ outputs[args] = (proc.returncode, output)
77
+ version = outputs[("--version",)][1]
78
+ helptext = outputs[("--help",)][1]
79
+ checks = ("--print", "--input-format", "--output-format", "--conversation", "--model",
80
+ "--settings", "--sandbox", "--mode", "--disable-slash-commands", "--print-timeout")
81
+ missing = [name for name in checks if name not in helptext]
82
+ if version != "1.5.20" or missing:
83
+ print("\nUnverified CLI profile. Version:", version, "Missing options:", missing or "none")
84
+ return 1
85
+ from adapters.gemini import policy_args
86
+ # Empty stdin and a fresh, signed-out home exercise the real argument
87
+ # parser without submitting a prompt or starting an OAuth session.
88
+ print("\nChecking diff’s sign-in and chat settings with the installed parser.")
89
+ try:
90
+ parsed = subprocess.run([binary, *policy_args(), "--disable-slash-commands",
91
+ "--input-format", "stream-json", "--output-format", "stream-json",
92
+ "--print-timeout", "2s"], cwd=cwd, env=env, input="",
93
+ capture_output=True, text=True, errors="replace", timeout=8)
94
+ except (OSError, subprocess.TimeoutExpired) as exc:
95
+ print(f"Could not verify settings ({type(exc).__name__}).")
96
+ return 1
97
+ if "--settings:" in parsed.stderr or "authentication required" not in parsed.stderr.lower():
98
+ print("Policy validation failed:", parsed.stderr.strip()[:500])
99
+ return 1
100
+ print("Accepted the complete policy and reached authentication with zero prompts.")
101
+ print("""
102
+ Observed interface and integration decisions for agy 1.5.20
103
+
104
+ • Standalone agy is separate from the Antigravity desktop launcher. Print mode lives at the top level.
105
+ • Run agy interactively and choose personal Google OAuth. Free, Pro and Ultra accounts may sign in.
106
+ In diff choose Connect models → Connect Gemini. It launches the official CLI in diff's private profile.
107
+ • -p/--print runs a single prompt. For private transcript input, send a user event on stdin using
108
+ --input-format stream-json and --output-format stream-json. Print outputs include text, JSON and NDJSON.
109
+ • agy models lists account choices as a slug and display name. --model selects an exact choice.
110
+ --effort is advertised. diff resolves each reasoning level to an explicitly listed model variant.
111
+ • --conversation <id> resumes a specific conversation. --continue would select the most recent one.
112
+ diff associates an explicit conversation ID with a single chat generation.
113
+ • --sandbox restricts terminal execution. There is no advertised switch to remove every tool or replace
114
+ the system prompt. diff uses --mode plan, strict permissions, explicit wildcard deny rules for files,
115
+ shell, URLs and MCP, and --disable-slash-commands. User framing is provided as text.
116
+ • diff creates an empty working directory, uses a dedicated private Google profile, sets the CLI timeout
117
+ and cancels the process tree on Stop. This profile uses the CLI's own sign-in and credential storage.
118
+ • Headless NDJSON supports text and text blocks. Selected text and extracted document contents can
119
+ enter the transcript. diff does not grant file-reading tools or forward images to this adapter.
120
+ • The standalone built-in 'agy -p /usage --output-format json' returns grouped quota windows,
121
+ remaining fractions and reset times, with zero model turns. Each account's windows can differ.
122
+ Only this fixed quota query enables slash commands. Google web tools stay disabled in chats.
123
+
124
+ Google authentication guide: https://antigravity.google/docs/install?tab=cli
125
+ Headless protocol: https://antigravity.google/docs/cli/headless/
126
+ Permission rules: https://antigravity.google/docs/permissions/?tab=cli
127
+ Settings schema: https://antigravity.google/schemas/v1/settings.json
128
+ """)
129
+ return 0
130
+
131
+
132
+ def main():
133
+ if sys.argv[1:] == ["--antigravity"]:
134
+ return antigravity_report()
135
+ if sys.argv[1:]:
136
+ print("Usage: python probe.py [--antigravity]")
137
+ return 2
138
+ google = antigravity_report()
139
+ for name in ("claude", "codex"):
140
+ print(f"{name} executable: {find_cli(name) or 'not installed'}", flush=True)
141
+ missing = False
142
+ help_checks = {}
143
+ versions = []
144
+ for command in COMMANDS:
145
+ print(f"\n$ {' '.join(command)}", flush=True)
146
+ binary = find_cli(command[0])
147
+ if not binary:
148
+ print(f"Missing executable: {command[0]}")
149
+ missing = True
150
+ continue
151
+ try:
152
+ with tempfile.TemporaryDirectory(prefix="transcript-probe-") as cwd:
153
+ # Even help and catalog commands can initialize per-user state.
154
+ # Use an empty workspace, home and credential namespace for this probe.
155
+ root = Path(cwd)
156
+ workspace = root / "workspace"
157
+ workspace.mkdir()
158
+ codex = root / "codex"
159
+ codex.mkdir()
160
+ env = {key: os.environ[key] for key in ("PATH", "SYSTEMROOT", "WINDIR", "PATHEXT")
161
+ if key in os.environ}
162
+ env['PATH'] = cli_path()
163
+ env.update(HOME=cwd, USERPROFILE=cwd, XDG_CONFIG_HOME=cwd, CODEX_HOME=str(codex),
164
+ CLAUDE_CONFIG_DIR=str(root / "claude"), CLAUDE_SECURESTORAGE_CONFIG_DIR=str(root / "claude"),
165
+ CLAUDE_CODE_SAFE_MODE="1", DISABLE_AUTOUPDATER="1", NO_COLOR="1",
166
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1")
167
+ result = subprocess.run(
168
+ [str(Path(binary).absolute()), *command[1:]],
169
+ cwd=workspace, stdin=subprocess.DEVNULL, env=env,
170
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
171
+ text=True, errors="replace", timeout=20,
172
+ )
173
+ print(result.stdout.rstrip())
174
+ missing |= result.returncode != 0
175
+ if command[1:] == ("--version",) and not result.returncode:
176
+ versions.append(result.stdout.strip())
177
+ if command in REQUIRED_HELP:
178
+ help_checks[command] = [flag for flag in REQUIRED_HELP[command] if flag not in result.stdout]
179
+ except (OSError, subprocess.TimeoutExpired) as error:
180
+ print(f"Probe failed: {error}")
181
+ missing = True
182
+ print("\nSession and isolation capabilities advertised by these clients:")
183
+ for command, required in REQUIRED_HELP.items():
184
+ absent = help_checks.get(command, required)
185
+ findings = "missing " + ", ".join(absent) if absent else "present: " + ", ".join(required)
186
+ print(f" {' '.join(command)}: {findings}")
187
+ missing |= bool(absent)
188
+ print("\nPreviously verified with the app's loopback request fixtures, by installed version:")
189
+ for version in versions:
190
+ print(f" {version}. {VERIFIED_PROFILES.get(version, 'No recorded profile for this build.')}")
191
+ return int(missing or google)
192
+
193
+
194
+ if __name__ == "__main__":
195
+ raise SystemExit(main())
runtime_paths.py ADDED
@@ -0,0 +1,195 @@
1
+ """Locate a private chat library and signed-in command-line clients for both launchers."""
2
+ import os
3
+ import platform
4
+ from pathlib import Path
5
+ import shutil
6
+ import sys
7
+ import tempfile
8
+
9
+
10
+ MODULE_ROOT = Path(__file__).resolve().parent
11
+ # The wheel installs the read-only interface in its own resource directory.
12
+ WHEEL_ASSETS = MODULE_ROOT / "diff_chat_assets"
13
+ RESOURCE_ROOT = WHEEL_ASSETS if (WHEEL_ASSETS / "settings.json").is_file() else MODULE_ROOT
14
+
15
+
16
+ def user_directory(variable, default):
17
+ configured = Path(os.environ.get(variable, ""))
18
+ return configured if configured.is_absolute() else default
19
+
20
+
21
+ def support_directory():
22
+ if sys.platform == 'win32':
23
+ return user_directory('LOCALAPPDATA', Path.home() / 'AppData' / 'Local') / 'diff'
24
+ if sys.platform != 'darwin':
25
+ return user_directory('XDG_DATA_HOME', Path.home() / '.local' / 'share') / 'diff'
26
+ base = Path.home() / 'Library' / 'Application Support'
27
+ current = base / 'diff'
28
+ previous = base / 'Transcript'
29
+ # The prior Mac release may own a library here or a selector for a source checkout.
30
+ for directory in (current, previous):
31
+ if (directory / 'data-root.txt').is_file() or populated(directory):
32
+ return directory
33
+ return current
34
+
35
+
36
+ def populated(root):
37
+ chats = root / 'chats'
38
+ return (chats.is_dir() and any(chats.iterdir())) or (root / 'settings.local.json').is_file() or (root / '.runtime').is_dir()
39
+
40
+
41
+ def data_root(resources=RESOURCE_ROOT):
42
+ """A bundle is read-only. Existing source installs keep their private files in place."""
43
+ explicit = os.environ.get('TRANSCRIPT_DATA_ROOT')
44
+ if explicit:
45
+ return Path(explicit).expanduser().resolve()
46
+ frozen = bool(getattr(sys, 'frozen', False))
47
+ if not frozen and resources.name != 'diff_chat_assets' and populated(resources):
48
+ return resources
49
+ support = support_directory()
50
+ location = support / 'data-root.txt'
51
+ try:
52
+ configured = Path(location.read_text(encoding='utf-8').rstrip('\n'))
53
+ except FileNotFoundError:
54
+ return support
55
+ if not configured.is_absolute() or not configured.is_dir():
56
+ raise ValueError(f'The saved diff library is unavailable. Check the path in {location}.')
57
+ return configured
58
+
59
+
60
+ def use_source_library(root):
61
+ """Explicitly connect a Mac installation to an existing library without moving any data."""
62
+ root = root.resolve()
63
+ if not (root / 'chats').is_dir():
64
+ raise ValueError('No chats directory in the source folder.')
65
+ if '\n' in str(root):
66
+ raise ValueError('The source folder path must be on one line.')
67
+ support = support_directory()
68
+ support.mkdir(mode=0o700, parents=True, exist_ok=True)
69
+ path = support / 'data-root.txt'
70
+ if not path.exists() and populated(support):
71
+ raise ValueError('The Mac app already has its own library. Its current selection has been kept.')
72
+ # Linking a finished private file is atomic and does not replace an existing choice.
73
+ with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=support, delete=False) as handle:
74
+ temporary = Path(handle.name)
75
+ try:
76
+ handle.write(str(root) + '\n')
77
+ handle.flush()
78
+ os.fsync(handle.fileno())
79
+ except BaseException:
80
+ temporary.unlink(missing_ok=True)
81
+ raise
82
+ try:
83
+ os.link(temporary, path)
84
+ except FileExistsError:
85
+ if Path(path.read_text(encoding='utf-8').rstrip('\n')).resolve() != root:
86
+ raise ValueError(f'diff already uses a different library. Check {path}.')
87
+ finally:
88
+ temporary.unlink(missing_ok=True)
89
+ return path
90
+
91
+
92
+ def cli_path():
93
+ """Finder does not load shell startup scripts. Keep Node on PATH for npm shims."""
94
+ inherited = os.environ.get('PATH', os.defpath)
95
+ folders = [Path(p.strip('"')) for p in inherited.split(os.pathsep) if os.path.isabs(p.strip('"'))]
96
+ home = Path.home()
97
+ folders.append(home / '.local' / 'bin')
98
+ if os.name == 'nt':
99
+ if os.environ.get('APPDATA') and Path(os.environ['APPDATA']).is_absolute():
100
+ folders.append(Path(os.environ['APPDATA']) / 'npm')
101
+ else:
102
+ folders.extend([home / '.volta/bin', home / '.npm-global/bin', home / '.local/share/pnpm'])
103
+ nvm = home / '.nvm/versions/node'
104
+ versions = sorted((p for p in nvm.glob('v*') if all(v.isdigit() for v in p.name[1:].split('.'))),
105
+ key=lambda p: tuple(int(v) for v in p.name[1:].split('.')), reverse=True)
106
+ folders.extend(p / 'bin' for p in versions)
107
+ if sys.platform == 'darwin':
108
+ folders.extend(['/opt/homebrew/bin', '/usr/local/bin', home / 'Library/pnpm',
109
+ '/Applications/Codex.app/Contents/Resources',
110
+ '/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS'])
111
+ return os.pathsep.join(dict.fromkeys(map(str, folders)))
112
+
113
+
114
+ def windows_program(candidate, name):
115
+ """Resolve an npm launcher to its installed executable, keeping CLI arguments out of cmd.exe."""
116
+ path = Path(candidate)
117
+ if path.suffix.lower() == '.exe':
118
+ return str(path) if path.is_file() else None
119
+ if path.suffix.lower() != '.cmd' or path.stem.lower() != name or not path.is_file():
120
+ return None
121
+ if name not in {'codex', 'claude'}:
122
+ return None
123
+ modules = path.parent.parent if path.parent.name == '.bin' else path.parent / 'node_modules'
124
+ machine = platform.machine().lower()
125
+ archs = ['arm64', 'x64'] if machine in {'arm64', 'aarch64'} else ['x64']
126
+ if name == 'codex':
127
+ package = modules / '@openai' / 'codex'
128
+ else:
129
+ package = modules / '@anthropic-ai' / 'claude-code'
130
+ candidates = []
131
+ if name == 'claude':
132
+ candidates.append(package / 'bin' / 'claude.exe')
133
+ for arch in archs:
134
+ if name == 'codex':
135
+ triple = ('aarch64' if arch == 'arm64' else 'x86_64') + '-pc-windows-msvc'
136
+ binary = Path('vendor') / triple / 'bin' / 'codex.exe'
137
+ platform_package = Path('@openai') / ('codex-win32-' + arch)
138
+ candidates.extend([modules / platform_package / binary, package / 'node_modules' / platform_package / binary, package / binary])
139
+ else:
140
+ binary = Path('@anthropic-ai') / ('claude-code-win32-' + arch) / 'claude.exe'
141
+ candidates.extend([modules / binary, package / 'node_modules' / binary])
142
+ for exe in candidates:
143
+ try:
144
+ # A failed npm postinstall can leave a JavaScript placeholder named .exe.
145
+ with exe.open('rb') as binary_file:
146
+ if binary_file.read(2) == b'MZ':
147
+ return str(exe)
148
+ except OSError:
149
+ continue
150
+ return None
151
+
152
+
153
+ def cli_override(name, candidate):
154
+ path = Path(candidate)
155
+ if not path.is_absolute():
156
+ return None
157
+ if os.name == 'nt':
158
+ return windows_program(path, name)
159
+ return str(path) if path.is_file() and os.access(path, os.X_OK) else None
160
+
161
+
162
+ def find_cli(name):
163
+ import app_preferences
164
+ from adapters import REGISTRY
165
+ provider = next((p.id for p in REGISTRY.values() if p.cli_name == name), None)
166
+ override = app_preferences.get().get(provider, {}).get("cli_path") if provider else None
167
+ if override:
168
+ return cli_override(name, override)
169
+ return autodetect_cli(name)
170
+
171
+
172
+ def autodetect_cli(name):
173
+ if name in {'claude', 'agy'}:
174
+ local = data_root() / '.runtime' / (name + '.exe' if os.name == 'nt' else name)
175
+ if local.is_file() and os.access(local, os.X_OK):
176
+ return str(local)
177
+ if os.name == 'nt':
178
+ # shutil.which on Python 3.11 prepends the current working directory on Windows.
179
+ for directory in cli_path().split(os.pathsep):
180
+ for suffix in ('.exe', '.cmd'):
181
+ found = windows_program(Path(directory) / (name + suffix), name)
182
+ if found:
183
+ return found
184
+ return None
185
+ return shutil.which(name, path=cli_path())
186
+
187
+
188
+ if __name__ == '__main__':
189
+ if sys.argv[1:] != ['--use-this-library'] or sys.platform != 'darwin':
190
+ raise SystemExit('Usage on macOS: python3 runtime_paths.py --use-this-library')
191
+ try:
192
+ selection = use_source_library(RESOURCE_ROOT)
193
+ except (OSError, ValueError) as error:
194
+ raise SystemExit(str(error)) from error
195
+ print(f'diff will use this library. The location is recorded in {selection}.')
server_security.py ADDED
@@ -0,0 +1,100 @@
1
+ """Per-process loopback identity and the private handoff used by the launchers."""
2
+ import hmac
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import secrets
8
+ import sys
9
+ import tempfile
10
+
11
+ from starlette.responses import JSONResponse
12
+ from runtime_paths import user_directory
13
+
14
+ BIND_HOST = "127.0.0.1"
15
+ RUN_ID = re.compile(r"^/api/runs/[a-f0-9]{32}/events$")
16
+ TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}")
17
+ CSP = ("default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; "
18
+ "connect-src 'self'; img-src 'self' data: blob:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
19
+
20
+
21
+ def instance_file(port):
22
+ if sys.platform == "darwin":
23
+ base = Path.home() / "Library" / "Caches"
24
+ elif os.name == "nt":
25
+ base = user_directory("LOCALAPPDATA", Path.home() / "AppData" / "Local")
26
+ else:
27
+ base = user_directory("XDG_RUNTIME_DIR", Path.home() / ".cache")
28
+ return base / "diff-chat" / f"instance-{int(port)}.json"
29
+
30
+
31
+ def instance_proof(token, nonce):
32
+ return hmac.digest(token.encode("ascii"), ("diff-instance-v1/" + nonce).encode("ascii"), "sha256").hex()
33
+
34
+
35
+ def read_instance(port):
36
+ try:
37
+ value = json.loads(instance_file(port).read_text(encoding="utf-8"))
38
+ token = value["token"]
39
+ if isinstance(token, str) and TOKEN_PATTERN.fullmatch(token):
40
+ return token
41
+ except (OSError, ValueError, KeyError, TypeError):
42
+ pass
43
+ return None
44
+
45
+
46
+ class LocalSession:
47
+ def __init__(self):
48
+ self.token = secrets.token_urlsafe(32)
49
+ self.port = None
50
+
51
+ def launch_url(self, origin):
52
+ return origin.rstrip("/") + "/#token=" + self.token
53
+
54
+ def publish(self, port):
55
+ self.token = secrets.token_urlsafe(32)
56
+ self.port = port
57
+ path = instance_file(port)
58
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
59
+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False, encoding="utf-8") as f:
60
+ temporary = Path(f.name)
61
+ json.dump({"token": self.token}, f)
62
+ try:
63
+ os.replace(temporary, path)
64
+ finally:
65
+ temporary.unlink(missing_ok=True)
66
+
67
+ def retire(self):
68
+ if self.port and read_instance(self.port) == self.token:
69
+ instance_file(self.port).unlink(missing_ok=True)
70
+
71
+ async def guard(self, request, call_next):
72
+ server = request.scope.get("server")
73
+ port = self.port or (server[1] if server else None)
74
+ authority = BIND_HOST if port == 80 else f"{BIND_HOST}:{port}"
75
+ hosts = request.headers.getlist("host")
76
+ origins = request.headers.getlist("origin")
77
+ path = request.scope["path"]
78
+ if hosts != [authority] or (origins and origins != ["http://" + authority]):
79
+ response = JSONResponse({"detail": "Use the local diff window."}, 403)
80
+ elif path.startswith("/api/") and not self.authorized(request, path):
81
+ response = JSONResponse({"detail": "Open diff from its launcher to connect this tab."}, 401)
82
+ elif request.method in {"POST", "PUT", "PATCH"} and request.headers.get("content-type", "").split(";")[0].strip() != "application/json":
83
+ response = JSONResponse({"detail": "Expected application/json."}, 415)
84
+ else:
85
+ response = await call_next(request)
86
+ response.headers.update({"Content-Security-Policy": CSP, "Referrer-Policy": "no-referrer",
87
+ "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY",
88
+ "Cache-Control": "no-cache" if path.startswith("/static/") else "no-store"})
89
+ return response
90
+
91
+ def authorized(self, request, path):
92
+ headers = request.headers.getlist("authorization")
93
+ candidates = []
94
+ if len(headers) == 1 and headers[0].startswith("Bearer "):
95
+ candidates = [headers[0][7:]]
96
+ elif not headers and request.method == "GET" and RUN_ID.fullmatch(path):
97
+ # Native EventSource has no request-header option. Only this endpoint accepts a query token.
98
+ candidates = request.query_params.getlist("session")
99
+ return (len(candidates) == 1 and TOKEN_PATTERN.fullmatch(candidates[0]) is not None
100
+ and hmac.compare_digest(candidates[0], self.token))
setup_status.py ADDED
@@ -0,0 +1,123 @@
1
+ """Readiness checks using the same subscription logins the chat adapters require."""
2
+ import asyncio
3
+ from pathlib import Path
4
+ import subprocess
5
+ import tempfile
6
+ import time
7
+
8
+ from fastapi import APIRouter, HTTPException, Request
9
+ from connection_handoff import open_terminal
10
+ import private_store
11
+ from adapters import VERSIONS, LOGIN, ModelError, _Invocation, _check_login, _environment, _prepare_codex
12
+ from adapters._cli import SetupRequired
13
+ from probe import find_cli
14
+
15
+ router = APIRouter()
16
+ INSTALL = {"claude": "npm install -g @anthropic-ai/claude-code@2.1.280",
17
+ "gpt": "npm install -g @openai/codex@0.166.0"}
18
+ _lock = asyncio.Lock()
19
+ _last = 0.0
20
+ _snapshot = {}
21
+
22
+
23
+ @router.get("/api/setup/ping")
24
+ def ping(request: Request):
25
+ status = {"application": "diff", "protocol": 2}
26
+ if request.app.state.draining:
27
+ status["closing"] = True
28
+ return status
29
+
30
+
31
+ async def check_subscription(provider):
32
+ path = find_cli("claude" if provider == "claude" else "codex")
33
+ if not path:
34
+ return {"status": "missing", "hint": "Install the CLI", "command": INSTALL[provider]}
35
+ details = {"path": str(path), "version": None}
36
+ try:
37
+ async with asyncio.timeout(8):
38
+ with tempfile.TemporaryDirectory(prefix="transcript-check-") as directory:
39
+ root = Path(directory)
40
+ cwd = root / "workspace"
41
+ cwd.mkdir()
42
+ env = _environment(root, provider)
43
+ if provider == "gpt":
44
+ original = Path(env["CODEX_HOME"]).expanduser().resolve()
45
+ home = root / "codex"
46
+ home.mkdir(mode=0o700)
47
+ env["CODEX_HOME"] = str(home)
48
+ call = _Invocation(path, cwd, env)
49
+ code, output = await call.execute(["--version"])
50
+ details["version"] = output.decode(errors="replace").strip()[:120]
51
+ if code or details["version"] != VERSIONS[provider]:
52
+ return {**details, "status": "update", "hint": "Install the supported version", "command": INSTALL[provider]}
53
+ if provider == "gpt":
54
+ await _prepare_codex(call, original)
55
+ else:
56
+ await _check_login(call, provider)
57
+ return {**details, "status": "ready", "hint": "Subscription connected", "command": None}
58
+ except SetupRequired as error:
59
+ return {**details, "status": "setup", "hint": str(error), "command": None}
60
+ except ModelError:
61
+ return {**details, "status": "login", "hint": "Sign in with your subscription", "command": LOGIN[provider]}
62
+ except (TimeoutError, OSError, ExceptionGroup):
63
+ return {**details, "status": "unavailable", "hint": "Couldn’t check the local CLI. Try checking again.", "command": None}
64
+
65
+
66
+ async def check(provider):
67
+ from adapters import REGISTRY
68
+ if private_store.is_disconnected(provider):
69
+ return {"status": "disconnected", "hint": "Disconnected from diff.",
70
+ "action": {"id": "reconnect", "label": "Reconnect"}}
71
+ adapter = REGISTRY[provider]
72
+ row = await adapter.detect()
73
+ if action := adapter.setup_action(row["status"]):
74
+ return dict(row, action={"id": action.id, "label": action.label})
75
+ return row
76
+
77
+
78
+ @router.post("/api/setup/{provider}/actions/{action_id}")
79
+ async def launch_setup(provider: str, action_id: str):
80
+ global _last, _snapshot
81
+ from adapters import REGISTRY
82
+ adapter = REGISTRY.get(provider)
83
+ if adapter is None:
84
+ raise HTTPException(404, "Unknown participant.")
85
+ if action_id in {"disconnect", "reconnect"}:
86
+ from plan_usage import invalidate_usage
87
+ async with _lock:
88
+ private_store.set_disconnected(provider, action_id == "disconnect")
89
+ _last, _snapshot = 0.0, {}
90
+ invalidate_usage({provider})
91
+ return {"disconnected": action_id == "disconnect"}
92
+ if private_store.is_disconnected(provider):
93
+ raise HTTPException(409, "Reconnect this participant in diff first.")
94
+ row = await adapter.detect()
95
+ action = adapter.setup_action(row["status"])
96
+ if not action or action.id != action_id or private_store.is_disconnected(provider):
97
+ raise HTTPException(409, "Connection status changed. Choose Check again.")
98
+ try:
99
+ await asyncio.to_thread(open_terminal, action)
100
+ except (OSError, subprocess.SubprocessError):
101
+ raise HTTPException(503, "Couldn’t open a terminal. Use the setup command below.") from None
102
+ return {"opened": True}
103
+
104
+
105
+ @router.get("/api/setup/disconnected")
106
+ def disconnected_participants():
107
+ from adapters import REGISTRY
108
+ return [p for p in REGISTRY if private_store.is_disconnected(p)]
109
+
110
+
111
+ @router.get("/api/setup")
112
+ async def status(refresh: bool = False):
113
+ global _last, _snapshot
114
+ requested = time.monotonic()
115
+ async with _lock:
116
+ cached_off = {p for p, item in _snapshot.items() if item["status"] == "disconnected"}
117
+ if (not _snapshot or requested - _last >= 60 or (refresh and requested > _last)
118
+ or cached_off != set(disconnected_participants())):
119
+ from adapters import REGISTRY
120
+ values = await asyncio.gather(*(check(name) for name in REGISTRY))
121
+ _snapshot = dict(zip(REGISTRY, values))
122
+ _last = time.monotonic()
123
+ return _snapshot