pyagy 0.7.1__tar.gz → 0.7.2__tar.gz

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.
@@ -98,10 +98,10 @@
98
98
 
99
99
  - **工具声明表**:全部 14 个工具的排列顺序、描述文本及 `parametersJsonSchema`(含 `$schema`、`additionalProperties`、`required` 等)与官方首轮请求完全一致。
100
100
  - **文件读写编辑**:`read_file`(绝对路径校验、空文件提示、行号切片、`ByteOffset` 续读、单次 800 行 / 46080 字节上限、PNG/JPEG/GIF/WebP 图片多模态读取)、`write_file`(自动建父目录、默认防覆盖、`Overwrite`/`Append` 互斥校验、Artifact 元数据落盘)、`edit_file`(全量精确替换、替换次数及起始行与增删行数统计)。
101
- - **命令执行与定时任务**:`run_command`(PTY 会话执行、`WaitMsBeforeAsync` 500~10000ms 同步等待或转后台任务、按 Gemini 4 / 3.x / 3.1 Pro 区分后台返回提示语、完成或取消后自动投递 `<SYSTEM_MESSAGE>`)、`manage_task`(`list` / `status` / `send_input` / `kill`)、`schedule`(单次倒计时支持 `TimerCondition` `never`/`any`/`<sender>` 来信早停,5 段式 Cron 支持抖动、`ExactTiming`、`IsDaemon` 与 `MaxIterations`)。`background_work_count` 包含所有仍能唤醒会话的后台命令和定时任务,打印模式只等待非守护任务。`background_work_snapshot` 省略原始命令行与提示词。
101
+ - **命令执行与定时任务**:`run_command`(POSIX 使用 PTY 会话与进程组信号清理,Windows 回退到标准管道、`CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW`、PowerShell UTF-8 `OutputEncoding` 初始化与 `taskkill /F /T` 清理进程树,并将工具描述中的运行环境切换为 `Operating System: windows`;双端统一注入 `TERM=dumb`、`PAGER=cat`、`GIT_PAGER=cat`、`JJ_PAGER=cat`、`GIT_EDITOR=false`、`HGEDITOR=false`、`JJ_EDITOR=false`、`GIT_TERMINAL_PROMPT=0`、`ANTIGRAVITY_AGENT=1`、`ANTIGRAVITY_CONVERSATION_ID` 及默认 `PYTHONUTF8=1`,在 Windows 下对环境变量名做大小写无关去重,并在主 Shell 退出而后台孙进程仍持有 PTY/管道句柄时最多等待 1 秒排空即判定命令完成,避免交互式分页器或孤儿孙进程导致永久卡死;`WaitMsBeforeAsync` 500~10000ms 同步等待或转后台任务、按 Gemini 4 / 3.x / 3.1 Pro 区分后台返回提示语、完成或取消后自动投递 `<SYSTEM_MESSAGE>`)、`manage_task`(`list` / `status` / `send_input` / `kill`)、`schedule`(单次倒计时支持 `TimerCondition` `never`/`any`/`<sender>` 来信早停,5 段式 Cron 支持抖动、`ExactTiming`、`IsDaemon` 与 `MaxIterations`)。`background_work_count` 包含所有仍能唤醒会话的后台命令和定时任务,打印模式只等待非守护任务。`background_work_snapshot` 省略原始命令行与提示词。
102
102
  - **工具输出 10 KiB 中间截断与步骤文件落盘**:同步 `run_command`、后台 `run_command` 完成时的 `<SYSTEM_MESSAGE>` 结果正文,以及其余非 `read_file` 纯文本工具输出超过 `10,240` UTF-8 字节时,统一按官方格式保留首尾合法 UTF-8 切片与 `\n<truncated X of Y bytes from the middle of the output>\n` 标记,并将完整原始输出写入 `.system_generated/steps/<step_index>/output.txt`(同步与后台完成的 `run_command` 始终落盘步骤输出文件,`read_file` 保持独立的 800 行 / 46,080 字节限制)。
103
103
  - **本地恢复扩展**:按会话保存待触发的 `schedule`。恢复时沿用任务 ID、下一次截止时间、取消条件及已触发次数。已过期的 cron 补发一次后按原表达式继续;已取消和完成的任务在关闭前即移除恢复记录。
104
- - **子 Agent 与跨会话通信**:`define_subagent`(自定义蓝图与写/子 Agent 工具开关)、`invoke_subagent`(支持 `self` / `research` / `image-generator` 及自定义类型、`Workspace` 支持 `inherit` / `branch` 目录克隆 / `share` Git worktree 隔离、按类型构造专属系统提示词与 `<subagent_reminder>`)、`send_message`(父子及同级双向消息投递与唤醒、已主动汇报时抑制重复空闲通知)、`manage_subagents`(直属子 Agent 列表及递归终止清理派生工作区);运行中的直属子 Agent 同步通过 `AgySubagentWorkTracker` 纳入父会话 `background_work_count` 与 `background_work_snapshot`。
104
+ - **子 Agent 与跨会话通信**:`define_subagent`(自定义蓝图与写/子 Agent 工具开关)、`invoke_subagent`(支持 `self` / `research` / `image-generator` 及自定义类型、`Workspace` 支持 `inherit` / `branch` 目录克隆 / `share` Git worktree 隔离、按类型构造专属系统提示词与 `<subagent_reminder>`)、`send_message`(父子及同级双向消息投递与唤醒、正常完成且已主动汇报时抑制重复空闲通知;若子 Agent 轮次异常失败或中断,或等待后台任务/孙 Agent 清零后进入空闲,均确保唤醒父会话)、`manage_subagents`(直属子 Agent 列表及递归终止清理派生工作区);运行中的直属子 Agent 同步通过 `AgySubagentWorkTracker` 纳入父会话 `background_work_count` 与 `background_work_snapshot`。
105
105
 
106
106
  ### 2.6 上下文压缩、会话恢复与 CLI 模式
107
107
 
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyagy
3
- Version: 0.7.1
3
+ Version: 0.7.2
4
4
  Summary: Antigravity CLI (agy 1.5.14) wire-compatible harness built on python-codex
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.7
7
- Requires-Dist: python-codex==0.7.1
7
+ Requires-Dist: python-codex==0.7.2
8
8
  Description-Content-Type: text/markdown
9
9
 
10
10
  # pyagy
@@ -5,4 +5,4 @@ from pycodex.utils.compat import importlib_metadata
5
5
  try:
6
6
  __version__ = importlib_metadata.version("pyagy")
7
7
  except importlib_metadata.PackageNotFoundError: # pragma: no cover - uninstalled checkout
8
- __version__ = "0.7.1"
8
+ __version__ = "0.7.2"
@@ -4,10 +4,13 @@ import asyncio
4
4
  from dataclasses import dataclass, replace
5
5
  from datetime import datetime
6
6
  import json
7
+ import os
7
8
  from pathlib import Path
8
9
  import re
9
10
  import shutil
11
+ import stat
10
12
  import subprocess
13
+ import sys
11
14
  import time
12
15
  import typing
13
16
  import uuid
@@ -28,6 +31,7 @@ from pycodex.events import (
28
31
  TurnFailedEvent,
29
32
  TurnInputReadyEvent,
30
33
  TurnInterrupted,
34
+ TurnInterruptedEvent,
31
35
  )
32
36
  from pycodex.model import ContextLengthExceeded
33
37
  from pycodex.multi_agents import AgentsManager
@@ -68,7 +72,7 @@ from .prompts.system_prompt import (
68
72
  build_subagent_system_instruction,
69
73
  find_git_repo_root,
70
74
  )
71
- from .task_manager import AgyTaskManager
75
+ from .task_manager import AgyTaskManager, build_agy_command_env
72
76
  from .tools import (
73
77
  IMAGE_GENERATOR_SUBAGENT_TOOLS,
74
78
  RESEARCH_SUBAGENT_TOOLS,
@@ -126,6 +130,32 @@ class AgyAgentsManager(AgentsManager):
126
130
  self.notify_parents(agent_id)
127
131
 
128
132
 
133
+ def _git_subprocess_kwargs() -> "typing.Dict[str, typing.Any]":
134
+ kwargs: "typing.Dict[str, typing.Any]" = {
135
+ "capture_output": True,
136
+ "env": build_agy_command_env(),
137
+ }
138
+ if os.name == "nt":
139
+ no_win = getattr(subprocess, "CREATE_NO_WINDOW", 0)
140
+ if no_win:
141
+ kwargs["creationflags"] = no_win
142
+ return kwargs
143
+
144
+
145
+ def _rmtree_force(path: "Path") -> "None":
146
+ def _clear_readonly(func: "typing.Any", target: "str", _exc: "typing.Any") -> "None":
147
+ try:
148
+ os.chmod(target, stat.S_IWRITE)
149
+ func(target)
150
+ except OSError:
151
+ pass
152
+
153
+ if sys.version_info >= (3, 12):
154
+ shutil.rmtree(path, onexc=_clear_readonly)
155
+ else:
156
+ shutil.rmtree(path, onerror=_clear_readonly)
157
+
158
+
129
159
  def _truncate_oversized_history_for_compaction(
130
160
  items: "typing.Sequence[ConversationItem]",
131
161
  ) -> "typing.Tuple[typing.List[ConversationItem], int]":
@@ -700,6 +730,7 @@ class AgySessionNode:
700
730
  self._activity_event: "typing.Optional[asyncio.Event]" = None
701
731
  self._turn_outputs: "typing.List[str]" = []
702
732
  self._last_turn_output = ""
733
+ self._last_turn_failed = False
703
734
  self._pending_idle_notify = False
704
735
  self._reported_to_parent = False
705
736
  self._completed_turns = 0
@@ -822,6 +853,26 @@ class AgySessionNode:
822
853
  if self._activity_event is not None:
823
854
  self._activity_event.set()
824
855
 
856
+ def _maybe_finalize_idle(self) -> "None":
857
+ if (
858
+ self._pending_idle_notify
859
+ and self.parent_conversation_id is not None
860
+ and self.state != "killed"
861
+ and not self.has_pending_work()
862
+ ):
863
+ self._pending_idle_notify = False
864
+ failed = self._last_turn_failed
865
+ self._last_turn_failed = False
866
+ reported = False if failed else self._reported_to_parent
867
+ self._reported_to_parent = False
868
+ self.state = "idle"
869
+ self.controller.notify_parent_subagent_idle(
870
+ self,
871
+ self._last_turn_output,
872
+ already_reported=reported,
873
+ )
874
+ self.controller.notify_parent_subagent_work(self.parent_conversation_id)
875
+
825
876
  def _on_runtime_event(self, event: "Event") -> "None":
826
877
  if isinstance(event, MessagesAddedEvent):
827
878
  for msg in event.messages:
@@ -867,32 +918,26 @@ class AgySessionNode:
867
918
  self._last_turn_output = out_txt
868
919
  if out_txt:
869
920
  self._turn_outputs.append(out_txt)
921
+ self._last_turn_failed = False
870
922
  self._pending_idle_notify = True
871
923
  self.save_session_state()
872
924
  self._signal_activity()
873
925
  elif isinstance(event, TurnFailedEvent):
874
926
  self._last_turn_output = f"{event.error_type}: {event.error}"
927
+ self._last_turn_failed = True
875
928
  self._pending_idle_notify = True
876
929
  self.save_session_state()
877
930
  self._signal_activity()
878
- elif isinstance(event, RuntimeUpdatedEvent) and event.reason == "idle":
931
+ elif isinstance(event, TurnInterruptedEvent):
932
+ self._last_turn_output = event.output_text or "Turn interrupted."
933
+ self._last_turn_failed = True
934
+ self._pending_idle_notify = True
935
+ self.save_session_state()
879
936
  self._signal_activity()
880
- if (
881
- self._pending_idle_notify
882
- and self.parent_conversation_id is not None
883
- and self.state != "killed"
884
- and not self.has_pending_work()
885
- ):
886
- self._pending_idle_notify = False
887
- reported = self._reported_to_parent
888
- self._reported_to_parent = False
889
- self.state = "idle"
890
- self.controller.notify_parent_subagent_idle(
891
- self,
892
- self._last_turn_output,
893
- already_reported=reported,
894
- )
895
- self.controller.notify_parent_subagent_work(self.parent_conversation_id)
937
+ elif isinstance(event, RuntimeUpdatedEvent):
938
+ if event.reason in ("idle", "background_work", "queue", "interrupt"):
939
+ self._signal_activity()
940
+ self._maybe_finalize_idle()
896
941
 
897
942
  for listener in tuple(self._event_listeners):
898
943
  listener(event)
@@ -936,6 +981,9 @@ class AgySessionNode:
936
981
  if waking:
937
982
  self.state = "running"
938
983
  self._reported_to_parent = False
984
+ self._last_turn_failed = False
985
+ if wake_if_idle:
986
+ self._pending_idle_notify = False
939
987
  self.runtime.message(sys_msg)
940
988
  if wake_if_idle:
941
989
  self.runtime.trigger()
@@ -973,22 +1021,8 @@ class AgySessionNode:
973
1021
  await asyncio.wait_for(self._activity_event.wait(), timeout=wait_slice)
974
1022
  except asyncio.TimeoutError:
975
1023
  pass
976
- if (
977
- self._pending_idle_notify
978
- and self.parent_conversation_id is not None
979
- and self.state != "killed"
980
- and not self.has_pending_work()
981
- ):
982
- self._pending_idle_notify = False
983
- reported = self._reported_to_parent
984
- self._reported_to_parent = False
985
- self.state = "idle"
986
- self.controller.notify_parent_subagent_idle(
987
- self,
988
- self._last_turn_output,
989
- already_reported=reported,
990
- )
991
- self.controller.notify_parent_subagent_work(self.parent_conversation_id)
1024
+ self._maybe_finalize_idle()
1025
+ self._maybe_finalize_idle()
992
1026
 
993
1027
  async def run_user_prompt(
994
1028
  self,
@@ -1056,19 +1090,23 @@ class AgySessionNode:
1056
1090
  await self.task_manager.close()
1057
1091
  if delete_workspace and self._owned_workspace_dir is not None:
1058
1092
  if self._git_worktree_repo is not None:
1059
- subprocess.run(
1060
- [
1061
- "git",
1062
- "-C",
1063
- str(self._git_worktree_repo),
1064
- "worktree",
1065
- "remove",
1066
- "--force",
1067
- str(self._owned_workspace_dir),
1068
- ],
1069
- capture_output=True,
1070
- )
1071
- shutil.rmtree(self._owned_workspace_dir, ignore_errors=True)
1093
+ try:
1094
+ subprocess.run(
1095
+ [
1096
+ "git",
1097
+ "-C",
1098
+ str(self._git_worktree_repo),
1099
+ "worktree",
1100
+ "remove",
1101
+ "--force",
1102
+ str(self._owned_workspace_dir),
1103
+ ],
1104
+ timeout=10.0,
1105
+ **_git_subprocess_kwargs(),
1106
+ )
1107
+ except (OSError, subprocess.TimeoutExpired):
1108
+ pass
1109
+ _rmtree_force(self._owned_workspace_dir)
1072
1110
 
1073
1111
 
1074
1112
  class AgyMultiAgentController:
@@ -1174,12 +1212,16 @@ class AgyMultiAgentController:
1174
1212
  has_git = (repo_root / ".git").exists()
1175
1213
 
1176
1214
  if mode == "share" and has_git:
1177
- proc = subprocess.run(
1178
- ["git", "-C", str(repo_root), "worktree", "add", "--detach", str(target_ws)],
1179
- capture_output=True,
1180
- text=True,
1181
- )
1182
- if proc.returncode == 0:
1215
+ try:
1216
+ proc = subprocess.run(
1217
+ ["git", "-C", str(repo_root), "worktree", "add", "--detach", str(target_ws)],
1218
+ text=True,
1219
+ timeout=15.0,
1220
+ **_git_subprocess_kwargs(),
1221
+ )
1222
+ except (OSError, subprocess.TimeoutExpired):
1223
+ proc = None
1224
+ if proc is not None and proc.returncode == 0:
1183
1225
  rel = parent_cwd.relative_to(repo_root)
1184
1226
  effective_cwd = (target_ws / rel).resolve()
1185
1227
  return effective_cwd, target_ws, repo_root
@@ -1187,7 +1229,7 @@ class AgyMultiAgentController:
1187
1229
  shutil.copytree(
1188
1230
  parent_cwd,
1189
1231
  target_ws,
1190
- symlinks=True,
1232
+ symlinks=(os.name != "nt"),
1191
1233
  ignore=shutil.ignore_patterns(".git") if mode == "branch" and not has_git else None,
1192
1234
  )
1193
1235
  return target_ws.resolve(), target_ws.resolve(), None
@@ -1,22 +1,30 @@
1
- """Background command and schedule task manager matching agy 1.5.13."""
1
+ """Background command and schedule task manager matching agy 1.5.14."""
2
2
 
3
3
  import asyncio
4
4
  from dataclasses import asdict, dataclass
5
5
  from datetime import datetime, timedelta
6
- import errno
7
6
  import json
8
7
  import os
9
- from pathlib import Path
10
- import pty
8
+ from pathlib import Path, PureWindowsPath
11
9
  import random
10
+ import selectors
11
+ import shutil
12
12
  import signal
13
13
  import subprocess
14
14
  import tempfile
15
15
  import threading
16
- from time import time
16
+ from time import monotonic, time
17
17
  import typing
18
18
 
19
- from .context import format_single_system_message, format_utc_iso
19
+ if os.name != "nt":
20
+ try:
21
+ import pty
22
+ except ImportError: # pragma: no cover
23
+ pty = None # type: ignore[assignment]
24
+ else:
25
+ pty = None # type: ignore[assignment]
26
+
27
+ from .context import format_utc_iso
20
28
  from .transcript import truncate_agy_tool_output
21
29
 
22
30
  if typing.TYPE_CHECKING:
@@ -25,6 +33,77 @@ if typing.TYPE_CHECKING:
25
33
 
26
34
  NotifyCallback = typing.Callable[..., typing.Optional[bool]]
27
35
 
36
+ _POST_EXIT_IDLE_DRAIN_SECONDS = 0.2
37
+ _POST_EXIT_MAX_DRAIN_SECONDS = 1.0
38
+
39
+ _POWERSHELL_UTF8_PRELUDE = (
40
+ "try { $OutputEncoding = [System.Text.UTF8Encoding]::new($false); "
41
+ "[Console]::OutputEncoding = $OutputEncoding } catch {}; "
42
+ )
43
+
44
+ _FORCED_COMMAND_ENV: "typing.Tuple[typing.Tuple[str, str], ...]" = (
45
+ ("TERM", "dumb"),
46
+ ("PAGER", "cat"),
47
+ ("GIT_PAGER", "cat"),
48
+ ("JJ_PAGER", "cat"),
49
+ ("GIT_EDITOR", "false"),
50
+ ("HGEDITOR", "false"),
51
+ ("JJ_EDITOR", "false"),
52
+ ("GIT_TERMINAL_PROMPT", "0"),
53
+ ("ANTIGRAVITY_AGENT", "1"),
54
+ )
55
+
56
+ _DEFAULT_COMMAND_ENV: "typing.Tuple[typing.Tuple[str, str], ...]" = (
57
+ ("PYTHONUTF8", "1"),
58
+ )
59
+
60
+
61
+ def build_agy_command_env(
62
+ base_env: "typing.Optional[typing.Mapping[str, str]]" = None,
63
+ conversation_id: "str" = "",
64
+ is_windows: "typing.Optional[bool]" = None,
65
+ ) -> "typing.Dict[str, str]":
66
+ """Build non-interactive, UTF-8-safe child environment matching official agy."""
67
+ source = os.environ if base_env is None else base_env
68
+ win_mode = (os.name == "nt") if is_windows is None else bool(is_windows)
69
+ if not win_mode:
70
+ env = {str(k): str(v) for k, v in source.items()}
71
+ for key, val in _DEFAULT_COMMAND_ENV:
72
+ env.setdefault(key, val)
73
+ for key, val in _FORCED_COMMAND_ENV:
74
+ env[key] = val
75
+ if conversation_id:
76
+ env["ANTIGRAVITY_CONVERSATION_ID"] = conversation_id
77
+ return env
78
+
79
+ env = {}
80
+ upper_to_actual: "typing.Dict[str, str]" = {}
81
+ for raw_k, raw_v in source.items():
82
+ key_str = str(raw_k)
83
+ upper_k = key_str.upper()
84
+ prev_actual = upper_to_actual.get(upper_k)
85
+ if prev_actual is not None and prev_actual != key_str:
86
+ env.pop(prev_actual, None)
87
+ env[key_str] = str(raw_v)
88
+ upper_to_actual[upper_k] = key_str
89
+
90
+ for key, val in _DEFAULT_COMMAND_ENV:
91
+ if key.upper() not in upper_to_actual:
92
+ env[key] = val
93
+ upper_to_actual[key.upper()] = key
94
+
95
+ forced_items = list(_FORCED_COMMAND_ENV)
96
+ if conversation_id:
97
+ forced_items.append(("ANTIGRAVITY_CONVERSATION_ID", conversation_id))
98
+ for key, val in forced_items:
99
+ upper_k = key.upper()
100
+ prev_actual = upper_to_actual.get(upper_k)
101
+ if prev_actual is not None and prev_actual != key:
102
+ env.pop(prev_actual, None)
103
+ env[key] = val
104
+ upper_to_actual[upper_k] = key
105
+ return env
106
+
28
107
 
29
108
  @dataclass(frozen=True)
30
109
  class ParsedCron:
@@ -216,19 +295,27 @@ class _CommandProcessHandle:
216
295
  def __init__(
217
296
  self,
218
297
  proc: "subprocess.Popen[bytes]",
219
- master_fd: "typing.Optional[int]",
220
298
  loop: "asyncio.AbstractEventLoop",
299
+ master_fd: "typing.Optional[int]" = None,
221
300
  ) -> "None":
222
301
  self.proc = proc
302
+ self._master_fd: "typing.Optional[int]" = master_fd
223
303
  self.tty: "bool" = master_fd is not None
224
- self._master_fd = master_fd
225
304
  self._loop = loop
226
305
  self._lock = threading.Lock()
227
306
  self._buffer = bytearray()
307
+ self._output_seq = 0
308
+ self._finished = False
309
+ self._stdin_closed = False
228
310
  self._log_path: "typing.Optional[Path]" = None
229
311
  self.done_event = asyncio.Event()
230
312
  self.exit_code: "typing.Optional[int]" = None
231
313
 
314
+ @property
315
+ def output_seq(self) -> "int":
316
+ with self._lock:
317
+ return self._output_seq
318
+
232
319
  def attach_log_file(self, log_path: "Path") -> "None":
233
320
  log_path.parent.mkdir(parents=True, exist_ok=True)
234
321
  with self._lock:
@@ -239,7 +326,10 @@ class _CommandProcessHandle:
239
326
  if not data:
240
327
  return
241
328
  with self._lock:
329
+ if self._finished:
330
+ return
242
331
  self._buffer.extend(data)
332
+ self._output_seq += 1
243
333
  if self._log_path is not None:
244
334
  with self._log_path.open("ab") as fh:
245
335
  fh.write(data)
@@ -251,28 +341,70 @@ class _CommandProcessHandle:
251
341
  def write_input(self, data: "str") -> "None":
252
342
  encoded = data.encode("utf-8")
253
343
  with self._lock:
344
+ if self._finished or self._stdin_closed:
345
+ raise ValueError("task stdin is already closed")
254
346
  if self._master_fd is not None:
255
- os.write(self._master_fd, encoded)
347
+ try:
348
+ os.write(self._master_fd, encoded)
349
+ except (BrokenPipeError, OSError, ValueError) as exc:
350
+ self._stdin_closed = True
351
+ raise ValueError(f"failed to write to task stdin: {exc}") from exc
256
352
  return
257
- if self.proc.stdin is not None:
353
+ if self.proc.stdin is None:
354
+ raise ValueError("task stdin is already closed")
355
+ try:
258
356
  self.proc.stdin.write(encoded)
259
357
  self.proc.stdin.flush()
260
- return
261
- raise RuntimeError("task stdin is already closed")
358
+ except (BrokenPipeError, OSError, ValueError) as exc:
359
+ self._stdin_closed = True
360
+ raise ValueError(f"failed to write to task stdin: {exc}") from exc
262
361
 
263
- def close_master(self) -> "None":
362
+ def _close_master_fd(self) -> "None":
264
363
  with self._lock:
265
- if self._master_fd is not None:
266
- fd = self._master_fd
267
- self._master_fd = None
364
+ fd = self._master_fd
365
+ self._master_fd = None
366
+ self._stdin_closed = True
367
+ if fd is not None:
368
+ try:
369
+ os.close(fd)
370
+ except OSError:
371
+ pass
372
+
373
+ def close_stdin(self) -> "None":
374
+ with self._lock:
375
+ if self._stdin_closed:
376
+ return
377
+ self._stdin_closed = True
378
+ if self._master_fd is None and self.proc.stdin is not None:
268
379
  try:
269
- os.close(fd)
270
- except OSError:
380
+ self.proc.stdin.close()
381
+ except (OSError, ValueError):
271
382
  pass
272
383
 
273
384
  def terminate_group(self) -> "None":
385
+ self.close_stdin()
274
386
  if self.proc.poll() is not None:
275
- self.close_master()
387
+ return
388
+ if os.name == "nt":
389
+ kill_kwargs: "typing.Dict[str, typing.Any]" = {
390
+ "stdout": subprocess.DEVNULL,
391
+ "stderr": subprocess.DEVNULL,
392
+ "timeout": 5.0,
393
+ }
394
+ no_win = getattr(subprocess, "CREATE_NO_WINDOW", 0)
395
+ if no_win:
396
+ kill_kwargs["creationflags"] = no_win
397
+ try:
398
+ subprocess.run(
399
+ ["taskkill", "/F", "/T", "/PID", str(self.proc.pid)],
400
+ **kill_kwargs,
401
+ )
402
+ except (OSError, subprocess.TimeoutExpired):
403
+ self.proc.kill()
404
+ try:
405
+ self.proc.wait(timeout=0.3)
406
+ except subprocess.TimeoutExpired:
407
+ self.proc.kill()
276
408
  return
277
409
  try:
278
410
  os.killpg(self.proc.pid, signal.SIGTERM)
@@ -287,11 +419,14 @@ class _CommandProcessHandle:
287
419
  os.killpg(self.proc.pid, signal.SIGKILL)
288
420
  except OSError:
289
421
  self.proc.kill()
290
- self.close_master()
291
422
 
292
423
  def mark_finished(self, code: "int") -> "None":
293
- self.exit_code = code
294
- self.close_master()
424
+ with self._lock:
425
+ if self._finished:
426
+ return
427
+ self._finished = True
428
+ self.exit_code = code
429
+ self.close_stdin()
295
430
  try:
296
431
  self._loop.call_soon_threadsafe(self.done_event.set)
297
432
  except RuntimeError:
@@ -352,6 +487,58 @@ class _Schedule:
352
487
  temporary.unlink()
353
488
 
354
489
 
490
+ def resolve_agy_shell_command(
491
+ command_line: "str",
492
+ ) -> "typing.Tuple[str, typing.List[str]]":
493
+ """Return `(shell_label, argv)` for executing `command_line` on the host OS."""
494
+ if os.name != "nt":
495
+ return "bash", ["bash", "-c", command_line]
496
+
497
+ ps_script = f"{_POWERSHELL_UTF8_PRELUDE}{command_line}" if command_line else ""
498
+ env_shell = (os.environ.get("SHELL") or "").strip()
499
+ resolved_env: "typing.Optional[str]" = None
500
+ if env_shell:
501
+ if env_shell.startswith("/"):
502
+ if os.path.isfile(env_shell):
503
+ resolved_env = env_shell
504
+ else:
505
+ resolved_env = shutil.which(PureWindowsPath(env_shell).name)
506
+ else:
507
+ resolved_env = shutil.which(env_shell) or env_shell
508
+
509
+ if resolved_env:
510
+ env_name = PureWindowsPath(resolved_env).name.lower()
511
+ if env_name in {"cmd", "cmd.exe"}:
512
+ return "cmd", [resolved_env, "/C", command_line]
513
+ if "powershell" in env_name or env_name in {"pwsh", "pwsh.exe"}:
514
+ label = "pwsh" if env_name in {"pwsh", "pwsh.exe"} else "powershell"
515
+ return label, [
516
+ resolved_env,
517
+ "-NoProfile",
518
+ "-NonInteractive",
519
+ "-Command",
520
+ ps_script,
521
+ ]
522
+ stem = env_name[:-4] if env_name.endswith(".exe") else env_name
523
+ return (stem or "bash"), [resolved_env, "-c", command_line]
524
+
525
+ for candidate in ("powershell.exe", "powershell", "pwsh.exe", "pwsh"):
526
+ found = shutil.which(candidate)
527
+ if found:
528
+ found_name = PureWindowsPath(found).name.lower()
529
+ label = "pwsh" if found_name in {"pwsh", "pwsh.exe"} else "powershell"
530
+ return label, [
531
+ found,
532
+ "-NoProfile",
533
+ "-NonInteractive",
534
+ "-Command",
535
+ ps_script,
536
+ ]
537
+
538
+ comspec = os.environ.get("COMSPEC") or "cmd.exe"
539
+ return "cmd", [comspec, "/C", command_line]
540
+
541
+
355
542
  def _next_cron_deadline(expression: str, exact_timing: bool) -> float:
356
543
  now = datetime.now().astimezone()
357
544
  target = next_cron_fire_time(parse_cron_expression(expression), now).timestamp()
@@ -407,8 +594,8 @@ class AgyTaskManager:
407
594
  for rec in list(self._tasks.values()):
408
595
  if rec.status == "RUNNING":
409
596
  rec.status = "CANCELLED"
410
- if rec.command_handle is not None:
411
- rec.command_handle.terminate_group()
597
+ if rec.command_handle is not None:
598
+ rec.command_handle.terminate_group()
412
599
  if rec.async_task is not None and not rec.async_task.done():
413
600
  rec.async_task.cancel()
414
601
  self._tasks.clear()
@@ -491,74 +678,128 @@ class AgyTaskManager:
491
678
  cwd: "Path",
492
679
  loop: "asyncio.AbstractEventLoop",
493
680
  ) -> "_CommandProcessHandle":
494
- master_fd: "typing.Optional[int]" = None
495
- slave_fd: "typing.Optional[int]" = None
496
- try:
497
- master_fd, slave_fd = pty.openpty()
498
- except OSError:
499
- master_fd, slave_fd = None, None
681
+ _, shell_argv = resolve_agy_shell_command(command_line)
682
+ child_env = build_agy_command_env(conversation_id=self.conversation_id)
683
+ reader_done = threading.Event()
684
+ stop_reader = threading.Event()
500
685
 
501
- if master_fd is not None and slave_fd is not None:
686
+ if pty is not None and os.name != "nt":
687
+ master_fd, slave_fd = pty.openpty()
502
688
  try:
503
689
  proc = subprocess.Popen(
504
- ["bash", "-c", command_line],
690
+ shell_argv,
505
691
  stdin=slave_fd,
506
692
  stdout=slave_fd,
507
693
  stderr=slave_fd,
508
694
  cwd=str(cwd),
695
+ env=child_env,
509
696
  start_new_session=True,
510
697
  close_fds=True,
511
698
  )
512
- except BaseException:
513
- os.close(master_fd)
514
- os.close(slave_fd)
699
+ except Exception:
700
+ try:
701
+ os.close(master_fd)
702
+ except OSError:
703
+ pass
515
704
  raise
516
- os.close(slave_fd)
517
- handle = _CommandProcessHandle(proc=proc, master_fd=master_fd, loop=loop)
705
+ finally:
706
+ try:
707
+ os.close(slave_fd)
708
+ except OSError:
709
+ pass
710
+
711
+ handle = _CommandProcessHandle(proc=proc, loop=loop, master_fd=master_fd)
518
712
 
519
713
  def _read_pty() -> "None":
714
+ sel = selectors.DefaultSelector()
520
715
  try:
716
+ sel.register(master_fd, selectors.EVENT_READ)
521
717
  while True:
718
+ timeout = 0.0 if stop_reader.is_set() else 0.1
719
+ events = sel.select(timeout=timeout)
720
+ if not events:
721
+ if stop_reader.is_set():
722
+ break
723
+ continue
522
724
  try:
523
725
  chunk = os.read(master_fd, 4096)
524
- except OSError as exc:
525
- if exc.errno in (errno.EIO, errno.EBADF):
526
- break
726
+ except OSError:
527
727
  break
528
728
  if not chunk:
529
729
  break
530
730
  handle.append_chunk(chunk)
731
+ if stop_reader.is_set():
732
+ break
531
733
  finally:
532
- code = proc.wait()
533
- handle.mark_finished(code)
534
-
535
- threading.Thread(target=_read_pty, daemon=True).start()
536
- return handle
537
-
538
- proc = subprocess.Popen(
539
- ["bash", "-c", command_line],
540
- stdin=subprocess.PIPE,
541
- stdout=subprocess.PIPE,
542
- stderr=subprocess.STDOUT,
543
- cwd=str(cwd),
544
- start_new_session=True,
545
- close_fds=True,
546
- )
547
- handle = _CommandProcessHandle(proc=proc, master_fd=None, loop=loop)
548
-
549
- def _read_pipe() -> "None":
550
- try:
551
- assert proc.stdout is not None
552
- while True:
553
- chunk = proc.stdout.read(4096)
554
- if not chunk:
555
- break
556
- handle.append_chunk(chunk)
557
- finally:
558
- code = proc.wait()
559
- handle.mark_finished(code)
734
+ try:
735
+ sel.close()
736
+ except OSError:
737
+ pass
738
+ reader_done.set()
739
+ handle._close_master_fd()
740
+
741
+ reader_target = _read_pty
742
+ else:
743
+ popen_kwargs: "typing.Dict[str, typing.Any]" = {
744
+ "stdin": subprocess.PIPE,
745
+ "stdout": subprocess.PIPE,
746
+ "stderr": subprocess.STDOUT,
747
+ "bufsize": 0,
748
+ "cwd": str(cwd),
749
+ "close_fds": True,
750
+ "env": child_env,
751
+ }
752
+ if os.name == "nt":
753
+ popen_kwargs["creationflags"] = (
754
+ getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
755
+ | getattr(subprocess, "CREATE_NO_WINDOW", 0)
756
+ )
757
+ else:
758
+ popen_kwargs["start_new_session"] = True
759
+ proc = subprocess.Popen(shell_argv, **popen_kwargs)
760
+ handle = _CommandProcessHandle(proc=proc, loop=loop)
560
761
 
561
- threading.Thread(target=_read_pipe, daemon=True).start()
762
+ def _read_pipe() -> "None":
763
+ stdout = proc.stdout
764
+ try:
765
+ if stdout is not None:
766
+ while True:
767
+ try:
768
+ chunk = stdout.read(4096)
769
+ except (OSError, ValueError):
770
+ break
771
+ if not chunk:
772
+ break
773
+ handle.append_chunk(chunk)
774
+ if stop_reader.is_set():
775
+ break
776
+ finally:
777
+ reader_done.set()
778
+ if stdout is not None:
779
+ try:
780
+ stdout.close()
781
+ except (OSError, ValueError):
782
+ pass
783
+
784
+ reader_target = _read_pipe
785
+
786
+ def _wait_process() -> "None":
787
+ code = proc.wait()
788
+ deadline = monotonic() + _POST_EXIT_MAX_DRAIN_SECONDS
789
+ while not reader_done.is_set():
790
+ before_seq = handle.output_seq
791
+ remaining = deadline - monotonic()
792
+ if remaining <= 0:
793
+ break
794
+ if reader_done.wait(timeout=min(_POST_EXIT_IDLE_DRAIN_SECONDS, remaining)):
795
+ break
796
+ if handle.output_seq == before_seq:
797
+ break
798
+ stop_reader.set()
799
+ handle.mark_finished(code)
800
+
801
+ threading.Thread(target=reader_target, daemon=True).start()
802
+ threading.Thread(target=_wait_process, daemon=True).start()
562
803
  return handle
563
804
 
564
805
  async def run_command(
@@ -605,31 +846,35 @@ class AgyTaskManager:
605
846
  )
606
847
 
607
848
  async def _watch_completion() -> "None":
608
- await handle.done_event.wait()
609
- if self._closed or record.status != "RUNNING":
849
+ try:
850
+ await handle.done_event.wait()
851
+ if self._closed or record.status != "RUNNING":
852
+ return
853
+ record.status = "DONE"
854
+ code = 0 if handle.exit_code is None else int(handle.exit_code)
855
+ raw_result_body = format_command_result_body(code, handle.output_text())
856
+ try:
857
+ result_body = truncate_agy_tool_output(
858
+ raw_result_body,
859
+ output_path=self._step_output_path(step_index),
860
+ always_persist=True,
861
+ )
862
+ except OSError:
863
+ result_body = truncate_agy_tool_output(raw_result_body)
864
+ msg_content = (
865
+ f'Task id "{task_id}" finished with result:\n'
866
+ f"{result_body}\n"
867
+ f"Log: file://{log_path}"
868
+ )
869
+ self._notify_callback(
870
+ msg_content,
871
+ task_id,
872
+ "MESSAGE_PRIORITY_HIGH",
873
+ True,
874
+ "Task done",
875
+ )
876
+ finally:
610
877
  self._signal_state_change()
611
- return
612
- record.status = "DONE"
613
- code = 0 if handle.exit_code is None else int(handle.exit_code)
614
- raw_result_body = format_command_result_body(code, handle.output_text())
615
- result_body = truncate_agy_tool_output(
616
- raw_result_body,
617
- output_path=self._step_output_path(step_index),
618
- always_persist=True,
619
- )
620
- msg_content = (
621
- f'Task id "{task_id}" finished with result:\n'
622
- f"{result_body}\n"
623
- f"Log: file://{log_path}"
624
- )
625
- self._notify_callback(
626
- msg_content,
627
- task_id,
628
- "MESSAGE_PRIORITY_HIGH",
629
- True,
630
- "Task done",
631
- )
632
- self._signal_state_change()
633
878
 
634
879
  self._tasks[task_id] = record
635
880
  record.async_task = asyncio.create_task(_watch_completion())
@@ -751,7 +996,10 @@ class AgyTaskManager:
751
996
  if accepted is False:
752
997
  return # Admission closed. Leave the saved occurrence for resume.
753
998
  if final:
754
- path.unlink()
999
+ try:
1000
+ path.unlink()
1001
+ except FileNotFoundError:
1002
+ pass
755
1003
  else:
756
1004
  schedule.next_fire_at = _next_cron_deadline(schedule.cron_expression, schedule.exact_timing)
757
1005
  schedule.save(path)
@@ -838,8 +1086,8 @@ class AgyTaskManager:
838
1086
  if rec.status == "RUNNING":
839
1087
  rec.status = "CANCELLED"
840
1088
  had_running = True
841
- if rec.command_handle is not None:
842
- rec.command_handle.terminate_group()
1089
+ if rec.command_handle is not None:
1090
+ rec.command_handle.terminate_group()
843
1091
  if rec.async_task is not None and not rec.async_task.done():
844
1092
  rec.async_task.cancel()
845
1093
  pending_tasks.append(rec.async_task)
@@ -4,6 +4,7 @@ import asyncio
4
4
  from copy import deepcopy
5
5
  from datetime import datetime
6
6
  import json
7
+ import os
7
8
  from pathlib import Path
8
9
  import typing
9
10
 
@@ -12,6 +13,7 @@ from pycodex.tools.base_tool import BaseTool, StructuredToolOutput, ToolContext,
12
13
  from pycodex.tools.runtime_services import AgentRuntimeEnvironment
13
14
 
14
15
  from ..context import format_local_iso
16
+ from ..task_manager import resolve_agy_shell_command
15
17
  from ..transcript import truncate_agy_tool_output
16
18
 
17
19
  if typing.TYPE_CHECKING:
@@ -56,6 +58,14 @@ def load_official_declarations() -> "typing.Tuple[typing.Tuple[str, ...], typing
56
58
  name = str(entry["name"])
57
59
  order.append(name)
58
60
  by_name[name] = deepcopy(entry)
61
+ if os.name == "nt" and "run_command" in by_name:
62
+ shell_label, _ = resolve_agy_shell_command("")
63
+ by_name["run_command"]["description"] = str(
64
+ by_name["run_command"]["description"]
65
+ ).replace(
66
+ "Operating System: linux. Shell: bash.",
67
+ f"Operating System: windows. Shell: {shell_label}.",
68
+ )
59
69
  return tuple(order), by_name
60
70
 
61
71
 
@@ -4,12 +4,12 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pyagy"
7
- version = "0.7.1"
7
+ version = "0.7.2"
8
8
  description = "Antigravity CLI (agy 1.5.14) wire-compatible harness built on python-codex"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.7"
11
11
  dependencies = [
12
- "python-codex==0.7.1",
12
+ "python-codex==0.7.2",
13
13
  ]
14
14
 
15
15
  [project.scripts]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes