pyagy 0.7.1__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.
- pyagy/__init__.py +8 -0
- pyagy/__main__.py +4 -0
- pyagy/bootstrap.py +232 -0
- pyagy/cli.py +789 -0
- pyagy/context.py +622 -0
- pyagy/gemini_wire.py +683 -0
- pyagy/models.py +246 -0
- pyagy/multi_agents.py +1538 -0
- pyagy/prompts/__init__.py +0 -0
- pyagy/prompts/static_system_prefix.txt +153 -0
- pyagy/prompts/system_prompt.py +458 -0
- pyagy/prompts/tool_declarations.json +558 -0
- pyagy/task_manager.py +851 -0
- pyagy/tools/__init__.py +325 -0
- pyagy/tools/agent_tools.py +192 -0
- pyagy/tools/command_tools.py +148 -0
- pyagy/tools/file_tools.py +243 -0
- pyagy/tools/interaction_tools.py +182 -0
- pyagy/transcript.py +707 -0
- pyagy-0.7.1.dist-info/METADATA +64 -0
- pyagy-0.7.1.dist-info/RECORD +24 -0
- pyagy-0.7.1.dist-info/WHEEL +4 -0
- pyagy-0.7.1.dist-info/entry_points.txt +2 -0
- pyagy-0.7.1.dist-info/licenses/LICENSE +201 -0
pyagy/cli.py
ADDED
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
"""Antigravity CLI (`agy 1.5.14`) wire-compatible command-line entrypoint."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
import typing
|
|
10
|
+
|
|
11
|
+
from pycodex.events import (
|
|
12
|
+
Event,
|
|
13
|
+
MessagesAddedEvent,
|
|
14
|
+
ToolStartedEvent,
|
|
15
|
+
TurnCompletedEvent,
|
|
16
|
+
TurnFailedEvent,
|
|
17
|
+
)
|
|
18
|
+
from pycodex.protocol import UserMessage
|
|
19
|
+
from pycodex.utils.codex_config import DEFAULT_CODEX_CONFIG_PATH
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
from .bootstrap import AgyBootstrappedSession, build_agy_session
|
|
23
|
+
from .context import (
|
|
24
|
+
AGY_COMPACTION_PROMPT_NAME,
|
|
25
|
+
AGY_RAW_USER_NAME,
|
|
26
|
+
AGY_SYSTEM_MESSAGE_NAME,
|
|
27
|
+
)
|
|
28
|
+
from .models import OFFICIAL_MODELS, normalize_effort_level
|
|
29
|
+
from .multi_agents import AgyCheckpointEvent
|
|
30
|
+
|
|
31
|
+
BUILTIN_AGENTS: "typing.Tuple[typing.Tuple[str, str], ...]" = (
|
|
32
|
+
("self", "General-purpose coding agent with full workspace tools"),
|
|
33
|
+
("research", "Read-only codebase and web research subagent"),
|
|
34
|
+
("image-generator", "Image generation and visual asset preparation subagent"),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_duration_seconds(raw_value: "typing.Optional[str]") -> "typing.Optional[float]":
|
|
39
|
+
"""Parse Go-style duration (`0s`, `15s`, `500ms`, `2m`, `1h`) or float seconds."""
|
|
40
|
+
if raw_value is None:
|
|
41
|
+
return None
|
|
42
|
+
text = str(raw_value).strip().lower()
|
|
43
|
+
if not text:
|
|
44
|
+
return None
|
|
45
|
+
multiplier = 1.0
|
|
46
|
+
if text.endswith("ms"):
|
|
47
|
+
multiplier = 0.001
|
|
48
|
+
num_str = text[:-2]
|
|
49
|
+
elif text.endswith("s"):
|
|
50
|
+
multiplier = 1.0
|
|
51
|
+
num_str = text[:-1]
|
|
52
|
+
elif text.endswith("m"):
|
|
53
|
+
multiplier = 60.0
|
|
54
|
+
num_str = text[:-1]
|
|
55
|
+
elif text.endswith("h"):
|
|
56
|
+
multiplier = 3600.0
|
|
57
|
+
num_str = text[:-1]
|
|
58
|
+
else:
|
|
59
|
+
num_str = text
|
|
60
|
+
seconds = float(num_str) * multiplier
|
|
61
|
+
if seconds < 0:
|
|
62
|
+
raise ValueError(f"duration must be non-negative: {raw_value!r}")
|
|
63
|
+
return None if seconds == 0.0 else seconds
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _format_trailing_newline(text: "str") -> "str":
|
|
67
|
+
if not text:
|
|
68
|
+
return ""
|
|
69
|
+
return text if text.endswith("\n") else (text + "\n")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _write_ndjson(stream: "typing.TextIO", obj: "typing.Dict[str, object]") -> "None":
|
|
73
|
+
stream.write(json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
74
|
+
stream.flush()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _run_models_subcommand(
|
|
78
|
+
argv: "typing.Sequence[str]",
|
|
79
|
+
stdout: "typing.TextIO",
|
|
80
|
+
) -> "int":
|
|
81
|
+
parser = argparse.ArgumentParser(
|
|
82
|
+
prog="pyagy models",
|
|
83
|
+
description="List available models",
|
|
84
|
+
)
|
|
85
|
+
parser.parse_args(list(argv))
|
|
86
|
+
stdout.write("Fetching available models...\n")
|
|
87
|
+
for slug, display_name in OFFICIAL_MODELS:
|
|
88
|
+
stdout.write(f"{slug}\t{display_name}\n")
|
|
89
|
+
stdout.flush()
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _run_agents_subcommand(
|
|
94
|
+
argv: "typing.Sequence[str]",
|
|
95
|
+
stdout: "typing.TextIO",
|
|
96
|
+
) -> "int":
|
|
97
|
+
parser = argparse.ArgumentParser(
|
|
98
|
+
prog="pyagy agent",
|
|
99
|
+
description="List available agents",
|
|
100
|
+
)
|
|
101
|
+
parser.parse_args(list(argv))
|
|
102
|
+
for name, desc in BUILTIN_AGENTS:
|
|
103
|
+
stdout.write(f"{name}\t{desc}\n")
|
|
104
|
+
stdout.flush()
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def build_cli_parser() -> "argparse.ArgumentParser":
|
|
109
|
+
parser = argparse.ArgumentParser(
|
|
110
|
+
prog="pyagy",
|
|
111
|
+
description="Antigravity CLI (agy 1.5.14) wire-compatible mode built on pycodex",
|
|
112
|
+
)
|
|
113
|
+
parser.add_argument(
|
|
114
|
+
"prompt",
|
|
115
|
+
nargs="?",
|
|
116
|
+
default=None,
|
|
117
|
+
help="Prompt text or subcommand (models, agent, agents)",
|
|
118
|
+
)
|
|
119
|
+
parser.add_argument(
|
|
120
|
+
"-v",
|
|
121
|
+
"--version",
|
|
122
|
+
action="version",
|
|
123
|
+
version=f"{__version__} (agy 1.5.14 wire-compatible)",
|
|
124
|
+
)
|
|
125
|
+
parser.add_argument(
|
|
126
|
+
"-p",
|
|
127
|
+
"--print",
|
|
128
|
+
"--prompt",
|
|
129
|
+
dest="print_prompt",
|
|
130
|
+
nargs="?",
|
|
131
|
+
const="",
|
|
132
|
+
default=None,
|
|
133
|
+
help="Run a single prompt non-interactively and print the response",
|
|
134
|
+
)
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"-i",
|
|
137
|
+
"--prompt-interactive",
|
|
138
|
+
dest="interactive_prompt",
|
|
139
|
+
nargs="?",
|
|
140
|
+
const="",
|
|
141
|
+
default=None,
|
|
142
|
+
help="Run an initial prompt interactively and continue the session",
|
|
143
|
+
)
|
|
144
|
+
parser.add_argument(
|
|
145
|
+
"-c",
|
|
146
|
+
"--continue",
|
|
147
|
+
dest="continue_latest",
|
|
148
|
+
action="store_true",
|
|
149
|
+
help="Continue the most recent conversation",
|
|
150
|
+
)
|
|
151
|
+
parser.add_argument(
|
|
152
|
+
"--conversation",
|
|
153
|
+
dest="conversation_id",
|
|
154
|
+
default=None,
|
|
155
|
+
help="Resume a previous conversation by ID",
|
|
156
|
+
)
|
|
157
|
+
parser.add_argument(
|
|
158
|
+
"--model",
|
|
159
|
+
default=None,
|
|
160
|
+
help="Model for the current CLI session",
|
|
161
|
+
)
|
|
162
|
+
parser.add_argument(
|
|
163
|
+
"--effort",
|
|
164
|
+
default=None,
|
|
165
|
+
help="Reasoning effort for the current CLI session (low|medium|high|xhigh|max)",
|
|
166
|
+
)
|
|
167
|
+
parser.add_argument(
|
|
168
|
+
"--config",
|
|
169
|
+
default=str(DEFAULT_CODEX_CONFIG_PATH),
|
|
170
|
+
help="Path to Codex config.toml (default: ~/.codex/config.toml)",
|
|
171
|
+
)
|
|
172
|
+
parser.add_argument(
|
|
173
|
+
"--profile",
|
|
174
|
+
default=None,
|
|
175
|
+
help="Profile name in ~/.codex/config.toml",
|
|
176
|
+
)
|
|
177
|
+
parser.add_argument(
|
|
178
|
+
"--add-dir",
|
|
179
|
+
dest="add_dirs",
|
|
180
|
+
action="append",
|
|
181
|
+
default=[],
|
|
182
|
+
help="Add a directory to the workspace (repeatable)",
|
|
183
|
+
)
|
|
184
|
+
parser.add_argument(
|
|
185
|
+
"--app-data-dir",
|
|
186
|
+
default=None,
|
|
187
|
+
help="Override AGY App Data Directory (default: ~/.gemini/antigravity-cli)",
|
|
188
|
+
)
|
|
189
|
+
parser.add_argument(
|
|
190
|
+
"--output-format",
|
|
191
|
+
choices=("text", "json", "stream-json"),
|
|
192
|
+
default="text",
|
|
193
|
+
help="Output format for print mode (text, json, stream-json)",
|
|
194
|
+
)
|
|
195
|
+
parser.add_argument(
|
|
196
|
+
"--input-format",
|
|
197
|
+
choices=("text", "stream-json"),
|
|
198
|
+
default="text",
|
|
199
|
+
help="Input format for print mode (text, stream-json)",
|
|
200
|
+
)
|
|
201
|
+
parser.add_argument(
|
|
202
|
+
"--print-timeout",
|
|
203
|
+
default="0s",
|
|
204
|
+
help="Optional time limit for print mode; 0s waits until turn completes",
|
|
205
|
+
)
|
|
206
|
+
parser.add_argument(
|
|
207
|
+
"--dangerously-skip-permissions",
|
|
208
|
+
action="store_true",
|
|
209
|
+
help="Auto-approve all tool permission requests without prompting",
|
|
210
|
+
)
|
|
211
|
+
parser.add_argument(
|
|
212
|
+
"--mode",
|
|
213
|
+
choices=("accept-edits", "auto", "plan"),
|
|
214
|
+
default="auto",
|
|
215
|
+
help="Agent execution mode for this session",
|
|
216
|
+
)
|
|
217
|
+
return parser
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _attach_stream_json_observer(
|
|
221
|
+
session: "AgyBootstrappedSession",
|
|
222
|
+
stdout: "typing.TextIO",
|
|
223
|
+
) -> "None":
|
|
224
|
+
root = session.root_node
|
|
225
|
+
seen_msg_ids: "typing.Set[str]" = set()
|
|
226
|
+
step_seq = [root.transcript_store.step_index]
|
|
227
|
+
|
|
228
|
+
def _next_idx() -> "int":
|
|
229
|
+
val = step_seq[0]
|
|
230
|
+
step_seq[0] += 1
|
|
231
|
+
return val
|
|
232
|
+
|
|
233
|
+
def _on_event(event: "Event") -> "None":
|
|
234
|
+
if isinstance(event, MessagesAddedEvent):
|
|
235
|
+
for msg in event.messages:
|
|
236
|
+
if (
|
|
237
|
+
isinstance(msg, UserMessage)
|
|
238
|
+
and msg.message_id not in seen_msg_ids
|
|
239
|
+
and msg.name not in (AGY_RAW_USER_NAME, AGY_COMPACTION_PROMPT_NAME)
|
|
240
|
+
):
|
|
241
|
+
seen_msg_ids.add(msg.message_id)
|
|
242
|
+
stype = (
|
|
243
|
+
"system_message"
|
|
244
|
+
if msg.name == AGY_SYSTEM_MESSAGE_NAME
|
|
245
|
+
else "user_input"
|
|
246
|
+
)
|
|
247
|
+
_write_ndjson(
|
|
248
|
+
stdout,
|
|
249
|
+
{
|
|
250
|
+
"event": "step_update",
|
|
251
|
+
"step_update": {
|
|
252
|
+
"conversation_id": root.conversation_id,
|
|
253
|
+
"step_index": _next_idx(),
|
|
254
|
+
"state": "DONE",
|
|
255
|
+
"step_type": stype,
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
)
|
|
259
|
+
elif isinstance(event, AgyCheckpointEvent):
|
|
260
|
+
_write_ndjson(
|
|
261
|
+
stdout,
|
|
262
|
+
{
|
|
263
|
+
"event": "step_update",
|
|
264
|
+
"step_update": {
|
|
265
|
+
"conversation_id": root.conversation_id,
|
|
266
|
+
"step_index": _next_idx(),
|
|
267
|
+
"state": "DONE",
|
|
268
|
+
"step_type": "checkpoint",
|
|
269
|
+
"duration_seconds": event.duration_seconds,
|
|
270
|
+
"usage": dict(event.usage),
|
|
271
|
+
},
|
|
272
|
+
},
|
|
273
|
+
)
|
|
274
|
+
elif isinstance(event, TurnCompletedEvent):
|
|
275
|
+
if event.output_text is not None:
|
|
276
|
+
_write_ndjson(
|
|
277
|
+
stdout,
|
|
278
|
+
{
|
|
279
|
+
"event": "step_update",
|
|
280
|
+
"step_update": {
|
|
281
|
+
"conversation_id": root.conversation_id,
|
|
282
|
+
"step_index": _next_idx(),
|
|
283
|
+
"state": "DONE",
|
|
284
|
+
"step_type": "agent_response",
|
|
285
|
+
"text_delta": _format_trailing_newline(event.output_text),
|
|
286
|
+
},
|
|
287
|
+
},
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
root.add_event_listener(_on_event)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
async def _run_print_mode_async(
|
|
294
|
+
session: "AgyBootstrappedSession",
|
|
295
|
+
input_format: "str",
|
|
296
|
+
output_format: "str",
|
|
297
|
+
prompt_text: "typing.Optional[str]",
|
|
298
|
+
timeout_seconds: "typing.Optional[float]",
|
|
299
|
+
stdin: "typing.TextIO",
|
|
300
|
+
stdout: "typing.TextIO",
|
|
301
|
+
stderr: "typing.TextIO",
|
|
302
|
+
) -> "int":
|
|
303
|
+
root = session.root_node
|
|
304
|
+
session_start = time.monotonic()
|
|
305
|
+
cumulative_turns = 0
|
|
306
|
+
|
|
307
|
+
if output_format == "stream-json":
|
|
308
|
+
_write_ndjson(
|
|
309
|
+
stdout,
|
|
310
|
+
{
|
|
311
|
+
"event": "init",
|
|
312
|
+
"conversation_id": root.conversation_id,
|
|
313
|
+
"init": {
|
|
314
|
+
"model": root.agent.model_name,
|
|
315
|
+
"cwd": str(root.cwd),
|
|
316
|
+
"tools": sorted(spec.name for spec in root.tool_registry.model_visible_specs()),
|
|
317
|
+
},
|
|
318
|
+
},
|
|
319
|
+
)
|
|
320
|
+
_attach_stream_json_observer(session, stdout)
|
|
321
|
+
|
|
322
|
+
if input_format == "stream-json":
|
|
323
|
+
loop = asyncio.get_running_loop()
|
|
324
|
+
while True:
|
|
325
|
+
raw_line = await loop.run_in_executor(None, stdin.readline)
|
|
326
|
+
if not raw_line:
|
|
327
|
+
break
|
|
328
|
+
stripped = raw_line.strip()
|
|
329
|
+
if not stripped:
|
|
330
|
+
continue
|
|
331
|
+
try:
|
|
332
|
+
obj = json.loads(stripped)
|
|
333
|
+
except json.JSONDecodeError as exc:
|
|
334
|
+
err_msg = f"failed to decode stream input: {exc}"
|
|
335
|
+
stderr.write(f"error: {err_msg}\n")
|
|
336
|
+
stderr.flush()
|
|
337
|
+
_write_ndjson(
|
|
338
|
+
stdout,
|
|
339
|
+
{
|
|
340
|
+
"event": "result",
|
|
341
|
+
"result": {
|
|
342
|
+
"conversation_id": root.conversation_id,
|
|
343
|
+
"status": "ERROR",
|
|
344
|
+
"response": "",
|
|
345
|
+
"error": err_msg,
|
|
346
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
347
|
+
"num_turns": cumulative_turns,
|
|
348
|
+
},
|
|
349
|
+
},
|
|
350
|
+
)
|
|
351
|
+
return 1
|
|
352
|
+
|
|
353
|
+
if not isinstance(obj, dict) or "event" not in obj:
|
|
354
|
+
err_msg = 'stream input message is missing the "event" field'
|
|
355
|
+
stderr.write(f"error: {err_msg}\n")
|
|
356
|
+
stderr.flush()
|
|
357
|
+
_write_ndjson(
|
|
358
|
+
stdout,
|
|
359
|
+
{
|
|
360
|
+
"event": "result",
|
|
361
|
+
"result": {
|
|
362
|
+
"conversation_id": root.conversation_id,
|
|
363
|
+
"status": "ERROR",
|
|
364
|
+
"response": "",
|
|
365
|
+
"error": err_msg,
|
|
366
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
367
|
+
"num_turns": cumulative_turns,
|
|
368
|
+
},
|
|
369
|
+
},
|
|
370
|
+
)
|
|
371
|
+
return 1
|
|
372
|
+
|
|
373
|
+
ev_type = obj.get("event")
|
|
374
|
+
if ev_type != "user":
|
|
375
|
+
stderr.write(
|
|
376
|
+
f"warning: ignoring unsupported stream input message event {ev_type!r}\n"
|
|
377
|
+
)
|
|
378
|
+
stderr.flush()
|
|
379
|
+
continue
|
|
380
|
+
|
|
381
|
+
msg_field = obj.get("message")
|
|
382
|
+
if not isinstance(msg_field, dict) or not isinstance(
|
|
383
|
+
msg_field.get("content"), str
|
|
384
|
+
):
|
|
385
|
+
err_msg = 'stream input "user" message is missing the "message" field'
|
|
386
|
+
stderr.write(f"error: {err_msg}\n")
|
|
387
|
+
stderr.flush()
|
|
388
|
+
_write_ndjson(
|
|
389
|
+
stdout,
|
|
390
|
+
{
|
|
391
|
+
"event": "result",
|
|
392
|
+
"result": {
|
|
393
|
+
"conversation_id": root.conversation_id,
|
|
394
|
+
"status": "ERROR",
|
|
395
|
+
"response": "",
|
|
396
|
+
"error": err_msg,
|
|
397
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
398
|
+
"num_turns": cumulative_turns,
|
|
399
|
+
},
|
|
400
|
+
},
|
|
401
|
+
)
|
|
402
|
+
return 1
|
|
403
|
+
|
|
404
|
+
try:
|
|
405
|
+
summary = await root.run_user_prompt(
|
|
406
|
+
msg_field["content"],
|
|
407
|
+
wait_background=True,
|
|
408
|
+
timeout_seconds=timeout_seconds,
|
|
409
|
+
)
|
|
410
|
+
except Exception as exc:
|
|
411
|
+
err_msg = str(exc)
|
|
412
|
+
stderr.write(f"error: {err_msg}\n")
|
|
413
|
+
stderr.flush()
|
|
414
|
+
_write_ndjson(
|
|
415
|
+
stdout,
|
|
416
|
+
{
|
|
417
|
+
"event": "result",
|
|
418
|
+
"result": {
|
|
419
|
+
"conversation_id": root.conversation_id,
|
|
420
|
+
"status": "ERROR",
|
|
421
|
+
"response": "",
|
|
422
|
+
"error": err_msg,
|
|
423
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
424
|
+
"num_turns": cumulative_turns,
|
|
425
|
+
},
|
|
426
|
+
},
|
|
427
|
+
)
|
|
428
|
+
return 1
|
|
429
|
+
|
|
430
|
+
cumulative_turns += summary.num_turns
|
|
431
|
+
_write_ndjson(
|
|
432
|
+
stdout,
|
|
433
|
+
{
|
|
434
|
+
"event": "result",
|
|
435
|
+
"result": {
|
|
436
|
+
"conversation_id": summary.conversation_id,
|
|
437
|
+
"status": "SUCCESS",
|
|
438
|
+
"response": _format_trailing_newline(summary.final_response),
|
|
439
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
440
|
+
"num_turns": cumulative_turns,
|
|
441
|
+
"usage": dict(root._usage_totals),
|
|
442
|
+
},
|
|
443
|
+
},
|
|
444
|
+
)
|
|
445
|
+
return 0
|
|
446
|
+
|
|
447
|
+
assert prompt_text is not None
|
|
448
|
+
try:
|
|
449
|
+
summary = await root.run_user_prompt(
|
|
450
|
+
prompt_text,
|
|
451
|
+
wait_background=True,
|
|
452
|
+
timeout_seconds=timeout_seconds,
|
|
453
|
+
)
|
|
454
|
+
except Exception as exc:
|
|
455
|
+
err_msg = str(exc)
|
|
456
|
+
if output_format == "json":
|
|
457
|
+
stdout.write(
|
|
458
|
+
json.dumps(
|
|
459
|
+
{
|
|
460
|
+
"conversation_id": root.conversation_id,
|
|
461
|
+
"status": "ERROR",
|
|
462
|
+
"response": "",
|
|
463
|
+
"error": err_msg,
|
|
464
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
465
|
+
"num_turns": 0,
|
|
466
|
+
},
|
|
467
|
+
ensure_ascii=False,
|
|
468
|
+
)
|
|
469
|
+
+ "\n"
|
|
470
|
+
)
|
|
471
|
+
stdout.flush()
|
|
472
|
+
elif output_format == "stream-json":
|
|
473
|
+
_write_ndjson(
|
|
474
|
+
stdout,
|
|
475
|
+
{
|
|
476
|
+
"event": "result",
|
|
477
|
+
"result": {
|
|
478
|
+
"conversation_id": root.conversation_id,
|
|
479
|
+
"status": "ERROR",
|
|
480
|
+
"response": "",
|
|
481
|
+
"error": err_msg,
|
|
482
|
+
"duration_seconds": time.monotonic() - session_start,
|
|
483
|
+
"num_turns": 0,
|
|
484
|
+
},
|
|
485
|
+
},
|
|
486
|
+
)
|
|
487
|
+
else:
|
|
488
|
+
stderr.write(f"Error: {err_msg}\n")
|
|
489
|
+
stderr.flush()
|
|
490
|
+
return 1
|
|
491
|
+
|
|
492
|
+
formatted_resp = _format_trailing_newline(summary.final_response)
|
|
493
|
+
if output_format == "text":
|
|
494
|
+
if formatted_resp:
|
|
495
|
+
stdout.write(formatted_resp)
|
|
496
|
+
stdout.flush()
|
|
497
|
+
elif output_format == "json":
|
|
498
|
+
stdout.write(
|
|
499
|
+
json.dumps(
|
|
500
|
+
{
|
|
501
|
+
"conversation_id": summary.conversation_id,
|
|
502
|
+
"status": "SUCCESS",
|
|
503
|
+
"response": formatted_resp,
|
|
504
|
+
"duration_seconds": summary.duration_seconds,
|
|
505
|
+
"num_turns": summary.num_turns,
|
|
506
|
+
"usage": summary.usage,
|
|
507
|
+
},
|
|
508
|
+
ensure_ascii=False,
|
|
509
|
+
)
|
|
510
|
+
+ "\n"
|
|
511
|
+
)
|
|
512
|
+
stdout.flush()
|
|
513
|
+
elif output_format == "stream-json":
|
|
514
|
+
_write_ndjson(
|
|
515
|
+
stdout,
|
|
516
|
+
{
|
|
517
|
+
"event": "result",
|
|
518
|
+
"result": {
|
|
519
|
+
"conversation_id": summary.conversation_id,
|
|
520
|
+
"status": "SUCCESS",
|
|
521
|
+
"response": formatted_resp,
|
|
522
|
+
"duration_seconds": summary.duration_seconds,
|
|
523
|
+
"num_turns": summary.num_turns,
|
|
524
|
+
"usage": summary.usage,
|
|
525
|
+
},
|
|
526
|
+
},
|
|
527
|
+
)
|
|
528
|
+
return 0
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
async def _run_interactive_repl_async(
|
|
532
|
+
session: "AgyBootstrappedSession",
|
|
533
|
+
initial_prompt: "typing.Optional[str]",
|
|
534
|
+
stdin: "typing.TextIO",
|
|
535
|
+
stdout: "typing.TextIO",
|
|
536
|
+
stderr: "typing.TextIO",
|
|
537
|
+
) -> "int":
|
|
538
|
+
root = session.root_node
|
|
539
|
+
|
|
540
|
+
def _on_event(event: "Event") -> "None":
|
|
541
|
+
if isinstance(event, ToolStartedEvent):
|
|
542
|
+
stdout.write(f" [tool] {event.call.name}\n")
|
|
543
|
+
stdout.flush()
|
|
544
|
+
elif isinstance(event, TurnFailedEvent):
|
|
545
|
+
stderr.write(f"[turn failed] {event.error_type}: {event.error}\n")
|
|
546
|
+
stderr.flush()
|
|
547
|
+
|
|
548
|
+
root.add_event_listener(_on_event)
|
|
549
|
+
await root.start()
|
|
550
|
+
|
|
551
|
+
if initial_prompt is not None and initial_prompt.strip():
|
|
552
|
+
summary = await root.run_user_prompt(initial_prompt, wait_background=True)
|
|
553
|
+
if summary.final_response:
|
|
554
|
+
stdout.write(_format_trailing_newline(summary.final_response))
|
|
555
|
+
stdout.flush()
|
|
556
|
+
|
|
557
|
+
loop = asyncio.get_running_loop()
|
|
558
|
+
while True:
|
|
559
|
+
stdout.write("agy> ")
|
|
560
|
+
stdout.flush()
|
|
561
|
+
raw_line = await loop.run_in_executor(None, stdin.readline)
|
|
562
|
+
if not raw_line:
|
|
563
|
+
stdout.write("\n")
|
|
564
|
+
stdout.flush()
|
|
565
|
+
break
|
|
566
|
+
line = raw_line.strip()
|
|
567
|
+
if not line:
|
|
568
|
+
continue
|
|
569
|
+
if line in ("/exit", "/quit"):
|
|
570
|
+
break
|
|
571
|
+
if line == "/help":
|
|
572
|
+
stdout.write(
|
|
573
|
+
"Commands:\n"
|
|
574
|
+
" /model [slug] Show or switch current model\n"
|
|
575
|
+
" /effort <level> Set reasoning effort (low|medium|high|xhigh|max)\n"
|
|
576
|
+
" /compact [msg] Compact conversation history (with optional follow-up)\n"
|
|
577
|
+
" /status Show active conversation & model status\n"
|
|
578
|
+
" /exit, /quit Exit interactive session\n"
|
|
579
|
+
)
|
|
580
|
+
stdout.flush()
|
|
581
|
+
continue
|
|
582
|
+
if line == "/compact" or (line.startswith("/compact") and line[8:9].isspace()):
|
|
583
|
+
if not root.agent.history:
|
|
584
|
+
stdout.write("Nothing to compact yet.\n")
|
|
585
|
+
stdout.flush()
|
|
586
|
+
continue
|
|
587
|
+
summary = await root.run_user_prompt(line, wait_background=True)
|
|
588
|
+
if summary.final_response:
|
|
589
|
+
stdout.write(_format_trailing_newline(summary.final_response))
|
|
590
|
+
else:
|
|
591
|
+
stdout.write("Conversation compacted.\n")
|
|
592
|
+
stdout.flush()
|
|
593
|
+
continue
|
|
594
|
+
if line == "/status":
|
|
595
|
+
stdout.write(
|
|
596
|
+
f"Conversation ID: {root.conversation_id}\n"
|
|
597
|
+
f"Model: {root.agent.model_name}\n"
|
|
598
|
+
f"Effort: {root.explicit_effort or root.config_effort or 'default'}\n"
|
|
599
|
+
f"Workspace: {root.cwd}\n"
|
|
600
|
+
)
|
|
601
|
+
stdout.flush()
|
|
602
|
+
continue
|
|
603
|
+
if line == "/model" or line.startswith("/model "):
|
|
604
|
+
arg = line[6:].strip()
|
|
605
|
+
if not arg:
|
|
606
|
+
stdout.write(f"Current model: {root.agent.model_name}\nAvailable models:\n")
|
|
607
|
+
for slug, display_name in OFFICIAL_MODELS:
|
|
608
|
+
stdout.write(f" {slug}\t{display_name}\n")
|
|
609
|
+
else:
|
|
610
|
+
root.set_model(arg)
|
|
611
|
+
stdout.write(f"Model set to {arg}\n")
|
|
612
|
+
stdout.flush()
|
|
613
|
+
continue
|
|
614
|
+
if line == "/effort" or line.startswith("/effort "):
|
|
615
|
+
arg = line[7:].strip()
|
|
616
|
+
if not arg:
|
|
617
|
+
stdout.write(
|
|
618
|
+
f"Current effort: {root.explicit_effort or root.config_effort or 'default'}\n"
|
|
619
|
+
)
|
|
620
|
+
stdout.flush()
|
|
621
|
+
continue
|
|
622
|
+
try:
|
|
623
|
+
normalized = normalize_effort_level(arg)
|
|
624
|
+
except ValueError as exc:
|
|
625
|
+
stderr.write(f"Error: {exc}\n")
|
|
626
|
+
stderr.flush()
|
|
627
|
+
continue
|
|
628
|
+
root.set_model(root.agent.model_name, explicit_effort=normalized)
|
|
629
|
+
stdout.write(f"Reasoning effort set to {normalized}\n")
|
|
630
|
+
stdout.flush()
|
|
631
|
+
continue
|
|
632
|
+
|
|
633
|
+
summary = await root.run_user_prompt(line, wait_background=True)
|
|
634
|
+
if summary.final_response:
|
|
635
|
+
stdout.write(_format_trailing_newline(summary.final_response))
|
|
636
|
+
stdout.flush()
|
|
637
|
+
|
|
638
|
+
return 0
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
async def _execute_session_async(
|
|
642
|
+
args: "argparse.Namespace",
|
|
643
|
+
is_print_mode: "bool",
|
|
644
|
+
resolved_prompt: "typing.Optional[str]",
|
|
645
|
+
timeout_seconds: "typing.Optional[float]",
|
|
646
|
+
cwd: "Path",
|
|
647
|
+
stdin: "typing.TextIO",
|
|
648
|
+
stdout: "typing.TextIO",
|
|
649
|
+
stderr: "typing.TextIO",
|
|
650
|
+
) -> "int":
|
|
651
|
+
app_data_dir = (
|
|
652
|
+
Path(args.app_data_dir).expanduser() if args.app_data_dir is not None else None
|
|
653
|
+
)
|
|
654
|
+
additional_ws = [Path(d).expanduser().resolve() for d in (args.add_dirs or [])]
|
|
655
|
+
req_timeout = (
|
|
656
|
+
max(30.0, timeout_seconds + 5.0) if timeout_seconds is not None else 300.0
|
|
657
|
+
)
|
|
658
|
+
session = build_agy_session(
|
|
659
|
+
config_path=Path(args.config).expanduser(),
|
|
660
|
+
profile=args.profile,
|
|
661
|
+
cwd=cwd,
|
|
662
|
+
model_override=args.model,
|
|
663
|
+
explicit_effort=args.effort,
|
|
664
|
+
app_data_dir=app_data_dir,
|
|
665
|
+
additional_workspaces=additional_ws,
|
|
666
|
+
continue_latest=bool(args.continue_latest),
|
|
667
|
+
resume_conversation_id=args.conversation_id,
|
|
668
|
+
timeout_seconds=req_timeout,
|
|
669
|
+
)
|
|
670
|
+
try:
|
|
671
|
+
if is_print_mode:
|
|
672
|
+
return await _run_print_mode_async(
|
|
673
|
+
session=session,
|
|
674
|
+
input_format=args.input_format,
|
|
675
|
+
output_format=args.output_format,
|
|
676
|
+
prompt_text=resolved_prompt,
|
|
677
|
+
timeout_seconds=timeout_seconds,
|
|
678
|
+
stdin=stdin,
|
|
679
|
+
stdout=stdout,
|
|
680
|
+
stderr=stderr,
|
|
681
|
+
)
|
|
682
|
+
init_prompt = (
|
|
683
|
+
args.interactive_prompt
|
|
684
|
+
if args.interactive_prompt is not None and args.interactive_prompt != ""
|
|
685
|
+
else resolved_prompt
|
|
686
|
+
)
|
|
687
|
+
return await _run_interactive_repl_async(
|
|
688
|
+
session=session,
|
|
689
|
+
initial_prompt=init_prompt,
|
|
690
|
+
stdin=stdin,
|
|
691
|
+
stdout=stdout,
|
|
692
|
+
stderr=stderr,
|
|
693
|
+
)
|
|
694
|
+
finally:
|
|
695
|
+
await session.close()
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def main(
|
|
699
|
+
argv: "typing.Optional[typing.Sequence[str]]" = None,
|
|
700
|
+
stdin: "typing.Optional[typing.TextIO]" = None,
|
|
701
|
+
stdout: "typing.Optional[typing.TextIO]" = None,
|
|
702
|
+
stderr: "typing.Optional[typing.TextIO]" = None,
|
|
703
|
+
cwd: "typing.Optional[Path]" = None,
|
|
704
|
+
) -> "int":
|
|
705
|
+
raw_args = list(sys.argv[1:] if argv is None else argv)
|
|
706
|
+
in_stream = sys.stdin if stdin is None else stdin
|
|
707
|
+
out_stream = sys.stdout if stdout is None else stdout
|
|
708
|
+
err_stream = sys.stderr if stderr is None else stderr
|
|
709
|
+
effective_cwd = (cwd if cwd is not None else Path.cwd()).resolve()
|
|
710
|
+
|
|
711
|
+
if raw_args in (["-v"], ["--version"]):
|
|
712
|
+
out_stream.write(f"{__version__} (agy 1.5.14 wire-compatible)\n")
|
|
713
|
+
out_stream.flush()
|
|
714
|
+
return 0
|
|
715
|
+
if raw_args:
|
|
716
|
+
first = raw_args[0]
|
|
717
|
+
if first == "models":
|
|
718
|
+
return _run_models_subcommand(raw_args[1:], out_stream)
|
|
719
|
+
if first in ("agent", "agents"):
|
|
720
|
+
return _run_agents_subcommand(raw_args[1:], out_stream)
|
|
721
|
+
if first == "help":
|
|
722
|
+
if len(raw_args) > 1 and raw_args[1] == "models":
|
|
723
|
+
return _run_models_subcommand(["--help"], out_stream)
|
|
724
|
+
if len(raw_args) > 1 and raw_args[1] in ("agent", "agents"):
|
|
725
|
+
return _run_agents_subcommand(["--help"], out_stream)
|
|
726
|
+
build_cli_parser().print_help(file=out_stream)
|
|
727
|
+
return 0
|
|
728
|
+
|
|
729
|
+
parser = build_cli_parser()
|
|
730
|
+
args = parser.parse_args(raw_args)
|
|
731
|
+
|
|
732
|
+
if args.input_format == "stream-json" and args.output_format != "stream-json":
|
|
733
|
+
err_stream.write(
|
|
734
|
+
"Error: --input-format stream-json requires --output-format stream-json\n"
|
|
735
|
+
)
|
|
736
|
+
err_stream.flush()
|
|
737
|
+
return 2
|
|
738
|
+
|
|
739
|
+
try:
|
|
740
|
+
timeout_seconds = parse_duration_seconds(args.print_timeout)
|
|
741
|
+
if args.effort is not None:
|
|
742
|
+
normalize_effort_level(args.effort)
|
|
743
|
+
except ValueError as exc:
|
|
744
|
+
err_stream.write(f"Error: {exc}\n")
|
|
745
|
+
err_stream.flush()
|
|
746
|
+
return 2
|
|
747
|
+
|
|
748
|
+
is_print_mode = (
|
|
749
|
+
args.print_prompt is not None or args.input_format == "stream-json"
|
|
750
|
+
)
|
|
751
|
+
|
|
752
|
+
resolved_prompt: "typing.Optional[str]" = None
|
|
753
|
+
if is_print_mode and args.input_format == "text":
|
|
754
|
+
if args.print_prompt is not None and args.print_prompt != "":
|
|
755
|
+
resolved_prompt = args.print_prompt
|
|
756
|
+
elif args.prompt is not None and args.prompt != "":
|
|
757
|
+
resolved_prompt = args.prompt
|
|
758
|
+
else:
|
|
759
|
+
is_tty = bool(getattr(in_stream, "isatty", lambda: False)())
|
|
760
|
+
if not is_tty:
|
|
761
|
+
piped = in_stream.read()
|
|
762
|
+
if piped.strip():
|
|
763
|
+
resolved_prompt = piped.rstrip("\r\n")
|
|
764
|
+
if resolved_prompt is None or not resolved_prompt.strip():
|
|
765
|
+
err_stream.write(
|
|
766
|
+
'Error: empty prompt. Usage: pyagy --print "your prompt here"\n'
|
|
767
|
+
)
|
|
768
|
+
err_stream.flush()
|
|
769
|
+
return 2
|
|
770
|
+
elif not is_print_mode:
|
|
771
|
+
resolved_prompt = args.prompt
|
|
772
|
+
|
|
773
|
+
try:
|
|
774
|
+
return asyncio.run(
|
|
775
|
+
_execute_session_async(
|
|
776
|
+
args=args,
|
|
777
|
+
is_print_mode=is_print_mode,
|
|
778
|
+
resolved_prompt=resolved_prompt,
|
|
779
|
+
timeout_seconds=timeout_seconds,
|
|
780
|
+
cwd=effective_cwd,
|
|
781
|
+
stdin=in_stream,
|
|
782
|
+
stdout=out_stream,
|
|
783
|
+
stderr=err_stream,
|
|
784
|
+
)
|
|
785
|
+
)
|
|
786
|
+
except Exception as exc:
|
|
787
|
+
err_stream.write(f"Error: {exc}\n")
|
|
788
|
+
err_stream.flush()
|
|
789
|
+
return 1
|