diff-chat 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. adapters/README.md +28 -0
  2. adapters/__init__.py +48 -0
  3. adapters/_base.py +102 -0
  4. adapters/_cli.py +405 -0
  5. adapters/claude.py +141 -0
  6. adapters/gemini.py +323 -0
  7. adapters/gpt.py +217 -0
  8. adapters/local.py +146 -0
  9. adapters/registry.py +33 -0
  10. api_fallback.py +189 -0
  11. app.py +827 -0
  12. app_preferences.py +205 -0
  13. archive_schema.py +142 -0
  14. attachments.py +129 -0
  15. chat_titles.py +60 -0
  16. connection_handoff.py +64 -0
  17. context_engine.py +256 -0
  18. conversation_actions.py +160 -0
  19. diff_chat-0.1.0.dist-info/METADATA +101 -0
  20. diff_chat-0.1.0.dist-info/RECORD +91 -0
  21. diff_chat-0.1.0.dist-info/WHEEL +4 -0
  22. diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
  23. diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
  24. diff_chat_assets/memory.example.md +1 -0
  25. diff_chat_assets/prompts/about_you_export.md +19 -0
  26. diff_chat_assets/settings.json +6 -0
  27. diff_chat_assets/static/about-you-parser.js +46 -0
  28. diff_chat_assets/static/about-you.js +171 -0
  29. diff_chat_assets/static/actions.css +275 -0
  30. diff_chat_assets/static/actions.js +650 -0
  31. diff_chat_assets/static/app.css +345 -0
  32. diff_chat_assets/static/app.js +1344 -0
  33. diff_chat_assets/static/attachments.js +80 -0
  34. diff_chat_assets/static/brand/favicon-32.png +0 -0
  35. diff_chat_assets/static/brand/icon.svg +11 -0
  36. diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
  37. diff_chat_assets/static/brand/wordmark-light.svg +13 -0
  38. diff_chat_assets/static/characters/CREDITS.md +7 -0
  39. diff_chat_assets/static/characters/characters.css +37 -0
  40. diff_chat_assets/static/characters/claude.json +507 -0
  41. diff_chat_assets/static/characters/claude.png +0 -0
  42. diff_chat_assets/static/characters/claude.webp +0 -0
  43. diff_chat_assets/static/characters/gemini.json +54 -0
  44. diff_chat_assets/static/characters/gemini.png +0 -0
  45. diff_chat_assets/static/characters/gemini.webp +0 -0
  46. diff_chat_assets/static/characters/gpt.json +507 -0
  47. diff_chat_assets/static/characters/gpt.png +0 -0
  48. diff_chat_assets/static/characters/gpt.webp +0 -0
  49. diff_chat_assets/static/characters/local.json +387 -0
  50. diff_chat_assets/static/characters/local.png +0 -0
  51. diff_chat_assets/static/characters/local.webp +0 -0
  52. diff_chat_assets/static/characters/player.js +318 -0
  53. diff_chat_assets/static/chat-filing.js +84 -0
  54. diff_chat_assets/static/controls.js +194 -0
  55. diff_chat_assets/static/corners.css +59 -0
  56. diff_chat_assets/static/craft.css +246 -0
  57. diff_chat_assets/static/drafts.js +41 -0
  58. diff_chat_assets/static/index.html +208 -0
  59. diff_chat_assets/static/library.css +30 -0
  60. diff_chat_assets/static/library.js +181 -0
  61. diff_chat_assets/static/memory.js +81 -0
  62. diff_chat_assets/static/preference-dialog.js +21 -0
  63. diff_chat_assets/static/preferences.css +56 -0
  64. diff_chat_assets/static/session.js +46 -0
  65. diff_chat_assets/static/settings.css +111 -0
  66. diff_chat_assets/static/settings.js +463 -0
  67. diff_chat_assets/static/setup.js +238 -0
  68. diff_chat_assets/static/utility.js +64 -0
  69. diff_chat_assets/static/vendor/LICENSES.txt +531 -0
  70. diff_chat_assets/static/vendor/highlight.min.js +1262 -0
  71. diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
  72. diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
  73. diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
  74. diff_launcher.py +93 -0
  75. discussion.py +239 -0
  76. history_search.py +68 -0
  77. library_manager.py +251 -0
  78. model_options.py +132 -0
  79. plan_usage.py +72 -0
  80. private_store.py +71 -0
  81. probe.py +195 -0
  82. runtime_paths.py +195 -0
  83. server_security.py +100 -0
  84. setup_status.py +123 -0
  85. shared_memory.py +189 -0
  86. storage.py +185 -0
  87. usage_budget.py +77 -0
  88. usage_claude.py +110 -0
  89. usage_codex.py +170 -0
  90. usage_gemini.py +70 -0
  91. utility_models.py +104 -0
adapters/claude.py ADDED
@@ -0,0 +1,141 @@
1
+ """Claude Code subscription, scoped tools, model choices and stream protocol."""
2
+ import json
3
+ from uuid import uuid4
4
+
5
+ from model_options import CLAUDE_OPTIONS, resolve_choice
6
+ from ._base import CliParticipant
7
+ from ._cli import (CLAUDE_CONTROL, INSTALL, ModelError, Reply, _check_login, _private_dir, _uuid)
8
+
9
+
10
+ class ClaudeReply(Reply):
11
+ async def accept_event(self, kind, event):
12
+ if (kind == "system" and event.get("subtype") == "init") or kind == "result":
13
+ self.session_id = _uuid(event.get("session_id")) or self.session_id
14
+ if kind == "system" and event.get("subtype") == "init":
15
+ self.session_started = True
16
+ if kind == "stream_event":
17
+ part = event.get("event") or {}
18
+ delta = part.get("delta") or {}
19
+ if part.get("type") == "message_start":
20
+ self.reported = (part.get("message") or {}).get("model", "")
21
+ if part.get("type") == "content_block_delta" and delta.get("type") == "text_delta":
22
+ if self._matches_selection():
23
+ await self.on_delta(delta["text"])
24
+ elif kind == "assistant":
25
+ message = event.get("message") or {}
26
+ self.reported = message.get("model", "") or self.reported
27
+ for block in message.get("content") or []:
28
+ if not isinstance(block, dict):
29
+ continue
30
+ if block.get("type") in {"tool_use", "server_tool_use"} and block.get("name") in {"WebSearch", "web_search"}:
31
+ if isinstance(block.get("id"), str):
32
+ self.search_ids.add(block["id"])
33
+ self.search_activity()
34
+ if block.get("type") == "text" and block.get("citations"):
35
+ web_citations = [c for c in block["citations"] if isinstance(c, dict) and c.get("url")]
36
+ if web_citations:
37
+ self.search_activity(web_citations)
38
+ elif kind == "user" and self.on_search:
39
+ # Claude Code returns hosted results under the outer WebSearch tool call.
40
+ result = event.get("tool_use_result")
41
+ content = (event.get("message") or {}).get("content") or []
42
+ matched = any(isinstance(b, dict) and b.get("type") == "tool_result"
43
+ and b.get("tool_use_id") in self.search_ids for b in content)
44
+ if matched and isinstance(result, dict) and isinstance(result.get("results"), list):
45
+ for group in result["results"]:
46
+ if isinstance(group, dict) and isinstance(group.get("content"), list):
47
+ self.search_activity(group["content"])
48
+ elif kind == "result":
49
+ self.finished = True
50
+ if event.get("is_error") or event.get("subtype") != "success":
51
+ self.error = event.get("result") or "Claude could not complete the reply."
52
+ if (event.get("subtype") == "error_during_execution" and event.get("num_turns") == 0
53
+ and event.get("duration_api_ms") == 0 and self.session_id
54
+ and event.get("errors") == [f"No conversation found with session ID: {self.session_id}"]):
55
+ self.missing_id = self.session_id
56
+ else:
57
+ if self.expected and not self.reported:
58
+ usage = event.get("modelUsage") or {}
59
+ if len(usage) == 1:
60
+ self.reported = next(iter(usage))
61
+ if self._matches_selection():
62
+ self.text = event.get("result", "")
63
+ elif self.reported:
64
+ self.error = f"Claude reported {self.reported} for the requested {self.expected}."
65
+ else:
66
+ self.error = f"Claude did not confirm the selected model {self.expected}."
67
+
68
+
69
+ class Claude(CliParticipant):
70
+ login_args = ("auth", "login", "--claudeai")
71
+ id, label, cli_name, order = "claude", "Claude", "claude", 10
72
+ color, dark_color, fill, dark_fill = "#994727", "#e69b78", "#c66941", "#d68a66"
73
+ default_enabled = True
74
+ search_tool = "WebSearch"
75
+ character = "/static/characters/claude.json"
76
+ reply = ClaudeReply
77
+
78
+ def expected_model(self, model_id):
79
+ return model_id if model_id == "claude-opus-5-5" else None
80
+
81
+ async def list_models(self):
82
+ return CLAUDE_OPTIONS
83
+
84
+ async def usage(self):
85
+ from usage_claude import get_claude_usage
86
+ return await get_claude_usage()
87
+
88
+ async def command(self, call, root, framing, transcript, model_id, effort, web_search, images,
89
+ session_dir, session_id, legacy, credential_links):
90
+ native = session_dir is not None
91
+ target_id = session_id
92
+ model = self.id
93
+ if native and legacy:
94
+ if session_id:
95
+ raise ModelError("Install the verified Claude Code 2.1.280 to resume this session.")
96
+ native = False
97
+ if native:
98
+ private = session_dir / "claude"
99
+ _private_dir(private)
100
+ # This pinned build routes file/keychain credentials and refresh to
101
+ # secure storage separately from its settings and conversation data.
102
+ call.env["CLAUDE_SECURESTORAGE_CONFIG_DIR"] = call.env.get("CLAUDE_CONFIG_DIR", "")
103
+ call.env.update(CLAUDE_CONFIG_DIR=str(private), CLAUDE_CODE_PROJECT_DIR_NAME="transcript")
104
+ try:
105
+ choice, level = resolve_choice(CLAUDE_OPTIONS, "default" if model_id is None else model_id, effort)
106
+ except ValueError as error:
107
+ raise ModelError(str(error)) from error
108
+ if legacy and choice["id"] == "claude-opus-5-5":
109
+ raise ModelError(f"Opus 5.5 requires Claude Code 2.1.280 or later. "
110
+ f"Install the verified version with {INSTALL['claude']}.")
111
+ await _check_login(call, model)
112
+ args = [*CLAUDE_CONTROL, "-p", "--tools", "WebSearch" if web_search else "", "--permission-mode", "dontAsk",
113
+ "--disable-slash-commands", "--no-chrome",
114
+ "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}',
115
+ "--system-prompt", framing, "--output-format", "stream-json",
116
+ "--verbose", "--include-partial-messages"]
117
+ if native:
118
+ target_id = session_id or str(uuid4())
119
+ args.extend(["--resume" if session_id else "--session-id", target_id])
120
+ else:
121
+ args.append("--no-session-persistence")
122
+ if web_search:
123
+ args.extend(["--allowedTools", "WebSearch"])
124
+ if not legacy:
125
+ args.extend(["--restricted", "--system-prompt-snapshot", "off"])
126
+ if choice["id"] != "default":
127
+ args.extend(["--model", choice["id"]])
128
+ if level != "default":
129
+ args.extend(["--effort", level])
130
+ prompt = transcript
131
+ if images:
132
+ blocks = [{"type": "text", "text": transcript}]
133
+ for image in images:
134
+ blocks.append({"type": "text", "text": f"Image from the user at {image.get('message_time', '')}: {image['name']}"})
135
+ blocks.append({"type": "image", "source": {"type": "base64", "media_type": image["type"], "data": image["data"]}})
136
+ args.extend(["--input-format", "stream-json"])
137
+ prompt = json.dumps({"type": "user", "message": {"role": "user", "content": blocks}}) + "\n"
138
+ return args, prompt, native, target_id
139
+
140
+
141
+ ADAPTER = Claude()
adapters/gemini.py ADDED
@@ -0,0 +1,323 @@
1
+ """Google Antigravity's personal-account headless CLI, with a diff-owned profile."""
2
+ import asyncio
3
+ from contextlib import asynccontextmanager, suppress
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import re
8
+ import shlex
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+
13
+ from runtime_paths import MODULE_ROOT, cli_path, data_root, find_cli
14
+ from ._base import Participant, transcript_text
15
+ from ._cli import ModelError, ResumeUnavailable, _Invocation, _private_dir, _tail, _uuid
16
+
17
+ VERSION = "1.5.20"
18
+ INSTALL_URL = "https://antigravity.google/docs/getting-started?tab=cli"
19
+ DENY = ["read_file(*)", "write_file(*)", "command(*)", "read_url(*)",
20
+ "execute_url(*)", "mcp(*)"]
21
+ POLICY = {"agentMode": "plan", "toolPermission": "strict", "enableTerminalSandbox": True,
22
+ "allowNonWorkspaceAccess": False, "disableSlashCommands": True,
23
+ "historySize": 0, "permissions": {"deny": DENY}}
24
+ EMPTY = {"default_model": "", "models": []}
25
+ PERSONAL_SIGN_IN = ("In Terminal, choose Google OAuth and sign in with your personal Google account. "
26
+ "If a previous sign-in appears, choose Other sign-in options first.")
27
+
28
+
29
+ def profile():
30
+ home = data_root() / ".runtime" / "antigravity-profile"
31
+ home.mkdir(mode=0o700, parents=True, exist_ok=True)
32
+ _private_dir(home)
33
+ shared = home / ".gemini" / "config"
34
+ shared.mkdir(mode=0o700, parents=True, exist_ok=True)
35
+ config = shared / "config.json"
36
+ # The CLI enables its built-in delegation plugin on a fresh profile. Disable it
37
+ # before the first CLI process starts. Never modify a user's Google installation.
38
+ if not config.exists():
39
+ try:
40
+ with config.open("x", encoding="utf-8") as f:
41
+ json.dump({"plugins": {"swarm": {"enabled": False}}}, f)
42
+ except FileExistsError:
43
+ pass
44
+ return home
45
+
46
+
47
+ def integrations_off(home):
48
+ """An explicitly added hook, plugin or MCP server in diff's private profile blocks chat."""
49
+ shared = home / ".gemini" / "config"
50
+ cli = home / ".gemini" / "antigravity-cli"
51
+ for path in (shared / "hooks.json", cli / "hooks.json", home / ".agents" / "hooks.json"):
52
+ if path.exists():
53
+ return False
54
+ try:
55
+ config = json.loads((shared / "config.json").read_text(encoding="utf-8"))
56
+ if config.get("plugins", {}).get("swarm", {}).get("enabled") is not False:
57
+ return False
58
+ if any(not isinstance(value, dict) or value.get("enabled") is not False
59
+ for value in config.get("plugins", {}).values()) or config.get("sidecars"):
60
+ return False
61
+ mcp = shared / "mcp_config.json"
62
+ if mcp.exists():
63
+ text = mcp.read_text(encoding="utf-8").strip()
64
+ if text and json.loads(text).get("mcpServers"):
65
+ return False
66
+ except (AttributeError, ValueError, OSError):
67
+ return False
68
+ return True
69
+
70
+
71
+ def environment(home, temp):
72
+ env = {key: os.environ[key] for key in ("USER", "LANG", "LC_ALL", "LOGNAME", "SYSTEMROOT",
73
+ "WINDIR", "PATHEXT", "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR") if key in os.environ}
74
+ env.update(PATH=cli_path(), HOME=str(home), USERPROFILE=str(home),
75
+ APPDATA=str(home / "Roaming"), LOCALAPPDATA=str(home / "Local"),
76
+ XDG_CONFIG_HOME=str(home / ".config"), XDG_DATA_HOME=str(home / ".local/share"),
77
+ TMPDIR=str(temp), TMP=str(temp), TEMP=str(temp), AGY_CLI_DISABLE_AUTO_UPDATE="true",
78
+ NO_COLOR="1")
79
+ return env
80
+
81
+
82
+ def login_argv():
83
+ args = [sys.executable]
84
+ if not getattr(sys, "frozen", False):
85
+ args.append(str(MODULE_ROOT / "app.py"))
86
+ args.append("--login-gemini")
87
+ return tuple(args)
88
+
89
+
90
+ def login_command():
91
+ args = login_argv()
92
+ library = os.environ.get("TRANSCRIPT_DATA_ROOT")
93
+ if os.name == "nt":
94
+ def quote(arg):
95
+ return "'" + arg.replace("'", "''") + "'"
96
+ command = "& " + " ".join(map(quote, args))
97
+ return "$env:TRANSCRIPT_DATA_ROOT=" + quote(str(data_root())) + "; " + command if library else command
98
+ if library:
99
+ args = ("env", "TRANSCRIPT_DATA_ROOT=" + str(data_root()), *args)
100
+ return shlex.join(args)
101
+
102
+
103
+ def policy_args(*, builtin_command=False):
104
+ # Only a fixed CLI-owned command may expand slash syntax. Chat inputs always
105
+ # use the fully restricted policy, even when a message starts with a slash.
106
+ policy = {**POLICY, "disableSlashCommands": False} if builtin_command else POLICY
107
+ return ["--mode", "plan", "--sandbox", "--settings", json.dumps(policy)]
108
+
109
+
110
+ def login():
111
+ """Interactive provider-owned OAuth, using exactly the profile read by detect/send."""
112
+ binary = find_cli("agy")
113
+ if not binary:
114
+ print(f"Install Antigravity CLI first. {INSTALL_URL}", file=sys.stderr)
115
+ return 1
116
+ with tempfile.TemporaryDirectory(prefix="diff-google-login-") as directory:
117
+ home = profile()
118
+ if not integrations_off(home):
119
+ print("Remove enabled hooks, plugins, MCP servers or sidecars from diff’s private Google CLI profile.", file=sys.stderr)
120
+ return 1
121
+ env = environment(home, directory)
122
+ version = subprocess.run([binary, "--version"], cwd=directory, env=env, timeout=8,
123
+ capture_output=True, text=True)
124
+ if version.returncode or version.stdout.strip() != VERSION:
125
+ print(f"diff has verified Antigravity CLI {VERSION}.", file=sys.stderr)
126
+ return 1
127
+ print(PERSONAL_SIGN_IN, flush=True)
128
+ print("If you see “Select subscription”, press Esc to return to the login methods. "
129
+ "After sign-in, return to diff and choose Check again.", flush=True)
130
+ return subprocess.call([binary, *policy_args()],
131
+ env=env, cwd=directory)
132
+
133
+
134
+ @asynccontextmanager
135
+ async def isolated(binary):
136
+ with tempfile.TemporaryDirectory(prefix="diff-google-") as directory:
137
+ root = Path(directory).resolve()
138
+ cwd = root / "workspace"
139
+ cwd.mkdir(mode=0o700)
140
+ home = profile()
141
+ if not integrations_off(home):
142
+ raise ModelError("Remove enabled hooks, plugins, MCP servers or sidecars from diff’s private Google CLI profile.")
143
+ call = _Invocation(binary, cwd, environment(home, root))
144
+ version, raw = await call.execute(["--version"])
145
+ if version or raw.decode(errors="replace").strip() != VERSION:
146
+ raise ModelError(f"diff requires the verified Antigravity CLI {VERSION}.")
147
+ yield call
148
+
149
+
150
+ def parse_models(output):
151
+ """This release prints slug TAB display name; only offer Google Gemini models."""
152
+ rows = []
153
+ for line in output.decode(errors="replace").splitlines():
154
+ slug, sep, name = line.partition("\t")
155
+ if not sep or not re.fullmatch(r"gemini-[a-z0-9][a-z0-9.-]{0,115}", slug) or len(name) > 128:
156
+ continue
157
+ rows.append((slug, name.strip() or slug))
158
+ # The account catalog lists separate slugs for effort variants. Send only
159
+ # an advertised combination; the picker maps the level back to its exact slug.
160
+ models = {}
161
+ for slug, name in rows:
162
+ family, _, ending = slug.rpartition("-")
163
+ variant = ending in {"low", "medium", "high", "xhigh", "max"}
164
+ identity, effort = (family, ending) if variant else (slug, "default")
165
+ if identity not in models:
166
+ models[identity] = {"id": identity, "label": re.sub(r"\s*\([^)]*\)$", "", name) if variant else name,
167
+ "default_effort": effort, "efforts": []}
168
+ models[identity]["efforts"].append(effort)
169
+ for model in models.values():
170
+ if "medium" in model["efforts"]:
171
+ model["default_effort"] = "medium"
172
+ return {"default_model": next(iter(models), ""), "models": list(models.values())}
173
+
174
+
175
+ async def catalog(call):
176
+ status, data = await call.execute(["models"])
177
+ if status:
178
+ if "sign in" in _tail(call.stderr).lower():
179
+ raise LoginRequired(PERSONAL_SIGN_IN)
180
+ raise ModelError("Antigravity could not fetch the Google account's model list.")
181
+ options = parse_models(data)
182
+ if not options["models"]:
183
+ raise ModelError("Antigravity returned no supported Gemini model for this account.")
184
+ return options
185
+
186
+
187
+ class LoginRequired(ModelError):
188
+ pass
189
+
190
+
191
+ class Gemini(Participant):
192
+ id, label, cli_name, order = "gemini", "Gemini", "agy", 30
193
+ color, dark_color = "#4A6382", "#7F9BBE"
194
+ character = "/static/characters/gemini.json"
195
+
196
+ async def usage(self):
197
+ from usage_gemini import get_gemini_usage
198
+ return await get_gemini_usage()
199
+
200
+ def setup_action(self, status):
201
+ from connection_handoff import SetupAction
202
+ if status == "login":
203
+ return SetupAction("login", "Connect Gemini", login_argv())
204
+ return None
205
+
206
+ def capabilities(self):
207
+ return {**super().capabilities(), "sessions": True, "reasoning_levels": True}
208
+
209
+ def resume(self, session_id):
210
+ if not _uuid(session_id):
211
+ raise ResumeUnavailable("Invalid Google conversation ID.")
212
+ return session_id
213
+
214
+ async def detect(self):
215
+ binary = find_cli(self.cli_name)
216
+ if not binary:
217
+ return {"status": "missing", "hint": "Install Google's Antigravity CLI.",
218
+ "install_url": INSTALL_URL, "command": None}
219
+ details = {"path": binary, "command": None, "version": None}
220
+ try:
221
+ async with asyncio.timeout(12), isolated(binary) as call:
222
+ details["version"] = VERSION
223
+ await catalog(call)
224
+ return {**details, "status": "ready", "hint": "Google account connected"}
225
+ except LoginRequired as error:
226
+ return {**details, "status": "login", "hint": str(error), "command": login_command()}
227
+ except (TimeoutError, OSError, ModelError) as error:
228
+ return {**details, "status": "unavailable", "hint": str(error) or "Google CLI check timed out."}
229
+
230
+ async def list_models(self):
231
+ if not (binary := find_cli(self.cli_name)):
232
+ return EMPTY
233
+ try:
234
+ async with asyncio.timeout(12), isolated(binary) as call:
235
+ return await catalog(call)
236
+ except (TimeoutError, OSError, ModelError):
237
+ return EMPTY
238
+
239
+ async def send(self, messages, model, reasoning, system, attachments, session_id, *, timeout=120,
240
+ session_dir=None, on_input=None, on_session=None, on_final=None, **runtime):
241
+ from model_options import resolve_choice
242
+ if attachments:
243
+ raise ModelError("Antigravity’s headless input supports text only. Remove images or turn Gemini off.")
244
+ if not (binary := find_cli(self.cli_name)):
245
+ raise ModelError("Install Google Antigravity CLI to use Gemini.")
246
+ marker = None
247
+ if session_dir:
248
+ folder = Path(session_dir)
249
+ _private_dir(folder)
250
+ marker = folder / "google-session"
251
+ if session_id:
252
+ self.resume(session_id)
253
+ if not marker or not marker.is_file() or marker.is_symlink() or marker.read_text() != session_id:
254
+ raise ResumeUnavailable("This Google conversation is no longer available.")
255
+ text = transcript_text(messages)
256
+ async with asyncio.timeout(timeout), isolated(binary) as call:
257
+ options = await catalog(call)
258
+ try:
259
+ selected, effort = resolve_choice(options, model, reasoning)
260
+ except ValueError as error:
261
+ raise ModelError(str(error)) from error
262
+ slug = selected["id"] + ("-" + effort if effort != "default" else "")
263
+ args = [*policy_args(), "--disable-slash-commands",
264
+ "--input-format", "stream-json", "--output-format", "stream-json",
265
+ "--print-timeout", f"{max(1, int(timeout))}s", "--model", slug]
266
+ if session_id:
267
+ args.extend(["--conversation", session_id])
268
+ prompt = json.dumps({"event": "user", "message": {"content": system + "\n\n" + text}}) + "\n"
269
+ queue = asyncio.Queue()
270
+ result = {}
271
+ started = False
272
+ async def receive(line):
273
+ nonlocal started
274
+ event = json.loads(line)
275
+ if event.get("event") in {"init", "step_update"}:
276
+ started = True
277
+ if event.get("event") == "step_update":
278
+ step = event.get("step_update", {})
279
+ if step.get("step_type") == "agent_response" and isinstance(step.get("text_delta"), str):
280
+ queue.put_nowait(step["text_delta"])
281
+ elif event.get("event") == "result":
282
+ result.update(event["result"])
283
+ async def execute():
284
+ try:
285
+ return await call.execute(args, prompt, receive,
286
+ on_submit=(lambda: on_input(len(system) + len(text))) if on_input else None)
287
+ finally:
288
+ queue.put_nowait(None)
289
+ task = asyncio.create_task(execute())
290
+ emitted = False
291
+ try:
292
+ async with asyncio.timeout(timeout):
293
+ while (piece := await queue.get()) is not None:
294
+ if piece:
295
+ emitted = True
296
+ yield piece
297
+ code, _ = await task
298
+ if code or result.get("status") != "SUCCESS" or not result.get("response"):
299
+ diagnosis = str(result.get("error", "")) + "\n" + _tail(call.stderr)
300
+ if (session_id and not started and re.search(
301
+ r"(?i)(?:conversation(?: id)?[^\n]{0,100}(?:not found|does not exist)|"
302
+ r"(?:unknown|no such) conversation)", diagnosis)):
303
+ raise ResumeUnavailable("This Google conversation is no longer available.")
304
+ raise ModelError("Antigravity could not finish the reply.", _tail(call.stderr))
305
+ identity = _uuid(result.get("conversation_id"))
306
+ if marker and (not identity or (session_id and identity != session_id)):
307
+ raise ModelError("Antigravity did not confirm the requested conversation.")
308
+ if marker and on_session:
309
+ marker.write_text(identity, encoding="ascii")
310
+ on_session(identity)
311
+ final = result["response"]
312
+ if on_final:
313
+ on_final(final)
314
+ if not emitted:
315
+ yield final
316
+ finally:
317
+ if not task.done():
318
+ task.cancel()
319
+ with suppress(asyncio.CancelledError):
320
+ await task
321
+
322
+
323
+ ADAPTER = Gemini()