snow-agent 0.1.0__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.
Files changed (78) hide show
  1. snow_agent-0.1.0/LICENSE +21 -0
  2. snow_agent-0.1.0/PKG-INFO +114 -0
  3. snow_agent-0.1.0/README.md +85 -0
  4. snow_agent-0.1.0/pyproject.toml +60 -0
  5. snow_agent-0.1.0/setup.cfg +4 -0
  6. snow_agent-0.1.0/src/snow_agent/__init__.py +3 -0
  7. snow_agent-0.1.0/src/snow_agent/__main__.py +8 -0
  8. snow_agent-0.1.0/src/snow_agent/adapters/__init__.py +1 -0
  9. snow_agent-0.1.0/src/snow_agent/adapters/_process.py +185 -0
  10. snow_agent-0.1.0/src/snow_agent/adapters/antigravity.py +162 -0
  11. snow_agent-0.1.0/src/snow_agent/adapters/claude_code.py +171 -0
  12. snow_agent-0.1.0/src/snow_agent/adapters/codex.py +284 -0
  13. snow_agent-0.1.0/src/snow_agent/adapters/opencode.py +209 -0
  14. snow_agent-0.1.0/src/snow_agent/adapters/zcode.py +374 -0
  15. snow_agent-0.1.0/src/snow_agent/cli/__init__.py +5 -0
  16. snow_agent-0.1.0/src/snow_agent/cli/app.py +578 -0
  17. snow_agent-0.1.0/src/snow_agent/cli/parser.py +202 -0
  18. snow_agent-0.1.0/src/snow_agent/cli/render.py +70 -0
  19. snow_agent-0.1.0/src/snow_agent/core/__init__.py +6 -0
  20. snow_agent-0.1.0/src/snow_agent/core/agent_adapters.py +239 -0
  21. snow_agent-0.1.0/src/snow_agent/core/capabilities.py +995 -0
  22. snow_agent-0.1.0/src/snow_agent/core/config.py +432 -0
  23. snow_agent-0.1.0/src/snow_agent/core/controlproto.py +120 -0
  24. snow_agent-0.1.0/src/snow_agent/core/delegation.py +650 -0
  25. snow_agent-0.1.0/src/snow_agent/core/errors.py +29 -0
  26. snow_agent-0.1.0/src/snow_agent/core/execution.py +45 -0
  27. snow_agent-0.1.0/src/snow_agent/core/help.py +182 -0
  28. snow_agent-0.1.0/src/snow_agent/core/local_exec.py +184 -0
  29. snow_agent-0.1.0/src/snow_agent/core/logutil.py +48 -0
  30. snow_agent-0.1.0/src/snow_agent/core/models.py +231 -0
  31. snow_agent-0.1.0/src/snow_agent/core/probes.py +239 -0
  32. snow_agent-0.1.0/src/snow_agent/core/services.py +219 -0
  33. snow_agent-0.1.0/src/snow_agent/core/shellencode.py +35 -0
  34. snow_agent-0.1.0/src/snow_agent/core/ssh_exec.py +369 -0
  35. snow_agent-0.1.0/src/snow_agent/core/task_contract.py +503 -0
  36. snow_agent-0.1.0/src/snow_agent/core/task_git.py +526 -0
  37. snow_agent-0.1.0/src/snow_agent/core/task_ipc.py +435 -0
  38. snow_agent-0.1.0/src/snow_agent/core/task_store.py +775 -0
  39. snow_agent-0.1.0/src/snow_agent/core/task_transport.py +202 -0
  40. snow_agent-0.1.0/src/snow_agent/core/util.py +98 -0
  41. snow_agent-0.1.0/src/snow_agent/core/wrapper.py +75 -0
  42. snow_agent-0.1.0/src/snow_agent/entrypoints/__init__.py +1 -0
  43. snow_agent-0.1.0/src/snow_agent/entrypoints/cli.py +20 -0
  44. snow_agent-0.1.0/src/snow_agent/entrypoints/tui.py +19 -0
  45. snow_agent-0.1.0/src/snow_agent/runtime/__init__.py +1 -0
  46. snow_agent-0.1.0/src/snow_agent/runtime/daemon.py +292 -0
  47. snow_agent-0.1.0/src/snow_agent/runtime/worker.py +806 -0
  48. snow_agent-0.1.0/src/snow_agent.egg-info/PKG-INFO +114 -0
  49. snow_agent-0.1.0/src/snow_agent.egg-info/SOURCES.txt +76 -0
  50. snow_agent-0.1.0/src/snow_agent.egg-info/dependency_links.txt +1 -0
  51. snow_agent-0.1.0/src/snow_agent.egg-info/entry_points.txt +2 -0
  52. snow_agent-0.1.0/src/snow_agent.egg-info/requires.txt +4 -0
  53. snow_agent-0.1.0/src/snow_agent.egg-info/top_level.txt +1 -0
  54. snow_agent-0.1.0/tests/test_agent_probe_units.py +383 -0
  55. snow_agent-0.1.0/tests/test_argv_fidelity.py +196 -0
  56. snow_agent-0.1.0/tests/test_cli.py +267 -0
  57. snow_agent-0.1.0/tests/test_config.py +183 -0
  58. snow_agent-0.1.0/tests/test_controlproto.py +153 -0
  59. snow_agent-0.1.0/tests/test_delegation_loop.py +390 -0
  60. snow_agent-0.1.0/tests/test_delegation_loop_antigravity.py +106 -0
  61. snow_agent-0.1.0/tests/test_delegation_loop_claude_code.py +105 -0
  62. snow_agent-0.1.0/tests/test_delegation_loop_opencode.py +107 -0
  63. snow_agent-0.1.0/tests/test_delegation_loop_zcode.py +146 -0
  64. snow_agent-0.1.0/tests/test_delegation_recovery.py +574 -0
  65. snow_agent-0.1.0/tests/test_failure_semantics.py +181 -0
  66. snow_agent-0.1.0/tests/test_help_driven.py +444 -0
  67. snow_agent-0.1.0/tests/test_local_executor.py +83 -0
  68. snow_agent-0.1.0/tests/test_loopback_sshd.py +289 -0
  69. snow_agent-0.1.0/tests/test_no_secret_leak.py +238 -0
  70. snow_agent-0.1.0/tests/test_p2_cli_fixes.py +122 -0
  71. snow_agent-0.1.0/tests/test_partial_output.py +102 -0
  72. snow_agent-0.1.0/tests/test_probes.py +243 -0
  73. snow_agent-0.1.0/tests/test_result_protocol.py +234 -0
  74. snow_agent-0.1.0/tests/test_shellencode.py +60 -0
  75. snow_agent-0.1.0/tests/test_ssh_executor.py +192 -0
  76. snow_agent-0.1.0/tests/test_streaming.py +225 -0
  77. snow_agent-0.1.0/tests/test_task_units.py +483 -0
  78. snow_agent-0.1.0/tests/test_transport_rpc.py +270 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 XiaodongTong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: snow-agent
3
+ Version: 0.1.0
4
+ Summary: Cross-device command execution and agent orchestration CLI.
5
+ Author: XiaodongTong
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/XiaodongTong/snow-agent
8
+ Project-URL: Repository, https://github.com/XiaodongTong/snow-agent
9
+ Project-URL: Issues, https://github.com/XiaodongTong/snow-agent/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development
21
+ Classifier: Topic :: System :: Distributed Computing
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.4; extra == "dev"
27
+ Requires-Dist: ruff>=0.4; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # snow-agent
31
+
32
+ Cross-device command execution and agent orchestration CLI.
33
+
34
+ snow-agent 把目标设备(host)与可复用命令(command)作为确定性资源管理:先注册可通过 SSH 访问的目标设备,再在本地或目标机上执行命令,直接复用目标机用户的登录态与业务凭据,不复制私钥或业务令牌。跨 Agent 任务委派(delegate/task/daemon)把开发方案交给执行设备上的原生编码 Agent(Codex / OpenCode / Claude Code / Antigravity CLI / ZCode)持久执行:同项目任务 FIFO 串行,Snow 独立验证并受控提交。定时调度(job)、配置管理(config)、环境检查(doctor)、MCP 接入与 Snow 自有 Agent Loop 在 [docs](docs/) 中规划,随迭代交付。
35
+
36
+ ## 安装
37
+
38
+ 需要 Python >= 3.10,无第三方运行时依赖:
39
+
40
+ ```bash
41
+ uvx snow-agent --version # 免安装直接运行(uv)
42
+ pipx install snow-agent # 独立环境常规安装
43
+ pip install snow-agent # 装入当前环境
44
+ ```
45
+
46
+ 开发安装:克隆仓库后 `pip install -e .`。
47
+
48
+ 安装后获得 `snow-agent` 命令入口;`uvx snow-agent` 无需安装即可使用全部子命令。
49
+
50
+ ## 当前可用命令
51
+
52
+ 完整调用说明(参数、工作流、JSON 字段与错误恢复)见 [docs/cli-usage.md](docs/cli-usage.md);本节只列命令速览。
53
+
54
+ ```text
55
+ snow-agent help [COMMAND...] # 分层帮助;--format json 输出同源的结构化能力描述
56
+ snow-agent init # 初始化用户级配置
57
+ snow-agent host add|list|show|test|remove # 目标设备注册与 SSH 连通性检查
58
+ snow-agent command add|list|show|check|run|remove # 可复用命令注册、检查与执行
59
+ snow-agent exec [--host HOST] [--cwd PATH] [--timeout DURATION] -- COMMAND [ARGS...]
60
+ snow-agent delegate submit|targets # 把开发方案提交给原生编码 Agent 持久执行
61
+ snow-agent task list|show|cancel|resume|report # 委派任务的查询、取消、恢复与阶段上报
62
+ snow-agent daemon start|stop|status # 任务调度守护进程(单实例)
63
+ ```
64
+
65
+ 无参数调用 `snow-agent` 预留给未来的交互式 TUI,当前降级为输出根帮助。
66
+
67
+ `job`、`config`、`doctor`、`mcp`、`agent` 已在命令树中声明但尚未实现,调用返回结构化 `not_available` 错误。`_rpc` 是委派传输经 SSH 调用的内部入口,不面向日常调用。
68
+
69
+ 根级支持 `snow-agent --version`:文本模式输出一行 `snow-agent 0.1.0`;`--json` 输出 `{"schema_version":1,"kind":"version","version":"0.1.0"}`。该选项仅在根级可用。
70
+
71
+ 退出码:确认的业务退出码原样保留;Snow 自身失败为 1;超时或中断等结果不确定的情况为 2。
72
+
73
+ 文本模式(无 `--json`)下,远端执行的输出剥离 snow-agent 控制记录后逐块实时转发到本进程 stdout/stderr,不等待命令结束;`--json` 时 stdout 只有一个结果对象,字段契约见 `snow-agent exec --help`。
74
+
75
+ 配置存储在 `~/.snow-agent/`(目录 0700、文件 0600、原子写入),用环境变量 `SNOW_AGENT_CONFIG_DIR` 可指定其他位置。
76
+
77
+ ## 快速上手
78
+
79
+ 本地执行,无需任何配置:
80
+
81
+ ```bash
82
+ snow-agent exec -- git status
83
+ ```
84
+
85
+ 跨设备执行(备用机调用主力机上已登录的业务 CLI):
86
+
87
+ ```bash
88
+ snow-agent host add main --ssh user@192.168.1.10 # 注册目标设备,认证沿用标准 SSH 配置
89
+ snow-agent host test main # 检查连接、认证与目标执行环境
90
+ snow-agent exec --host main -- meishi unread # 在目标机上执行一次
91
+ ```
92
+
93
+ 对需要反复调用的 CLI,注册为可复用命令:
94
+
95
+ ```bash
96
+ snow-agent command add meishi --host main --bin /opt/homebrew/bin/meishi
97
+ snow-agent command check meishi
98
+ snow-agent command run meishi -- unread
99
+ ```
100
+
101
+ 跨设备委派在项目所在设备执行(`--host` 指定,默认 local);方案文件在调用端读取,以不可变快照传输。执行设备需先启动调度进程:
102
+
103
+ ```bash
104
+ snow-agent daemon start # 在执行设备上启动任务调度
105
+ snow-agent delegate targets # 查看当前设备可用的委派目标(codex / opencode / claude-code / antigravity / zcode)
106
+ snow-agent delegate submit --cwd /workspace/repo --agent codex --file ./plans/B.md
107
+ snow-agent task show <task_id> # 轮询阶段、验证结论与提交哈希
108
+ ```
109
+
110
+ `submit` 立即返回任务 ID;执行设备上的队列、Agent 轮次、独立验证与受控提交在调用方离线后继续。同项目任务按提交顺序串行,失败或状态不明的任务阻塞后续任务,处理后用 `task resume` 恢复。跨设备查询与提交经 SSH 短请求转发到执行设备,方案文件在调用端读取后以不可变快照传输。
111
+
112
+ 取消、恢复、崩溃续接与各阶段上报语义,以及全部命令的参数、JSON 字段和错误处理,见 [docs/cli-usage.md](docs/cli-usage.md)。
113
+
114
+ 每个命令都有分层 `--help`;外部 Agent 无需预置专属 Skill,仅凭逐级帮助与结构化结果即可完成配置、检查、执行和错误恢复。
@@ -0,0 +1,85 @@
1
+ # snow-agent
2
+
3
+ Cross-device command execution and agent orchestration CLI.
4
+
5
+ snow-agent 把目标设备(host)与可复用命令(command)作为确定性资源管理:先注册可通过 SSH 访问的目标设备,再在本地或目标机上执行命令,直接复用目标机用户的登录态与业务凭据,不复制私钥或业务令牌。跨 Agent 任务委派(delegate/task/daemon)把开发方案交给执行设备上的原生编码 Agent(Codex / OpenCode / Claude Code / Antigravity CLI / ZCode)持久执行:同项目任务 FIFO 串行,Snow 独立验证并受控提交。定时调度(job)、配置管理(config)、环境检查(doctor)、MCP 接入与 Snow 自有 Agent Loop 在 [docs](docs/) 中规划,随迭代交付。
6
+
7
+ ## 安装
8
+
9
+ 需要 Python >= 3.10,无第三方运行时依赖:
10
+
11
+ ```bash
12
+ uvx snow-agent --version # 免安装直接运行(uv)
13
+ pipx install snow-agent # 独立环境常规安装
14
+ pip install snow-agent # 装入当前环境
15
+ ```
16
+
17
+ 开发安装:克隆仓库后 `pip install -e .`。
18
+
19
+ 安装后获得 `snow-agent` 命令入口;`uvx snow-agent` 无需安装即可使用全部子命令。
20
+
21
+ ## 当前可用命令
22
+
23
+ 完整调用说明(参数、工作流、JSON 字段与错误恢复)见 [docs/cli-usage.md](docs/cli-usage.md);本节只列命令速览。
24
+
25
+ ```text
26
+ snow-agent help [COMMAND...] # 分层帮助;--format json 输出同源的结构化能力描述
27
+ snow-agent init # 初始化用户级配置
28
+ snow-agent host add|list|show|test|remove # 目标设备注册与 SSH 连通性检查
29
+ snow-agent command add|list|show|check|run|remove # 可复用命令注册、检查与执行
30
+ snow-agent exec [--host HOST] [--cwd PATH] [--timeout DURATION] -- COMMAND [ARGS...]
31
+ snow-agent delegate submit|targets # 把开发方案提交给原生编码 Agent 持久执行
32
+ snow-agent task list|show|cancel|resume|report # 委派任务的查询、取消、恢复与阶段上报
33
+ snow-agent daemon start|stop|status # 任务调度守护进程(单实例)
34
+ ```
35
+
36
+ 无参数调用 `snow-agent` 预留给未来的交互式 TUI,当前降级为输出根帮助。
37
+
38
+ `job`、`config`、`doctor`、`mcp`、`agent` 已在命令树中声明但尚未实现,调用返回结构化 `not_available` 错误。`_rpc` 是委派传输经 SSH 调用的内部入口,不面向日常调用。
39
+
40
+ 根级支持 `snow-agent --version`:文本模式输出一行 `snow-agent 0.1.0`;`--json` 输出 `{"schema_version":1,"kind":"version","version":"0.1.0"}`。该选项仅在根级可用。
41
+
42
+ 退出码:确认的业务退出码原样保留;Snow 自身失败为 1;超时或中断等结果不确定的情况为 2。
43
+
44
+ 文本模式(无 `--json`)下,远端执行的输出剥离 snow-agent 控制记录后逐块实时转发到本进程 stdout/stderr,不等待命令结束;`--json` 时 stdout 只有一个结果对象,字段契约见 `snow-agent exec --help`。
45
+
46
+ 配置存储在 `~/.snow-agent/`(目录 0700、文件 0600、原子写入),用环境变量 `SNOW_AGENT_CONFIG_DIR` 可指定其他位置。
47
+
48
+ ## 快速上手
49
+
50
+ 本地执行,无需任何配置:
51
+
52
+ ```bash
53
+ snow-agent exec -- git status
54
+ ```
55
+
56
+ 跨设备执行(备用机调用主力机上已登录的业务 CLI):
57
+
58
+ ```bash
59
+ snow-agent host add main --ssh user@192.168.1.10 # 注册目标设备,认证沿用标准 SSH 配置
60
+ snow-agent host test main # 检查连接、认证与目标执行环境
61
+ snow-agent exec --host main -- meishi unread # 在目标机上执行一次
62
+ ```
63
+
64
+ 对需要反复调用的 CLI,注册为可复用命令:
65
+
66
+ ```bash
67
+ snow-agent command add meishi --host main --bin /opt/homebrew/bin/meishi
68
+ snow-agent command check meishi
69
+ snow-agent command run meishi -- unread
70
+ ```
71
+
72
+ 跨设备委派在项目所在设备执行(`--host` 指定,默认 local);方案文件在调用端读取,以不可变快照传输。执行设备需先启动调度进程:
73
+
74
+ ```bash
75
+ snow-agent daemon start # 在执行设备上启动任务调度
76
+ snow-agent delegate targets # 查看当前设备可用的委派目标(codex / opencode / claude-code / antigravity / zcode)
77
+ snow-agent delegate submit --cwd /workspace/repo --agent codex --file ./plans/B.md
78
+ snow-agent task show <task_id> # 轮询阶段、验证结论与提交哈希
79
+ ```
80
+
81
+ `submit` 立即返回任务 ID;执行设备上的队列、Agent 轮次、独立验证与受控提交在调用方离线后继续。同项目任务按提交顺序串行,失败或状态不明的任务阻塞后续任务,处理后用 `task resume` 恢复。跨设备查询与提交经 SSH 短请求转发到执行设备,方案文件在调用端读取后以不可变快照传输。
82
+
83
+ 取消、恢复、崩溃续接与各阶段上报语义,以及全部命令的参数、JSON 字段和错误处理,见 [docs/cli-usage.md](docs/cli-usage.md)。
84
+
85
+ 每个命令都有分层 `--help`;外部 Agent 无需预置专属 Skill,仅凭逐级帮助与结构化结果即可完成配置、检查、执行和错误恢复。
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "snow-agent"
7
+ description = "Cross-device command execution and agent orchestration CLI."
8
+ readme = "README.md"
9
+ requires-python = ">=3.10"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "XiaodongTong" }]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Environment :: Console",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: MacOS",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Software Development",
25
+ "Topic :: System :: Distributed Computing",
26
+ ]
27
+ dependencies = []
28
+ dynamic = ["version"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/XiaodongTong/snow-agent"
32
+ Repository = "https://github.com/XiaodongTong/snow-agent"
33
+ Issues = "https://github.com/XiaodongTong/snow-agent/issues"
34
+
35
+ [project.optional-dependencies]
36
+ dev = ["pytest>=7.4", "ruff>=0.4"]
37
+
38
+ [project.scripts]
39
+ snow-agent = "snow_agent.entrypoints.cli:main"
40
+
41
+ [tool.setuptools]
42
+ package-dir = { "" = "src" }
43
+
44
+ [tool.setuptools.dynamic]
45
+ version = { attr = "snow_agent.__version__" }
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["src"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
52
+ addopts = "-q"
53
+
54
+ [tool.ruff]
55
+ line-length = 100
56
+ target-version = "py310"
57
+ src = ["src", "tests"]
58
+
59
+ [tool.ruff.lint]
60
+ select = ["E", "F", "W", "I", "UP", "B", "C4"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """snow-agent: cross-device command execution and agent orchestration CLI."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,8 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ from .entrypoints.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ """Agent adapters: one module per delivered delegation target."""
@@ -0,0 +1,185 @@
1
+ """Shared process plumbing for JSONL-emitting agent CLIs.
2
+
3
+ The adapters for OpenCode, Claude Code and Antigravity drive plain CLI
4
+ processes whose stdout is one JSON object per line; the turn ends when the
5
+ process exits (their exit codes and envelopes never prove business success —
6
+ that decision stays in the workflow core). ``JsonlProcess`` owns the process
7
+ group started with ``start_new_session``, feeds the prompt (stdin or argv per
8
+ product contract) and leaves per-product event handling to subclasses.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import subprocess
16
+ import time
17
+ from threading import Thread
18
+ from typing import Any
19
+
20
+ from ..core.agent_adapters import AgentProcess, AgentStartSpec
21
+ from ..core.errors import SnowError
22
+
23
+ _STDERR_TAIL_BYTES = 8192
24
+
25
+
26
+ class JsonlProcess(AgentProcess):
27
+ """One CLI agent round: process group + stdout/stderr reader threads.
28
+
29
+ ``stop_sequence`` is the escalation ladder for :meth:`stop` (Antigravity
30
+ needs SIGINT first; the others stop on SIGTERM like Codex).
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ proc: subprocess.Popen[bytes],
36
+ argv_label: str,
37
+ stop_sequence: tuple[tuple[int, float], ...],
38
+ ) -> None:
39
+ super().__init__()
40
+ self._proc = proc
41
+ self._argv_label = argv_label
42
+ self._stop_sequence = stop_sequence
43
+ self.stderr_tail = ""
44
+ self.exit_code: int | None = None
45
+ self._threads = [
46
+ Thread(target=self._read_stdout, daemon=True),
47
+ Thread(target=self._read_stderr, daemon=True),
48
+ ]
49
+ for thread in self._threads:
50
+ thread.start()
51
+
52
+ # ---- per-product event handling ------------------------------------------
53
+
54
+ def _handle_event(self, event: dict[str, Any]) -> None:
55
+ """Inspect one parsed stdout line; set ``session_id`` / queue events."""
56
+
57
+ # ---- process lifecycle -----------------------------------------------------
58
+
59
+ @property
60
+ def pid(self) -> int | None:
61
+ return self._proc.pid
62
+
63
+ @property
64
+ def pgid(self) -> int | None:
65
+ return self._proc.pid if self._proc.pid else None
66
+
67
+ def _read_stdout(self) -> None:
68
+ assert self._proc.stdout is not None
69
+ for line in self._proc.stdout:
70
+ text = line.decode("utf-8", errors="replace").strip()
71
+ if not text:
72
+ continue
73
+ try:
74
+ event = json.loads(text)
75
+ except json.JSONDecodeError:
76
+ continue
77
+ if isinstance(event, dict):
78
+ self._handle_event(event)
79
+
80
+ def _read_stderr(self) -> None:
81
+ assert self._proc.stderr is not None
82
+ data = self._proc.stderr.read() or b""
83
+ try:
84
+ self.stderr_tail = data[-_STDERR_TAIL_BYTES:].decode("utf-8", errors="replace")
85
+ except Exception:
86
+ self.stderr_tail = ""
87
+
88
+ def poll(self) -> int | None:
89
+ return self._proc.poll()
90
+
91
+ def wait(self, timeout: float | None = None) -> int | None:
92
+ try:
93
+ self.exit_code = self._proc.wait(timeout=timeout)
94
+ except subprocess.TimeoutExpired:
95
+ return None
96
+ for thread in self._threads:
97
+ thread.join(timeout=5)
98
+ return self.exit_code
99
+
100
+ def group_alive(self) -> bool:
101
+ """True while any member of the agent process group exists."""
102
+ pgid = self.pgid
103
+ if pgid is None:
104
+ return False
105
+ try:
106
+ os.killpg(pgid, 0)
107
+ except ProcessLookupError:
108
+ return False
109
+ except PermissionError:
110
+ return True
111
+ return True
112
+
113
+ def stop(self, *, grace_s: float = 10.0) -> None:
114
+ """Escalate through ``stop_sequence`` to the group; verify it is gone."""
115
+ pgid = self.pgid
116
+ if pgid is None:
117
+ return
118
+ for sig, wait_s in self._stop_sequence:
119
+ try:
120
+ os.killpg(pgid, sig)
121
+ except (ProcessLookupError, PermissionError):
122
+ break
123
+ deadline = time.monotonic() + wait_s
124
+ while time.monotonic() < deadline:
125
+ if self._proc.poll() is not None and not self.group_alive():
126
+ self.exit_code = self._proc.returncode
127
+ return
128
+ time.sleep(0.2)
129
+ try:
130
+ self.exit_code = self._proc.wait(timeout=5)
131
+ except subprocess.TimeoutExpired:
132
+ pass
133
+
134
+ def join(self, timeout: float = 5.0) -> None:
135
+ for thread in self._threads:
136
+ thread.join(timeout=timeout)
137
+
138
+
139
+ def spawn_jsonl_agent(
140
+ argv: list[str],
141
+ spec: AgentStartSpec,
142
+ *,
143
+ product: str,
144
+ stop_sequence: tuple[tuple[int, float], ...],
145
+ prompt_stdin: bool = True,
146
+ process_cls: type[JsonlProcess] | None = None,
147
+ ) -> JsonlProcess:
148
+ """Spawn one agent round and return its :class:`JsonlProcess`.
149
+
150
+ ``prompt_stdin`` selects the product's prompt channel: OpenCode and
151
+ Claude Code read the prompt from stdin (EOF right after); Antigravity's
152
+ ``--print`` takes the prompt as an argv value and does not read stdin.
153
+ """
154
+ env = {**os.environ, **spec.env}
155
+ stdin_target = subprocess.PIPE if prompt_stdin else subprocess.DEVNULL
156
+ try:
157
+ proc = subprocess.Popen(
158
+ argv,
159
+ cwd=str(spec.cwd),
160
+ stdin=stdin_target,
161
+ stdout=subprocess.PIPE,
162
+ stderr=subprocess.PIPE,
163
+ start_new_session=True,
164
+ env=env,
165
+ )
166
+ except OSError as err:
167
+ raise SnowError(
168
+ "agent_start_failed",
169
+ f"Starting {product} failed: {err}",
170
+ next_steps=(f"Check the {product} installation on this device.",),
171
+ ) from err
172
+ if prompt_stdin:
173
+ assert proc.stdin is not None
174
+ try:
175
+ proc.stdin.write(spec.prompt.encode("utf-8"))
176
+ proc.stdin.flush()
177
+ except OSError:
178
+ pass # agent died immediately; the observer path reports it
179
+ finally:
180
+ try:
181
+ proc.stdin.close()
182
+ except OSError:
183
+ pass
184
+ cls = process_cls or JsonlProcess
185
+ return cls(proc, argv_label=argv[0], stop_sequence=stop_sequence)
@@ -0,0 +1,162 @@
1
+ """Google Antigravity CLI (``agy``) adapter for delegated execution.
2
+
3
+ Launch contract (research-verified on 1.5.3, re-smoked on 1.5.9):
4
+ ``agy --dangerously-skip-permissions --output-format stream-json -p <prompt>``
5
+ with the prompt as an argv value — ``--print`` never reads plain stdin. The
6
+ first ``init`` event carries ``conversation_id`` at the top level (1.5.3 also
7
+ accepted ``init.conversation_id``; 1.5.9 only emits the top-level key), and
8
+ resume appends ``--conversation <id>``. Unattended authorization is only
9
+ verified to work with ``--dangerously-skip-permissions`` (fine-grained allow
10
+ rules were measured broken in headless 1.5.3), so tasks must target a
11
+ dedicated sandbox repository — that boundary is operational, documented in
12
+ the CLI usage guide, and enforced nowhere in code. Cancellation sends SIGINT
13
+ first (agy reports ``finished_reason: interrupted``), then escalates; the
14
+ signal must reach the real agy PID/group, never a ``timeout`` wrapper.
15
+ ``status=SUCCESS`` only means the turn ended; business success is decided by
16
+ the workflow core.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ import signal
23
+
24
+ from ..core.agent_adapters import (
25
+ AgentStartSpec,
26
+ ProbeResult,
27
+ probe_binary,
28
+ run_probe,
29
+ )
30
+ from ..core.errors import SnowError
31
+ from ._process import JsonlProcess, spawn_jsonl_agent
32
+
33
+ AGENT_NAME = "antigravity"
34
+ MINIMUM_VERSION = (1, 5, 3)
35
+ STOP_SEQUENCE = ((signal.SIGINT, 10.0), (signal.SIGTERM, 5.0), (signal.SIGKILL, 5.0))
36
+ _BASE_ARGV = ("--dangerously-skip-permissions", "--output-format", "stream-json")
37
+
38
+
39
+ def _version_supported(version: str) -> tuple[bool, str]:
40
+ match = re.search(r"(\d+)\.(\d+)\.(\d+)", version)
41
+ if not match:
42
+ return False, f"unrecognized version output: {version.strip()!r}"
43
+ triple = tuple(int(part) for part in match.groups())
44
+ if triple >= MINIMUM_VERSION:
45
+ return True, ""
46
+ dots = ".".join(str(part) for part in triple)
47
+ return (
48
+ False,
49
+ f"version {dots} is below the required minimum 1.5.3 (1.1.x writes files"
50
+ " outside the working directory)",
51
+ )
52
+
53
+
54
+ def probe() -> ProbeResult:
55
+ """Check binary, minimum version and cached credentials (``agy models``)."""
56
+ result = ProbeResult(agent=AGENT_NAME, available=True)
57
+ binary, reason = probe_binary("agy")
58
+ if binary is None:
59
+ result.available = False
60
+ result.unavailable_reason = reason
61
+ result.checks.append({"name": "binary", "result": "fail", "detail": reason})
62
+ return result
63
+ result.checks.append({"name": "binary", "result": "pass", "detail": binary})
64
+ try:
65
+ version = run_probe([binary, "--version"]).stdout
66
+ except Exception as err: # noqa: BLE001 - probe reports, never raises
67
+ result.available = False
68
+ reason = f"agy --version failed: {err}"
69
+ result.unavailable_reason = reason
70
+ result.checks.append({"name": "version", "result": "fail", "detail": reason})
71
+ return result
72
+ ok, detail = _version_supported(version)
73
+ result.checks.append(
74
+ {"name": "version", "result": "pass" if ok else "fail", "detail": detail or version.strip()}
75
+ )
76
+ if not ok:
77
+ result.available = False
78
+ result.unavailable_reason = detail
79
+ return result
80
+ try:
81
+ models = run_probe([binary, "models"], timeout_s=60.0)
82
+ authenticated = models.returncode == 0 and bool(models.stdout.strip())
83
+ detail = "cached credentials available" if authenticated else (
84
+ (models.stderr or models.stdout).strip()[-400:] or "agy models returned no models"
85
+ )
86
+ except Exception as err: # noqa: BLE001 - probe reports, never raises
87
+ authenticated = False
88
+ detail = f"agy models failed: {err}"
89
+ result.checks.append(
90
+ {"name": "login", "result": "pass" if authenticated else "fail", "detail": detail}
91
+ )
92
+ if not authenticated:
93
+ result.available = False
94
+ result.unavailable_reason = (
95
+ "agy has no usable cached credentials; run 'agy' interactively once to"
96
+ " log in on this device (headless mode cannot log in)"
97
+ )
98
+ return result
99
+
100
+
101
+ class AntigravityProcess(JsonlProcess):
102
+ """One ``agy -p`` round: conversation_id from init/step/result events."""
103
+
104
+ def _handle_event(self, event: dict) -> None:
105
+ kind = event.get("event")
106
+ session_id = event.get("conversation_id")
107
+ if not isinstance(session_id, str) or not session_id:
108
+ payload = event.get(kind) if isinstance(event.get(kind), dict) else {}
109
+ session_id = payload.get("conversation_id") if isinstance(payload, dict) else None
110
+ if isinstance(session_id, str) and session_id:
111
+ self.session_id = session_id
112
+
113
+
114
+ class AntigravityAdapter:
115
+ """Launch and resume Antigravity CLI rounds with the verified argument set."""
116
+
117
+ def __init__(self, binary: str | None = None) -> None:
118
+ self._binary = binary
119
+
120
+ def _resolve_binary(self) -> str:
121
+ if self._binary:
122
+ return self._binary
123
+ binary, reason = probe_binary("agy")
124
+ if binary is None:
125
+ raise SnowError(
126
+ "agent_binary_missing",
127
+ f"Cannot start agy: {reason}.",
128
+ next_steps=("Install the Antigravity CLI or add it to PATH on this device.",),
129
+ )
130
+ return binary
131
+
132
+ def _spawn(self, argv: list[str], spec: AgentStartSpec) -> AntigravityProcess:
133
+ return spawn_jsonl_agent(
134
+ argv,
135
+ spec,
136
+ product="agy",
137
+ stop_sequence=STOP_SEQUENCE,
138
+ prompt_stdin=False,
139
+ process_cls=AntigravityProcess,
140
+ )
141
+
142
+ def start(self, spec: AgentStartSpec) -> AntigravityProcess:
143
+ """Fresh conversation: prompt as the ``-p`` argv value."""
144
+ binary = self._resolve_binary()
145
+ return self._spawn([binary, *_BASE_ARGV, "-p", spec.prompt], spec)
146
+
147
+ def resume(self, session_id: str, spec: AgentStartSpec) -> AntigravityProcess:
148
+ """Continue the same conversation with ``--conversation <id>``."""
149
+ if not session_id:
150
+ raise SnowError(
151
+ "agent_session_missing",
152
+ "Cannot resume without a native conversation id.",
153
+ next_steps=("Let Snow start a fresh implement round instead.",),
154
+ )
155
+ binary = self._resolve_binary()
156
+ return self._spawn(
157
+ [binary, *_BASE_ARGV, "--conversation", session_id, "-p", spec.prompt],
158
+ spec,
159
+ )
160
+
161
+
162
+ Adapter = AntigravityAdapter