mystack-rig 1.3.2__tar.gz → 1.4.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 (120) hide show
  1. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/GLOSSARY.md +8 -0
  2. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/PKG-INFO +48 -4
  3. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/README.md +47 -3
  4. mystack_rig-1.4.0/docs/adr/0004-agents-run-as-live-agents-in-tmux.md +20 -0
  5. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/pyproject.toml +3 -0
  6. mystack_rig-1.4.0/src/cli/ansible_filters/rig_live.py +88 -0
  7. mystack_rig-1.4.0/src/cli/assets/rig-agent-queue +33 -0
  8. mystack_rig-1.4.0/src/cli/assets/rig-agent-state +12 -0
  9. mystack_rig-1.4.0/src/cli/assets/tmux.conf +27 -0
  10. mystack_rig-1.4.0/src/cli/live_agent.py +238 -0
  11. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/main.py +215 -2
  12. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/remote_dev.py +196 -11
  13. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/PKG-INFO +48 -4
  14. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/SOURCES.txt +8 -0
  15. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/scm_file_list.json +8 -0
  16. mystack_rig-1.4.0/src/mystack_rig.egg-info/scm_version.json +8 -0
  17. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_attach_command.py +7 -0
  18. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_init_command.py +1 -1
  19. mystack_rig-1.4.0/tests/test_live_agent.py +614 -0
  20. mystack_rig-1.4.0/tests/test_live_agent_cli.py +507 -0
  21. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_rig_ansible_vars.py +1 -0
  22. mystack_rig-1.3.2/src/mystack_rig.egg-info/scm_version.json +0 -8
  23. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.coveragerc +0 -0
  24. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.git-blame-ignore-revs +0 -0
  25. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.github/workflows/release.yml +0 -0
  26. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.github/workflows/tests.yml +0 -0
  27. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.gitignore +0 -0
  28. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.rig/playbooks/README.md +0 -0
  29. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/.rig/playbooks/vpn-gateway.yml +0 -0
  30. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/CLI_STORAGE_SUMMARY.md +0 -0
  31. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/Dockerfile +0 -0
  32. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/GIT_CLONE_FEATURE.md +0 -0
  33. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/HETZNER_STORAGE_GUIDE.md +0 -0
  34. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/HETZNER_STORAGE_SECURITY_GUIDE.md +0 -0
  35. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/LICENSE +0 -0
  36. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/Makefile +0 -0
  37. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/README_REAL_E2E.md +0 -0
  38. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/STORAGE_CLI_GUIDE.md +0 -0
  39. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/docs/adr/0001-per-profile-generated-state-bucket.md +0 -0
  40. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/docs/adr/0002-outputs-as-separate-object-via-file-handoff.md +0 -0
  41. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/docs/adr/0003-mcp-servers-declared-once-rendered-at-authorize.md +0 -0
  42. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/docs/architecture.md +0 -0
  43. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/docs/architecture.png +0 -0
  44. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/docs/architecture.svg +0 -0
  45. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/forged-idea.md +0 -0
  46. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/pytest.ini +0 -0
  47. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/requirements.txt +0 -0
  48. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/sample.env +0 -0
  49. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/scripts/coverage_badge.py +0 -0
  50. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/scripts/pypi_version.py +0 -0
  51. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/setup.cfg +0 -0
  52. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/__init__.py +0 -0
  53. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/__init__.py +0 -0
  54. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/__main__.py +0 -0
  55. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/agents.py +0 -0
  56. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/ansible_filters/__init__.py +0 -0
  57. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/ansible_filters/rig_mcp.py +0 -0
  58. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/config.py +0 -0
  59. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/encrypt.py +0 -0
  60. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/git.py +0 -0
  61. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/git_author.py +0 -0
  62. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/last_env.py +0 -0
  63. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/last_session.py +0 -0
  64. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/log.py +0 -0
  65. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/mcp.py +0 -0
  66. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/outputs.py +0 -0
  67. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/requirements.txt +0 -0
  68. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/snapshots.py +0 -0
  69. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/state_bucket.py +0 -0
  70. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/storage.py +0 -0
  71. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/vault_keys.py +0 -0
  72. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/cli/vpn.py +0 -0
  73. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/dependency_links.txt +0 -0
  74. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/entry_points.txt +0 -0
  75. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/requires.txt +0 -0
  76. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/src/mystack_rig.egg-info/top_level.txt +0 -0
  77. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/test_hetzner_integration.py +0 -0
  78. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/conftest.py +0 -0
  79. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_agents.py +0 -0
  80. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_ansible_galaxy.py +0 -0
  81. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_credential_security.py +0 -0
  82. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_destroy_command.py +0 -0
  83. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_dev_command.py +0 -0
  84. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_encrypt_command.py +0 -0
  85. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_encrypt_coverage.py +0 -0
  86. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_firewall_client_ip.py +0 -0
  87. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_git_clone_unit.py +0 -0
  88. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_git_credentials_and_author.py +0 -0
  89. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_git_manager.py +0 -0
  90. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_gitignore_init.py +0 -0
  91. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_hetzner_storage.py +0 -0
  92. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_inspect_describe.py +0 -0
  93. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_last_env.py +0 -0
  94. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_last_session.py +0 -0
  95. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_log.py +0 -0
  96. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_main_coverage.py +0 -0
  97. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_mcp_command.py +0 -0
  98. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_mcp_render.py +0 -0
  99. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_outputs.py +0 -0
  100. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_outputs_storage.py +0 -0
  101. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_pypi_version.py +0 -0
  102. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_python_floor.py +0 -0
  103. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_real_e2e_integration.py +0 -0
  104. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_real_e2e_storage.py +0 -0
  105. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_real_e2e_vpn.py +0 -0
  106. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_real_e2e_vpn_tunnel.py +0 -0
  107. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_remote_dev.py +0 -0
  108. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_remote_dev_coverage_extensions.py +0 -0
  109. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_rig_config.py +0 -0
  110. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_secret_prompt_hidden.py +0 -0
  111. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_setup_provision.py +0 -0
  112. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_simulation_storage.py +0 -0
  113. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_small_module_coverage.py +0 -0
  114. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_snapshots.py +0 -0
  115. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_state_bucket.py +0 -0
  116. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_storage_basic.py +0 -0
  117. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_vault_keys.py +0 -0
  118. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_vpn_optional.py +0 -0
  119. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_vpn_unit.py +0 -0
  120. {mystack_rig-1.3.2 → mystack_rig-1.4.0}/tests/test_workspace_git_clone.py +0 -0
@@ -32,6 +32,14 @@ _Avoid_: Dev bucket
32
32
  A coding CLI that rig installs on an Environment: OpenCode, Claude Code or Cursor CLI.
33
33
  _Avoid_: Coding agent type, CLI, assistant
34
34
 
35
+ **Agent session**:
36
+ An Agent's saved conversation, which can be resumed by its id.
37
+ _Avoid_: Chat, thread
38
+
39
+ **Live agent**:
40
+ An Agent's running process on an Environment, kept alive when no terminal is connected. Attaching joins it; ending the Agent ends it.
41
+ _Avoid_: Background agent, daemon, detached session
42
+
35
43
  **Stage**:
36
44
  One of the playbook steps rig runs in order when creating an Environment: provision, configure, authorize, materialize, finalize. Only provision and configure are cached in a snapshot.
37
45
  _Avoid_: Phase, step
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mystack-rig
3
- Version: 1.3.2
3
+ Version: 1.4.0
4
4
  Summary: Ephemeral remotes with full local parity for coding agents
5
5
  Author: mystack-cloud
6
6
  License-Expression: MIT
@@ -102,6 +102,48 @@ rig mcp remove awx
102
102
  - Support files for a server (for example a stdio wrapper script) are not managed by rig: install them from your own playbook (provision, configure or authorize) and point `command` at that path.
103
103
  - The per-agent `.rig/.claude|.cursor|.opencode/mcp.json` files from earlier versions are no longer deployed. If one still declares servers, `rig apply`/`create` and `rig mcp check` warn; move them to `.rig/mcp.json`.
104
104
 
105
+ ## Live agents
106
+
107
+ `rig attach` runs the agent as a **live agent**: a process kept running on the Environment inside its own tmux session (`tmux -L rig`, with a config rig ships, so it never touches a tmux you use yourself). Closing the terminal or losing the connection only detaches; the agent keeps working, and the next `rig attach` joins it.
108
+
109
+ ```bash
110
+ rig attach # start the live agent, or join the running one
111
+ # leave: close the terminal, or detach with Ctrl+b d. Ctrl+C still goes to the agent.
112
+ rig attach --restart # replace it with a fresh process (resumes the same conversation)
113
+ rig attach --no-persist # old behaviour: the agent ends with the SSH session
114
+ ```
115
+
116
+ - One live agent per Agent type per Environment. A second `rig attach` joins the first (both terminals see the same screen). Resume flags (`-c`, `--resume`, `--session`) apply only when a live agent is *started*; joining ignores them with a warning.
117
+ - A bare `rig attach` joins whichever live agent is running. `--agent` picks another.
118
+ - `rig inspect` lists live agents. `rig apply` and `rig delete` warn when there are any: a live agent keeps the credentials and MCP config it started with until `rig attach --restart`, and deleting the Environment ends it.
119
+ - If the agent exits while nobody is attached, tmux has logged its output on the VM, and the next `rig attach` recovers the resume id from that log.
120
+
121
+ ### `rig exec`
122
+
123
+ Start an agent on a task and leave:
124
+
125
+ ```bash
126
+ rig exec "fix the failing tests in /workspace/api"
127
+ rig exec @task.md # prompt from a file
128
+ echo "review the diff" | rig exec - # prompt from stdin
129
+ rig exec --name dev-ab12cd34 --agent claude "..."
130
+ ```
131
+
132
+ `rig exec` starts the live agent with the prompt, prints how to attach, and returns. It never creates an Environment and never waits.
133
+
134
+ - **Approvals are skipped by default** (`--permission-mode bypassPermissions` for Claude Code, `--force` for Cursor, `--auto` for OpenCode), because an unattended agent that stops at a prompt just sits there. Claude Code refuses bypass mode as root unless it is told it runs in a sandbox, so rig sets `IS_SANDBOX=1` for that run, and authorize pre-accepts Claude's first-use warning dialog (`skipDangerousModePermissionPrompt`), whose default answer is "exit". The Environment has internet access, your tokens and root, so an agent reading untrusted text could be talked into acting on it. Use `--no-auto-approve` to supervise the run; it then pauses at each approval until you attach.
135
+ - **If a live agent is already running**, `rig exec` queues the prompt into it for Claude Code, which runs it after the current turn. rig does this only when Claude's hooks report it idle or working, never while it waits at an approval dialog (typing there would answer the dialog). If it is waiting, the state is unknown, or the agent is OpenCode or Cursor (queue behaviour not yet verified), `rig exec` refuses with the reason; `--restart` replaces the live agent instead. A queued prompt runs under the existing agent's permission mode.
136
+ - The agent's startup is checked: if it exits within a couple of seconds (for example no credentials), `rig exec` prints its output and fails.
137
+
138
+ The prompt reaches the VM on stdin and a private temporary file that is deleted when the agent starts, never on a command line.
139
+
140
+ ### How it works
141
+
142
+ - tmux is installed at provision. The tmux config, two small helper scripts (`rig-agent-state`, `rig-agent-queue`) and Claude Code's state hooks are deployed by `authorize.yml`, so changing them never rebuilds the cached image. The hooks are merged into `~/.claude/settings.json` next to any hooks you added.
143
+ - The hooks record `idle`, `working`, `waiting` or `ended` in `/run/rig/agents/claude.state`; `rig-agent-queue` reads it before pasting.
144
+ - A failed agent leaves its (dead) pane so the error stays readable; the next `rig attach` or `rig exec` replaces it.
145
+ - Agent output is logged to `/var/log/rig/rig-<agent>.log` (the previous run's log is kept as `.prev`).
146
+
105
147
  ## IDEs
106
148
 
107
149
  `rig dev` opens the remote `/workspace`. Default is local editor + Remote-SSH; `--browser` uses code-server on the VM.
@@ -221,7 +263,8 @@ destroy playbooks:
221
263
  | **init** | Scaffold `rig.yml` + `.rig/`. Collect Hetzner creds, repo PATs, agent choices and a key per agent. |
222
264
  | **create** | Boot VM (base/system snapshot). Run provision → configure → authorize → materialize. Snapshot after **configure** only. |
223
265
  | **apply** | Default: authorize → materialize. Flags: `--provision` / `--configure` / `--authorize` / `--materialize` / `--finalize` / `--destroy` (playbooks only; the VM stays). `--tags` is passed to every playbook in the run. |
224
- | **attach** | SSH TTY into `opencode` / `claude` / Cursor `agent` on `/workspace`. `--agent` picks among installed agents. |
266
+ | **attach** | SSH TTY into the agent's [live agent](#live-agents) on `/workspace` (started if needed, joined if running). `--agent` picks among installed agents. |
267
+ | **exec** | Start a live agent with a prompt and return; the work continues unattended. See [Live agents](#live-agents). |
225
268
  | **dev** | Open VS Code/Cursor via Remote-SSH on `/workspace` (or `--browser` for code-server). |
226
269
  | **delete** | Run finalize → destroy playbooks, then delete VM / firewall / SSH key. `--tags` is passed to both playbooks. |
227
270
 
@@ -263,11 +306,12 @@ Global: `-v` playbook tasks and debug · `-vv`/`-vvv`/`-vvvv` ansible verbosity
263
306
  | `init` | | Interactive scaffold |
264
307
  | `create` | `[--name]` `[--provider]` `[--type]` `[--availability-zone]` `[--image]` `[--no-attach]` `[--force-playbooks\|--force-system\|--force-workspace]` | Host defaults from `rig.yml`. `--provider` defaults to `hetzner`. `--type` sets `host.server_type`. `host.type` defaults to `vm`. `--region` aliases `--availability-zone`. |
265
308
  | `apply` | `[name]` `[--provision\|--configure\|--authorize\|--materialize\|--finalize\|--destroy]` `[--tags TAGS]` | Default: authorize then materialize. Each flag runs that playbook (`--provision` also runs configure and authorize; `--materialize` also runs authorize). `--finalize` and `--destroy` do not delete the VM. `--tags` limits every playbook in the run |
266
- | `attach` | `[name]` `[-c\|--continue]` `[-s\|--session ID]` `[--resume [ID]]` `[--agent opencode\|claude\|cursor]` `[-- …agent args]` | Reopens last remembered session by default; `--agent` picks which installed agent |
309
+ | `attach` | `[name]` `[-c\|--continue]` `[-s\|--session ID]` `[--resume [ID]]` `[--agent opencode\|claude\|cursor]` `[--restart]` `[--no-persist]` `[-- …agent args]` | Joins the running live agent, or starts one (reopening the last remembered session). `--restart` replaces it; `--no-persist` runs the agent as the SSH session's own process |
310
+ | `exec` | `PROMPT\|@FILE\|-` `[--name]` `[--agent opencode\|claude\|cursor]` `[--restart]` `[--no-auto-approve]` | Start a live agent with the prompt and return; approvals are skipped unless `--no-auto-approve`. Queues into a running Claude Code when that is safe |
267
311
  | `ssh` | `[name]` `[-- command]` | Shell on the VM in `/workspace`. A command after `--` runs instead of a login shell |
268
312
  | `dev` | `[name]` `[--path /workspace]` `[--browser]` `[--editor code\|cursor\|…]` | Remote-SSH by default; `--editor` opens another IDE from `editor.enabled`. Defaults to `editor.default` |
269
313
  | `list` | | Lists envs, or `No remote environments` |
270
- | `inspect` | `[name]` `[--json]` | Technical details of one env: stored record plus live Hetzner status. Falls back to stored data (flagged stale) if the API is unreachable. Data goes to stdout |
314
+ | `inspect` | `[name]` `[--json]` | Technical details of one env: stored record plus live Hetzner status, and its live agents when the VM is running. Falls back to stored data (flagged stale) if the API is unreachable. Data goes to stdout |
271
315
  | `describe` | `[name]` `[--json]` `[--show-secrets]` | Outputs published by the env's playbooks (see below). Sensitive values are masked unless `--show-secrets` |
272
316
  | `delete` | `[name …]` `[--tags TAGS]` | Runs finalize then destroy playbooks, then deletes the VM; multi-name OK. `--tags` limits both playbooks |
273
317
  | `cache` | `list\|clear` `[--system\|--workspace] [--all] [-y]` | List or clear; unused by default, `--all` includes current |
@@ -80,6 +80,48 @@ rig mcp remove awx
80
80
  - Support files for a server (for example a stdio wrapper script) are not managed by rig: install them from your own playbook (provision, configure or authorize) and point `command` at that path.
81
81
  - The per-agent `.rig/.claude|.cursor|.opencode/mcp.json` files from earlier versions are no longer deployed. If one still declares servers, `rig apply`/`create` and `rig mcp check` warn; move them to `.rig/mcp.json`.
82
82
 
83
+ ## Live agents
84
+
85
+ `rig attach` runs the agent as a **live agent**: a process kept running on the Environment inside its own tmux session (`tmux -L rig`, with a config rig ships, so it never touches a tmux you use yourself). Closing the terminal or losing the connection only detaches; the agent keeps working, and the next `rig attach` joins it.
86
+
87
+ ```bash
88
+ rig attach # start the live agent, or join the running one
89
+ # leave: close the terminal, or detach with Ctrl+b d. Ctrl+C still goes to the agent.
90
+ rig attach --restart # replace it with a fresh process (resumes the same conversation)
91
+ rig attach --no-persist # old behaviour: the agent ends with the SSH session
92
+ ```
93
+
94
+ - One live agent per Agent type per Environment. A second `rig attach` joins the first (both terminals see the same screen). Resume flags (`-c`, `--resume`, `--session`) apply only when a live agent is *started*; joining ignores them with a warning.
95
+ - A bare `rig attach` joins whichever live agent is running. `--agent` picks another.
96
+ - `rig inspect` lists live agents. `rig apply` and `rig delete` warn when there are any: a live agent keeps the credentials and MCP config it started with until `rig attach --restart`, and deleting the Environment ends it.
97
+ - If the agent exits while nobody is attached, tmux has logged its output on the VM, and the next `rig attach` recovers the resume id from that log.
98
+
99
+ ### `rig exec`
100
+
101
+ Start an agent on a task and leave:
102
+
103
+ ```bash
104
+ rig exec "fix the failing tests in /workspace/api"
105
+ rig exec @task.md # prompt from a file
106
+ echo "review the diff" | rig exec - # prompt from stdin
107
+ rig exec --name dev-ab12cd34 --agent claude "..."
108
+ ```
109
+
110
+ `rig exec` starts the live agent with the prompt, prints how to attach, and returns. It never creates an Environment and never waits.
111
+
112
+ - **Approvals are skipped by default** (`--permission-mode bypassPermissions` for Claude Code, `--force` for Cursor, `--auto` for OpenCode), because an unattended agent that stops at a prompt just sits there. Claude Code refuses bypass mode as root unless it is told it runs in a sandbox, so rig sets `IS_SANDBOX=1` for that run, and authorize pre-accepts Claude's first-use warning dialog (`skipDangerousModePermissionPrompt`), whose default answer is "exit". The Environment has internet access, your tokens and root, so an agent reading untrusted text could be talked into acting on it. Use `--no-auto-approve` to supervise the run; it then pauses at each approval until you attach.
113
+ - **If a live agent is already running**, `rig exec` queues the prompt into it for Claude Code, which runs it after the current turn. rig does this only when Claude's hooks report it idle or working, never while it waits at an approval dialog (typing there would answer the dialog). If it is waiting, the state is unknown, or the agent is OpenCode or Cursor (queue behaviour not yet verified), `rig exec` refuses with the reason; `--restart` replaces the live agent instead. A queued prompt runs under the existing agent's permission mode.
114
+ - The agent's startup is checked: if it exits within a couple of seconds (for example no credentials), `rig exec` prints its output and fails.
115
+
116
+ The prompt reaches the VM on stdin and a private temporary file that is deleted when the agent starts, never on a command line.
117
+
118
+ ### How it works
119
+
120
+ - tmux is installed at provision. The tmux config, two small helper scripts (`rig-agent-state`, `rig-agent-queue`) and Claude Code's state hooks are deployed by `authorize.yml`, so changing them never rebuilds the cached image. The hooks are merged into `~/.claude/settings.json` next to any hooks you added.
121
+ - The hooks record `idle`, `working`, `waiting` or `ended` in `/run/rig/agents/claude.state`; `rig-agent-queue` reads it before pasting.
122
+ - A failed agent leaves its (dead) pane so the error stays readable; the next `rig attach` or `rig exec` replaces it.
123
+ - Agent output is logged to `/var/log/rig/rig-<agent>.log` (the previous run's log is kept as `.prev`).
124
+
83
125
  ## IDEs
84
126
 
85
127
  `rig dev` opens the remote `/workspace`. Default is local editor + Remote-SSH; `--browser` uses code-server on the VM.
@@ -199,7 +241,8 @@ destroy playbooks:
199
241
  | **init** | Scaffold `rig.yml` + `.rig/`. Collect Hetzner creds, repo PATs, agent choices and a key per agent. |
200
242
  | **create** | Boot VM (base/system snapshot). Run provision → configure → authorize → materialize. Snapshot after **configure** only. |
201
243
  | **apply** | Default: authorize → materialize. Flags: `--provision` / `--configure` / `--authorize` / `--materialize` / `--finalize` / `--destroy` (playbooks only; the VM stays). `--tags` is passed to every playbook in the run. |
202
- | **attach** | SSH TTY into `opencode` / `claude` / Cursor `agent` on `/workspace`. `--agent` picks among installed agents. |
244
+ | **attach** | SSH TTY into the agent's [live agent](#live-agents) on `/workspace` (started if needed, joined if running). `--agent` picks among installed agents. |
245
+ | **exec** | Start a live agent with a prompt and return; the work continues unattended. See [Live agents](#live-agents). |
203
246
  | **dev** | Open VS Code/Cursor via Remote-SSH on `/workspace` (or `--browser` for code-server). |
204
247
  | **delete** | Run finalize → destroy playbooks, then delete VM / firewall / SSH key. `--tags` is passed to both playbooks. |
205
248
 
@@ -241,11 +284,12 @@ Global: `-v` playbook tasks and debug · `-vv`/`-vvv`/`-vvvv` ansible verbosity
241
284
  | `init` | | Interactive scaffold |
242
285
  | `create` | `[--name]` `[--provider]` `[--type]` `[--availability-zone]` `[--image]` `[--no-attach]` `[--force-playbooks\|--force-system\|--force-workspace]` | Host defaults from `rig.yml`. `--provider` defaults to `hetzner`. `--type` sets `host.server_type`. `host.type` defaults to `vm`. `--region` aliases `--availability-zone`. |
243
286
  | `apply` | `[name]` `[--provision\|--configure\|--authorize\|--materialize\|--finalize\|--destroy]` `[--tags TAGS]` | Default: authorize then materialize. Each flag runs that playbook (`--provision` also runs configure and authorize; `--materialize` also runs authorize). `--finalize` and `--destroy` do not delete the VM. `--tags` limits every playbook in the run |
244
- | `attach` | `[name]` `[-c\|--continue]` `[-s\|--session ID]` `[--resume [ID]]` `[--agent opencode\|claude\|cursor]` `[-- …agent args]` | Reopens last remembered session by default; `--agent` picks which installed agent |
287
+ | `attach` | `[name]` `[-c\|--continue]` `[-s\|--session ID]` `[--resume [ID]]` `[--agent opencode\|claude\|cursor]` `[--restart]` `[--no-persist]` `[-- …agent args]` | Joins the running live agent, or starts one (reopening the last remembered session). `--restart` replaces it; `--no-persist` runs the agent as the SSH session's own process |
288
+ | `exec` | `PROMPT\|@FILE\|-` `[--name]` `[--agent opencode\|claude\|cursor]` `[--restart]` `[--no-auto-approve]` | Start a live agent with the prompt and return; approvals are skipped unless `--no-auto-approve`. Queues into a running Claude Code when that is safe |
245
289
  | `ssh` | `[name]` `[-- command]` | Shell on the VM in `/workspace`. A command after `--` runs instead of a login shell |
246
290
  | `dev` | `[name]` `[--path /workspace]` `[--browser]` `[--editor code\|cursor\|…]` | Remote-SSH by default; `--editor` opens another IDE from `editor.enabled`. Defaults to `editor.default` |
247
291
  | `list` | | Lists envs, or `No remote environments` |
248
- | `inspect` | `[name]` `[--json]` | Technical details of one env: stored record plus live Hetzner status. Falls back to stored data (flagged stale) if the API is unreachable. Data goes to stdout |
292
+ | `inspect` | `[name]` `[--json]` | Technical details of one env: stored record plus live Hetzner status, and its live agents when the VM is running. Falls back to stored data (flagged stale) if the API is unreachable. Data goes to stdout |
249
293
  | `describe` | `[name]` `[--json]` `[--show-secrets]` | Outputs published by the env's playbooks (see below). Sensitive values are masked unless `--show-secrets` |
250
294
  | `delete` | `[name …]` `[--tags TAGS]` | Runs finalize then destroy playbooks, then deletes the VM; multi-name OK. `--tags` limits both playbooks |
251
295
  | `cache` | `list\|clear` `[--system\|--workspace] [--all] [-y]` | List or clear; unused by default, `--all` includes current |
@@ -0,0 +1,20 @@
1
+ # Agents run as live agents in a rig-owned tmux, and `rig exec` starts them unattended
2
+
3
+ `rig attach` used to run the agent as the SSH session's own process, so closing the terminal killed it. Agents now run as live agents in a tmux session on a socket of their own (`tmux -L rig`, a config rig ships), which keeps them alive when the terminal goes away. `rig exec` starts one with a prompt and returns; it skips the agent's approval prompts by default, and queues a prompt into an already-running Claude Code only when Claude's hooks say that is safe.
4
+
5
+ ## Considered Options
6
+
7
+ - **dtach / abduco**: rejected. They keep no screen state and give no scrollback, the redraw on reattach is uncertain, and abduco was not confirmed in Ubuntu 24.04. tmux is in the default repositories (3.4), and Claude Code documents a tmux configuration.
8
+ - **screen**: rejected. No evidence it handles the Agents' key sequences, and Cursor's docs say it intercepts Shift+Enter like tmux does.
9
+ - **Sharing the user's tmux or a default tmux config**: rejected. A separate socket and `-f` file mean rig never changes the behaviour of a tmux someone runs on the VM, and rig can set status bar off and the settings Claude Code recommends.
10
+ - **Queueing by sending keystrokes to every Agent**: rejected. A pasted prompt and Enter would answer an approval or trust dialog, and the Agents differ (Claude queues, OpenCode steers, Cursor is undocumented). Queueing is gated on Claude's hook-written state and supported for Claude Code only; the others refuse with a reason until verified.
11
+ - **Opt-in persistence (`--persist`)**: rejected. Losing an agent's work to a dropped connection is the worse default; `--no-persist` keeps the old behaviour.
12
+ - **A separate flag for unattended approval skipping**: rejected in favour of making it the default for `rig exec`, because an unattended agent that stops at a prompt is not unattended. `--no-auto-approve` opts out.
13
+
14
+ ## Consequences
15
+
16
+ - Claude Code refuses its bypass mode as root, so `rig exec` launches it with `IS_SANDBOX=1`, and authorize pre-accepts its first-use warning dialog. Both were found by running against a real VM, and both would otherwise stop an unattended run silently.
17
+ - An unattended agent can run any command on the Environment, which has internet access, tokens and root. Prompt injection from repository content is a real risk, and `rig exec` says so every time it skips approvals.
18
+ - A live agent keeps the credentials and MCP config it started with; `rig attach --restart` picks up changes. `rig apply` and `rig delete` warn about running live agents but do not stop.
19
+ - tmux is part of the provisioned image, and Claude Code's settings carry rig-owned hooks (merged with the user's, identified by their command path).
20
+ - Agent output is logged on the VM so a resume id survives an unattended exit. The log can contain whatever the agent printed.
@@ -37,6 +37,9 @@ rig = "cli.main:main"
37
37
  [tool.setuptools.packages.find]
38
38
  where = ["src"]
39
39
 
40
+ [tool.setuptools.package-data]
41
+ cli = ["assets/*"]
42
+
40
43
  [tool.setuptools_scm]
41
44
  fallback_version = "0.0.0"
42
45
 
@@ -0,0 +1,88 @@
1
+ """Claude Code hooks for live agents (Ansible filter plugin, standard library only).
2
+
3
+ ``rig exec`` may queue a prompt into a running Claude Code, but typing into a TUI
4
+ that waits at an approval dialog would answer the dialog. These hooks record what
5
+ Claude is doing in a state file that ``rig-agent-queue`` reads first:
6
+
7
+ idle SessionStart, Stop, Notification(idle_prompt)
8
+ working UserPromptSubmit, PreToolUse, PostToolUse
9
+ waiting PermissionRequest, Notification(permission_prompt | agent_needs_input)
10
+ ended SessionEnd
11
+
12
+ Claude has no event for "the user answered the dialog"; the next tool event
13
+ marks the work as resumed.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ from typing import Any
20
+
21
+ STATE_HELPER = "/usr/local/bin/rig-agent-state"
22
+ AGENT = "claude"
23
+
24
+ # (event, matcher or None, state)
25
+ HOOKS: tuple[tuple[str, str | None, str], ...] = (
26
+ ("SessionStart", None, "idle"),
27
+ ("UserPromptSubmit", None, "working"),
28
+ ("PreToolUse", None, "working"),
29
+ ("PostToolUse", None, "working"),
30
+ ("PermissionRequest", None, "waiting"),
31
+ ("Notification", "permission_prompt", "waiting"),
32
+ ("Notification", "agent_needs_input", "waiting"),
33
+ ("Notification", "idle_prompt", "idle"),
34
+ ("Stop", None, "idle"),
35
+ ("SessionEnd", None, "ended"),
36
+ )
37
+
38
+
39
+ def _command(state: str) -> str:
40
+ return f"{STATE_HELPER} {AGENT} {state}"
41
+
42
+
43
+ def _is_rig_handler(handler: Any) -> bool:
44
+ return isinstance(handler, dict) and str(handler.get("command", "")).startswith(STATE_HELPER)
45
+
46
+
47
+ def merge_hooks(settings: Any) -> dict[str, Any]:
48
+ """Return ``settings`` with rig's state hooks installed.
49
+
50
+ Hooks the user added are kept. Earlier rig entries are removed first, so
51
+ running this again (or with a changed event list) does not duplicate them.
52
+ """
53
+ out = copy.deepcopy(settings) if isinstance(settings, dict) else {}
54
+ hooks = out.get("hooks")
55
+ hooks = hooks if isinstance(hooks, dict) else {}
56
+
57
+ for event, groups in list(hooks.items()):
58
+ if not isinstance(groups, list):
59
+ continue
60
+ kept = []
61
+ for group in groups:
62
+ handlers = group.get("hooks") if isinstance(group, dict) else None
63
+ if not isinstance(handlers, list):
64
+ kept.append(group)
65
+ continue
66
+ remaining = [h for h in handlers if not _is_rig_handler(h)]
67
+ if remaining:
68
+ kept.append({**group, "hooks": remaining})
69
+ hooks[event] = kept
70
+
71
+ for event, matcher, state in HOOKS:
72
+ rig_group: dict[str, Any] = {"hooks": [{"type": "command", "command": _command(state)}]}
73
+ if matcher:
74
+ rig_group = {"matcher": matcher, **rig_group}
75
+ hooks.setdefault(event, []).append(rig_group)
76
+
77
+ out["hooks"] = {event: groups for event, groups in hooks.items() if groups}
78
+ return out
79
+
80
+
81
+ def rig_claude_hooks(settings: Any) -> dict[str, Any]:
82
+ """``{{ existing_settings | rig_claude_hooks }}``"""
83
+ return merge_hooks(settings)
84
+
85
+
86
+ class FilterModule:
87
+ def filters(self) -> dict[str, Any]:
88
+ return {"rig_claude_hooks": rig_claude_hooks}
@@ -0,0 +1,33 @@
1
+ #!/bin/sh
2
+ # Queue a prompt (read from stdin) into a running live agent, but only when that is safe.
3
+ # rig-agent-queue AGENT
4
+ # The agent's hooks keep a state file (see rig-agent-state). Typing into a TUI that is
5
+ # waiting at an approval dialog would answer the dialog, so the prompt is delivered only
6
+ # when the agent is idle or working. Exit status:
7
+ # 0 queued 10 waiting for approval 11 state unknown (no hooks / no state)
8
+ # 12 no live agent 13 delivery failed
9
+ set -u
10
+ agent="${1:?usage: rig-agent-queue AGENT}"
11
+ socket="${RIG_TMUX_SOCKET:-rig}"
12
+ conf="${RIG_TMUX_CONF:-/etc/rig/tmux.conf}"
13
+ state_dir="${RIG_STATE_DIR:-/run/rig/agents}"
14
+ session="rig-$agent"
15
+ tmux_cmd() { tmux -L "$socket" -f "$conf" "$@"; }
16
+
17
+ tmux_cmd has-session -t "$session" 2>/dev/null || exit 12
18
+ [ "$(tmux_cmd list-panes -t "$session" -F '#{pane_dead}' 2>/dev/null | head -n 1)" = "0" ] || exit 12
19
+
20
+ state_file="$state_dir/$agent.state"
21
+ [ -r "$state_file" ] || exit 11
22
+ state="$(cut -d' ' -f1 < "$state_file")"
23
+ case "$state" in
24
+ idle|working) ;;
25
+ waiting) exit 10 ;;
26
+ *) exit 11 ;;
27
+ esac
28
+
29
+ buffer="rig-queue-$$"
30
+ tmux_cmd load-buffer -b "$buffer" - || exit 13
31
+ # -p: bracketed paste, so newlines stay part of one message; -d: drop the buffer after.
32
+ tmux_cmd paste-buffer -p -d -b "$buffer" -t "$session" || exit 13
33
+ tmux_cmd send-keys -t "$session" Enter || exit 13
@@ -0,0 +1,12 @@
1
+ #!/bin/sh
2
+ # Record what a coding agent is doing, for `rig exec` to read before it queues a prompt.
3
+ # Called by the agent's hooks (see authorize.yml): rig-agent-state AGENT STATE
4
+ # STATE is one of: idle working waiting ended. Writes "STATE EPOCH" to the state file.
5
+ set -eu
6
+ agent="${1:?usage: rig-agent-state AGENT STATE}"
7
+ state="${2:?usage: rig-agent-state AGENT STATE}"
8
+ dir="${RIG_STATE_DIR:-/run/rig/agents}"
9
+ mkdir -p "$dir"
10
+ tmp="$dir/.$agent.$$"
11
+ printf '%s %s\n' "$state" "$(date +%s)" > "$tmp"
12
+ mv -f "$tmp" "$dir/$agent.state"
@@ -0,0 +1,27 @@
1
+ # rig's tmux configuration for live agents. Used only with `tmux -L rig -f <this file>`,
2
+ # so it never touches a tmux the user runs themselves. Deployed by authorize.yml.
3
+
4
+ # The agent's TUI should look exactly as it does outside tmux.
5
+ set -g status off
6
+ set -g default-shell /bin/bash
7
+ set -g default-terminal "tmux-256color"
8
+ set -ga terminal-overrides ",xterm-256color:RGB"
9
+
10
+ # Recommended by Claude Code's docs (https://code.claude.com/docs/en/terminal-config):
11
+ # without these Shift+Enter submits and desktop notifications never reach the terminal.
12
+ set -g allow-passthrough on
13
+ set -g focus-events on
14
+ set -s extended-keys on
15
+ set -as terminal-features 'xterm*:extkeys'
16
+
17
+ # A smaller scrollback keeps Cursor's reattach redraw short.
18
+ set -g history-limit 1000
19
+ set -sg escape-time 10
20
+
21
+ # Several terminals can join one live agent; follow the most recently active one.
22
+ set -g window-size latest
23
+ set -g aggressive-resize on
24
+
25
+ # Keep the pane when the agent fails so its error stays readable. `rig attach` and
26
+ # `rig exec` replace a dead pane the next time.
27
+ set -g remain-on-exit failed
@@ -0,0 +1,238 @@
1
+ """Live agents: an Agent's process kept running on an Environment.
2
+
3
+ A live agent is a tmux session on a socket of its own (``tmux -L rig``) with a
4
+ config file that rig ships, so it never touches a tmux the user runs. The agent
5
+ keeps running when the SSH connection drops or the user detaches.
6
+
7
+ * ``rig attach`` starts the live agent or joins the existing one.
8
+ * ``rig exec`` starts one with a prompt (unattended), or queues the prompt into
9
+ a running Claude Code when its hooks say that is safe.
10
+
11
+ The helper scripts and config under ``cli/assets`` are deployed by authorize.yml.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import shlex
18
+ from dataclasses import dataclass
19
+
20
+ from cli.agents import SUPPORTED_AGENTS
21
+
22
+ TMUX_SOCKET = "rig"
23
+ TMUX_CONF = "/etc/rig/tmux.conf"
24
+ LOG_DIR = "/var/log/rig"
25
+ STATE_DIR = "/run/rig/agents"
26
+ QUEUE_HELPER = "/usr/local/bin/rig-agent-queue"
27
+ STATE_HELPER = "/usr/local/bin/rig-agent-state"
28
+ ASSETS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
29
+
30
+ # Flags that make an unattended agent run without stopping at approval prompts.
31
+ AUTO_APPROVE_FLAGS: dict[str, list[str]] = {
32
+ "claude": ["--permission-mode", "bypassPermissions"],
33
+ "cursor": ["--force"],
34
+ "opencode": ["--auto"],
35
+ }
36
+
37
+ # Claude Code refuses its bypass mode as root ("cannot be used with root/sudo privileges")
38
+ # unless it is told it runs in a sandbox. Verified on a real VM: with IS_SANDBOX=1 it works.
39
+ # Environments are disposable VMs, and `rig exec` skips approvals by default.
40
+ AUTO_APPROVE_ENV: dict[str, dict[str, str]] = {"claude": {"IS_SANDBOX": "1"}}
41
+
42
+
43
+ def auto_approve_exports(agent: str) -> str:
44
+ """Shell that exports what an agent needs to skip approvals when run as root."""
45
+ return "".join(f"export {k}={shlex.quote(v)}; " for k, v in AUTO_APPROVE_ENV.get(agent, {}).items())
46
+
47
+
48
+ # Exit status of rig-agent-queue -> why a prompt could not be queued.
49
+ QUEUE_RESULTS = {
50
+ 0: "queued",
51
+ 10: "waiting for approval",
52
+ 11: "state unknown",
53
+ 12: "no live agent",
54
+ 13: "delivery failed",
55
+ }
56
+ QUEUE_REFUSALS = {
57
+ 10: "it is waiting for approval; attach to answer it first",
58
+ 11: "its state is unknown (the Environment predates live-agent hooks; run `rig apply --authorize`)",
59
+ 12: "no live agent is running",
60
+ 13: "tmux could not deliver the prompt",
61
+ }
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class LiveAgent:
66
+ agent: str
67
+ dead: bool
68
+ created: int
69
+ attached: int
70
+
71
+ def describe(self, now: int) -> str:
72
+ if self.dead:
73
+ return f"{self.agent} (exited with an error)"
74
+ minutes = max(0, now - self.created) // 60
75
+ age = f"{minutes}m" if minutes < 120 else f"{minutes // 60}h"
76
+ clients = f"{self.attached} attached" if self.attached else "detached"
77
+ return f"{self.agent} (running {age}, {clients})"
78
+
79
+
80
+ def session_name(agent: str) -> str:
81
+ return f"rig-{agent}"
82
+
83
+
84
+ def _tmux(socket: str, conf: str) -> str:
85
+ return f"tmux -L {shlex.quote(socket)} -f {shlex.quote(conf)}"
86
+
87
+
88
+ def ensure_session_script(
89
+ agent: str,
90
+ launch_cmd: str,
91
+ *,
92
+ restart: bool = False,
93
+ socket: str = TMUX_SOCKET,
94
+ conf: str = TMUX_CONF,
95
+ log_dir: str = LOG_DIR,
96
+ ) -> str:
97
+ """Shell that makes sure the agent's session exists, starting it when needed.
98
+
99
+ An existing healthy session is left alone (a later attach joins it). A dead
100
+ pane (the agent failed) and ``restart`` both replace it. The previous run's
101
+ output log is kept as ``.prev`` and the new one is recorded by tmux so the
102
+ resume id survives an unattended exit.
103
+ """
104
+ name = session_name(agent)
105
+ tmux = _tmux(socket, conf)
106
+ log = f"{log_dir}/{name}.log"
107
+ lines = [
108
+ "set -u",
109
+ f"mkdir -p {shlex.quote(log_dir)}",
110
+ f"S={shlex.quote(name)}",
111
+ f"LOG={shlex.quote(log)}",
112
+ ]
113
+ if restart:
114
+ lines.append(f'{tmux} kill-session -t "$S" 2>/dev/null || true')
115
+ lines += [
116
+ f'if {tmux} has-session -t "$S" 2>/dev/null; then',
117
+ f' if [ "$({tmux} list-panes -t "$S" -F \'#{{pane_dead}}\' | head -n 1)" = 1 ]; then',
118
+ f' {tmux} kill-session -t "$S"',
119
+ " fi",
120
+ "fi",
121
+ f'if ! {tmux} has-session -t "$S" 2>/dev/null; then',
122
+ ' [ -f "$LOG" ] && mv -f "$LOG" "$LOG.prev"',
123
+ ' : > "$LOG"',
124
+ f' {tmux} new-session -d -s "$S" -x 200 -y 50 {shlex.quote(launch_cmd)} || exit 1',
125
+ # Best effort: an agent that dies at once leaves a dead pane to pipe.
126
+ f' {tmux} pipe-pane -o -t "$S" "cat >> $LOG" 2>/dev/null || true',
127
+ "fi",
128
+ ]
129
+ return "\n".join(lines)
130
+
131
+
132
+ def attach_script(agent: str, launch_cmd: str, **kwargs: object) -> str:
133
+ """Ensure the session, then attach this terminal to it (needs a tty)."""
134
+ socket = str(kwargs.get("socket", TMUX_SOCKET))
135
+ conf = str(kwargs.get("conf", TMUX_CONF))
136
+ body = ensure_session_script(agent, launch_cmd, **kwargs) # type: ignore[arg-type]
137
+ return f'{body}\nexec {_tmux(socket, conf)} attach-session -t "{session_name(agent)}"'
138
+
139
+
140
+ def verify_started_script(
141
+ agent: str, *, socket: str = TMUX_SOCKET, conf: str = TMUX_CONF, wait_seconds: int = 2
142
+ ) -> str:
143
+ """Shell that waits briefly, then fails (status 3) with the pane's text if the agent already died.
144
+
145
+ Catches the common unattended failures (no credentials, a bad flag) that would
146
+ otherwise look like a successful start.
147
+ """
148
+ name = shlex.quote(session_name(agent))
149
+ tmux = _tmux(socket, conf)
150
+ return "\n".join(
151
+ [
152
+ f"sleep {int(wait_seconds)}",
153
+ f"if [ \"$({tmux} list-panes -t {name} -F '#{{pane_dead}}' 2>/dev/null | head -n 1)\" = 1 ]; then",
154
+ f" {tmux} capture-pane -p -S - -t {name} | grep -v '^$' | tail -n 20",
155
+ " exit 3",
156
+ "fi",
157
+ ]
158
+ )
159
+
160
+
161
+ def list_script(*, socket: str = TMUX_SOCKET, conf: str = TMUX_CONF) -> str:
162
+ """Shell printing one line per live agent: name|dead|created|attached."""
163
+ fmt = "#{session_name}|#{pane_dead}|#{session_created}|#{session_attached}"
164
+ return f"{_tmux(socket, conf)} list-panes -a -F {shlex.quote(fmt)} 2>/dev/null || true"
165
+
166
+
167
+ def parse_live_agents(output: str) -> list[LiveAgent]:
168
+ """Parse :func:`list_script` output; ignores sessions that are not rig's."""
169
+ found: dict[str, LiveAgent] = {}
170
+ for line in (output or "").splitlines():
171
+ parts = line.strip().split("|")
172
+ if len(parts) != 4 or not parts[0].startswith("rig-"):
173
+ continue
174
+ agent = parts[0][len("rig-") :]
175
+ if agent not in SUPPORTED_AGENTS:
176
+ continue
177
+ try:
178
+ created, attached = int(parts[2]), int(parts[3])
179
+ except ValueError:
180
+ continue
181
+ found[agent] = LiveAgent(agent, parts[1] == "1", created, attached)
182
+ return sorted(found.values(), key=lambda la: la.agent)
183
+
184
+
185
+ def running_agents(live: list[LiveAgent]) -> list[str]:
186
+ """Agent types with a healthy (not dead) live agent."""
187
+ return [la.agent for la in live if not la.dead]
188
+
189
+
190
+ def recent_log_script(agent: str, *, log_dir: str = LOG_DIR, max_bytes: int = 65536) -> str:
191
+ """Shell printing the tail of the agent's recorded output (empty when none)."""
192
+ log = shlex.quote(f"{log_dir}/{session_name(agent)}.log")
193
+ return f"tail -c {int(max_bytes)} {log} 2>/dev/null || true"
194
+
195
+
196
+ def queue_script(agent: str, *, helper: str = QUEUE_HELPER) -> str:
197
+ """Shell reading a prompt on stdin and queueing it via the helper."""
198
+ return f"{shlex.quote(helper)} {shlex.quote(agent)}"
199
+
200
+
201
+ def upload_prompt_script() -> str:
202
+ """Shell that stores stdin in a private temp file and prints its path."""
203
+ return 'umask 077; f="$(mktemp /tmp/rig-prompt.XXXXXX)" && cat > "$f" && printf "%s\\n" "$f"'
204
+
205
+
206
+ def prompt_launch_fragments(agent: str, prompt_file: str, auto_approve: bool) -> tuple[str, str, str]:
207
+ """Pieces to splice into an agent's launch command for an unattended prompt.
208
+
209
+ Returns ``(lead, flags, trailer)``: ``lead`` reads and deletes the prompt
210
+ file into ``$p`` before the agent starts, ``flags`` are inserted after the
211
+ agent binary, and ``trailer`` passes the prompt (OpenCode needs ``--prompt``;
212
+ Claude Code and Cursor take it as the positional argument).
213
+ """
214
+ lead = f'p="$(cat {shlex.quote(prompt_file)})"; rm -f {shlex.quote(prompt_file)}; '
215
+ flags = ""
216
+ if auto_approve:
217
+ flags = " " + " ".join(shlex.quote(f) for f in AUTO_APPROVE_FLAGS[agent])
218
+ trailer = ' --prompt "$p"' if agent == "opencode" else ' "$p"'
219
+ return lead, flags, trailer
220
+
221
+
222
+ def read_prompt(value: str, *, stdin_text: str | None = None) -> str:
223
+ """Resolve ``rig exec``'s prompt argument: text, ``@file`` or ``-`` (stdin)."""
224
+ if value == "-":
225
+ text = stdin_text if stdin_text is not None else ""
226
+ elif value.startswith("@") and len(value) > 1:
227
+ path = os.path.expanduser(value[1:])
228
+ try:
229
+ with open(path, encoding="utf-8") as handle:
230
+ text = handle.read()
231
+ except OSError as exc:
232
+ raise ValueError(f"cannot read prompt file {path}: {exc.strerror or exc}") from exc
233
+ else:
234
+ text = value
235
+ text = text.strip("\n")
236
+ if not text.strip():
237
+ raise ValueError("the prompt is empty")
238
+ return text