herdr-turn-coordinator 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KarthusLorin
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.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # Herdr Turn Coordinator
2
+
3
+ Run one interactive coding-agent turn in Herdr without spending parent-model tokens on status polling.
4
+
5
+ The plugin keeps the downstream agent's native TUI, creates a dedicated visible pane, waits in a local supervisor process, reads the final output once, and leaves the pane open for human takeover.
6
+
7
+ ## Why
8
+
9
+ `herdr agent prompt --wait` can report `agent_prompt_stalled` even when a prompt was delivered and the agent continues working. A parent model that recovers by repeatedly calling `agent get`, `agent read`, or `agent wait` pays for every observation as another model turn.
10
+
11
+ Turn Coordinator moves that recovery loop into an ordinary local process. On a false stall it confirms delivery from a new visible prompt anchor or a recovered working state, then waits for lifecycle settlement. If only a 15-second pane-revision quiet period is available, it returns `unknown` for human takeover instead of guessing that the turn completed. It never resends the same prompt.
12
+
13
+ ## Requirements
14
+
15
+ - Herdr 0.8.0 or newer
16
+ - Python 3.9 or newer
17
+ - macOS or Linux
18
+ - A Herdr-supported interactive agent CLI
19
+
20
+ ## Install
21
+
22
+ Recommended Herdr plugin installation:
23
+
24
+ ```sh
25
+ herdr plugin install KarthusLorin/herdr-turn-coordinator
26
+ herdr plugin action invoke karthuslorin.turn-coordinator.install-cli
27
+ herdr plugin log list --plugin karthuslorin.turn-coordinator --limit 1
28
+ herdr-turn doctor
29
+ ```
30
+
31
+ Plugin actions are asynchronous. Confirm the install action log says `succeeded` before running `doctor`, and ensure `~/.local/bin` is on `PATH`.
32
+
33
+ Alternatively, install the CLI from npm:
34
+
35
+ ```sh
36
+ npm install --global herdr-turn-coordinator --registry=https://registry.npmjs.org/
37
+ herdr-turn doctor
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ Start a new interactive agent in a dedicated visible pane:
43
+
44
+ ```sh
45
+ herdr-turn run \
46
+ --kind kimi \
47
+ --name reviewer \
48
+ --prompt "Review the current diff and report only actionable findings."
49
+ ```
50
+
51
+ Continue an existing settled agent:
52
+
53
+ ```sh
54
+ herdr-turn prompt \
55
+ --target reviewer \
56
+ --prompt "Now summarize the top three risks."
57
+ ```
58
+
59
+ Both commands print one JSON result. The created pane stays open and the agent remains fully interactive.
60
+
61
+ ## Suggested agent instruction
62
+
63
+ ```md
64
+ Inside Herdr, preserve downstream agents' native interactive TUIs. Use one
65
+ blocking `herdr-turn run --kind <kind> --name <name> --prompt <prompt>` call,
66
+ then consume its single final JSON result. Do not poll Herdr from model turns.
67
+ ```
68
+
69
+ ## Behavior
70
+
71
+ - Preserves the native interactive TUI; it never substitutes `kimi -p`, `grok --single`, or another batch mode.
72
+ - Rejects prompts to agents reported as `working`, `blocked`, or `unknown`.
73
+ - Uses Herdr's native blocking wait first.
74
+ - On `agent_prompt_stalled`, falls back only after a revision advance plus a new prompt anchor or a recovered `working` state.
75
+ - Uses native lifecycle waiting once Herdr reports `working`; otherwise a local 15-second revision-quiet heuristic returns `unknown` without declaring success.
76
+ - Reads history once only after confirmed completion. Blocked or uncertain turns read the visible screen without scrolling the live TUI.
77
+ - Never resends a stalled prompt automatically.
78
+
79
+ ## Local A/B result
80
+
81
+ One parent-Codex-to-Kimi review task produced the following result on macOS with Herdr 0.8.0:
82
+
83
+ | Metric | Before | With plugin | Change |
84
+ | --- | ---: | ---: | ---: |
85
+ | Input tokens | 357,074 | 124,276 | -65.2% |
86
+ | Parent tool calls | 15 | 4 | -73.3% |
87
+ | Output tokens | 2,950 | 1,638 | -44.5% |
88
+ | Wall time | 108 s | 62 s | -42.6% |
89
+
90
+ This is a single local comparison, not a universal performance guarantee.
91
+
92
+ ## Check
93
+
94
+ ```sh
95
+ python3 -m unittest -v
96
+ ```
97
+
98
+ ## Scope
99
+
100
+ This plugin coordinates interactive Herdr agents. Outside Herdr, use the downstream CLI's normal blocking non-interactive mode. It does not modify Herdr, replace agent TUIs, or require an npm package.
101
+
102
+ ## Uninstall
103
+
104
+ ```sh
105
+ herdr plugin action invoke karthuslorin.turn-coordinator.uninstall-cli
106
+ herdr plugin log list --plugin karthuslorin.turn-coordinator --limit 1
107
+ herdr plugin uninstall karthuslorin.turn-coordinator
108
+ ```
109
+
110
+ For an npm installation:
111
+
112
+ ```sh
113
+ npm uninstall --global herdr-turn-coordinator --registry=https://registry.npmjs.org/
114
+ ```
115
+
116
+ ## License
117
+
118
+ MIT
@@ -0,0 +1,24 @@
1
+ id = "karthuslorin.turn-coordinator"
2
+ name = "Turn Coordinator"
3
+ version = "0.1.0"
4
+ min_herdr_version = "0.8.0"
5
+ description = "Run one interactive agent turn without model-driven polling"
6
+ platforms = ["macos", "linux"]
7
+
8
+ [[actions]]
9
+ id = "install-cli"
10
+ title = "Install herdr-turn CLI"
11
+ contexts = ["workspace"]
12
+ command = ["python3", "herdr_turn.py", "install-cli"]
13
+
14
+ [[actions]]
15
+ id = "uninstall-cli"
16
+ title = "Uninstall herdr-turn CLI"
17
+ contexts = ["workspace"]
18
+ command = ["python3", "herdr_turn.py", "uninstall-cli"]
19
+
20
+ [[actions]]
21
+ id = "doctor"
22
+ title = "Check turn coordinator"
23
+ contexts = ["workspace"]
24
+ command = ["python3", "herdr_turn.py", "doctor"]
package/herdr_turn.py ADDED
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import os
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+
11
+
12
+ HERDR = os.environ.get("HERDR_BIN_PATH", "herdr")
13
+ CLI_PATH = Path.home() / ".local" / "bin" / "herdr-turn"
14
+
15
+
16
+ def call(*args):
17
+ return subprocess.run(
18
+ [HERDR, *args], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
19
+ )
20
+
21
+
22
+ def payload(result):
23
+ raw = result.stdout.strip() or result.stderr.strip()
24
+ try:
25
+ return json.loads(raw)
26
+ except json.JSONDecodeError:
27
+ return {"raw": raw, "exit_code": result.returncode}
28
+
29
+
30
+ def fail(message, **details):
31
+ print(json.dumps({"ok": False, "error": message, **details}, ensure_ascii=False))
32
+ raise SystemExit(1)
33
+
34
+
35
+ def install_cli():
36
+ source = Path(__file__).resolve()
37
+ CLI_PATH.parent.mkdir(parents=True, exist_ok=True)
38
+ if CLI_PATH.is_symlink():
39
+ if CLI_PATH.resolve(strict=False) == source:
40
+ print(json.dumps({"ok": True, "cli": str(CLI_PATH)}, ensure_ascii=False))
41
+ return
42
+ CLI_PATH.unlink()
43
+ elif CLI_PATH.exists():
44
+ fail("cli_path_exists", path=str(CLI_PATH))
45
+ CLI_PATH.symlink_to(source)
46
+ print(json.dumps({"ok": True, "cli": str(CLI_PATH)}, ensure_ascii=False))
47
+
48
+
49
+ def uninstall_cli():
50
+ source = Path(__file__).resolve()
51
+ removed = False
52
+ if CLI_PATH.is_symlink() and CLI_PATH.resolve(strict=False) == source:
53
+ CLI_PATH.unlink()
54
+ removed = True
55
+ elif CLI_PATH.is_symlink() and not CLI_PATH.exists():
56
+ CLI_PATH.unlink()
57
+ removed = True
58
+ print(json.dumps({"ok": True, "cli": str(CLI_PATH), "removed": removed}, ensure_ascii=False))
59
+
60
+
61
+ def read_once(target, lines):
62
+ result = call("agent", "read", target, "--source", "recent-unwrapped", "--lines", str(lines))
63
+ if result.returncode:
64
+ fail("agent_read_failed", detail=payload(result))
65
+ return result.stdout.rstrip()
66
+
67
+
68
+ def read_visible(target):
69
+ result = call("agent", "read", target, "--source", "visible")
70
+ if result.returncode:
71
+ fail("agent_read_failed", detail=payload(result))
72
+ return result.stdout.rstrip()
73
+
74
+
75
+ def normalize_screen(text):
76
+ return re.sub(r"[\s│┃┆┇┊┋┌┐└┘╭╮╰╯]+", "", text)
77
+
78
+
79
+ def contains_new_prompt(before, after, prompt):
80
+ before = normalize_screen(before)
81
+ after = normalize_screen(after)
82
+ prompt = normalize_screen(prompt)
83
+ for offset in range(0, min(len(prompt), 120), 12):
84
+ anchor = prompt[offset:offset + 24]
85
+ if len(anchor) >= 12 and anchor not in before and anchor in after:
86
+ return True
87
+ return False
88
+
89
+
90
+ def wait_for_quiet(target, pane_id, delivered_revision, timeout):
91
+ deadline = time.monotonic() + max(0, timeout - 5000) / 1000
92
+ revision = delivered_revision
93
+ last_change = time.monotonic()
94
+ while time.monotonic() < deadline:
95
+ pane = call("pane", "get", pane_id)
96
+ if pane.returncode:
97
+ fail("pane_get_failed", detail=payload(pane))
98
+ info = payload(pane).get("result", {}).get("pane", {})
99
+ status = info.get("agent_status")
100
+ if status == "blocked":
101
+ return "blocked", "blocked"
102
+ if status == "working":
103
+ remaining = min(max(int((deadline - time.monotonic()) * 1000), 3001), 300000)
104
+ settled = call("agent", "wait", target, "--timeout", str(remaining))
105
+ if settled.returncode:
106
+ fail("agent_wait_failed", detail=payload(settled))
107
+ return (
108
+ payload(settled).get("result", {}).get("agent", {}).get("agent_status", "idle"),
109
+ "native_wait",
110
+ )
111
+ current = info.get("revision", revision)
112
+ if current != revision:
113
+ revision = current
114
+ last_change = time.monotonic()
115
+ if time.monotonic() - last_change >= 15:
116
+ return "unknown", "output_quiet"
117
+ time.sleep(0.5)
118
+ fail("agent_quiet_timeout", pane_id=pane_id, revision=revision)
119
+
120
+
121
+ def submit(target, prompt, timeout, lines, baseline_revision):
122
+ before = call("agent", "read", target, "--source", "visible")
123
+ result = call("agent", "prompt", target, prompt, "--wait", "--timeout", str(timeout))
124
+ if result.returncode:
125
+ state = call("agent", "get", target)
126
+ text = call("agent", "read", target, "--source", "visible")
127
+ prompt_error = payload(result)
128
+ agent = payload(state).get("result", {}).get("agent", {})
129
+ status_confirms_delivery = agent.get("agent_status") in {"working", "blocked"}
130
+ screen_confirms_delivery = (
131
+ before.returncode == 0
132
+ and text.returncode == 0
133
+ and contains_new_prompt(before.stdout, text.stdout, prompt)
134
+ )
135
+ if (
136
+ prompt_error.get("error", {}).get("code") == "agent_prompt_stalled"
137
+ and agent.get("revision", baseline_revision) > baseline_revision
138
+ and (status_confirms_delivery or screen_confirms_delivery)
139
+ ):
140
+ status, wait_mode = wait_for_quiet(target, agent["pane_id"], agent["revision"], timeout)
141
+ final_text = read_once(target, lines) if wait_mode == "native_wait" and status in {"idle", "done"} else read_visible(target)
142
+ print(json.dumps({
143
+ "ok": status in {"idle", "done"},
144
+ "pane_id": agent["pane_id"],
145
+ "agent_name": agent.get("name"),
146
+ "agent_status": status,
147
+ "wait_mode": wait_mode,
148
+ "text": final_text,
149
+ }, ensure_ascii=False))
150
+ raise SystemExit(0 if status in {"idle", "done"} else 2)
151
+ fail(
152
+ "agent_prompt_failed",
153
+ prompt=prompt_error,
154
+ state=payload(state),
155
+ before=payload(before),
156
+ text=payload(text),
157
+ )
158
+
159
+ info = payload(result).get("result", {}).get("agent", {})
160
+ status = info.get("agent_status")
161
+ text = read_once(target, lines) if status in {"idle", "done"} else read_visible(target)
162
+ output = {
163
+ "ok": status in {"idle", "done"},
164
+ "pane_id": info.get("pane_id"),
165
+ "agent_name": info.get("name"),
166
+ "agent_status": status,
167
+ "text": text,
168
+ }
169
+ print(json.dumps(output, ensure_ascii=False))
170
+ raise SystemExit(0 if output["ok"] else 2)
171
+
172
+
173
+ def start_agent(kind, name, timeout):
174
+ layout = call("pane", "layout", "--pane", os.environ["HERDR_PANE_ID"])
175
+ if layout.returncode:
176
+ fail("pane_layout_failed", detail=payload(layout))
177
+ area = payload(layout)["result"]["layout"]["area"]
178
+ direction = "right" if area["width"] >= 120 and area["width"] >= area["height"] * 2 else "down"
179
+
180
+ split = call(
181
+ "pane", "split", "--current", "--direction", direction,
182
+ "--cwd", os.getcwd(), "--no-focus",
183
+ )
184
+ if split.returncode:
185
+ fail("pane_split_failed", detail=payload(split))
186
+ pane_id = payload(split)["result"]["pane"]["pane_id"]
187
+
188
+ start_timeout = str(min(max(timeout, 3001), 300000))
189
+ started = call("agent", "start", name, "--kind", kind, "--pane", pane_id, "--timeout", start_timeout)
190
+ if started.returncode and payload(started).get("error", {}).get("code") == "agent_pane_busy":
191
+ process = call("pane", "process-info", "--pane", pane_id)
192
+ # ponytail: one bounded retry covers shell startup; use a shell-ready event if Herdr adds one.
193
+ if process.returncode == 0:
194
+ time.sleep(0.2)
195
+ started = call("agent", "start", name, "--kind", kind, "--pane", pane_id, "--timeout", start_timeout)
196
+ if started.returncode:
197
+ call("pane", "close", pane_id)
198
+ fail("agent_start_failed", pane_id=pane_id, detail=payload(started))
199
+ agent = payload(started).get("result", {}).get("agent", {})
200
+ return pane_id, agent.get("revision", 0)
201
+
202
+
203
+ def main():
204
+ parser = argparse.ArgumentParser(prog="herdr-turn")
205
+ sub = parser.add_subparsers(dest="command", required=True)
206
+
207
+ run = sub.add_parser("run")
208
+ run.add_argument("--kind", required=True)
209
+ run.add_argument("--prompt", required=True)
210
+ run.add_argument("--name")
211
+ run.add_argument("--timeout", type=int, default=300000)
212
+ run.add_argument("--lines", type=int, default=160)
213
+
214
+ prompt = sub.add_parser("prompt")
215
+ prompt.add_argument("--target", required=True)
216
+ prompt.add_argument("--prompt", required=True)
217
+ prompt.add_argument("--timeout", type=int, default=300000)
218
+ prompt.add_argument("--lines", type=int, default=160)
219
+
220
+ sub.add_parser("doctor")
221
+ sub.add_parser("install-cli")
222
+ sub.add_parser("uninstall-cli")
223
+ args = parser.parse_args()
224
+
225
+ if args.command == "install-cli":
226
+ install_cli()
227
+ return
228
+ if args.command == "uninstall-cli":
229
+ uninstall_cli()
230
+ return
231
+
232
+ if args.command == "doctor":
233
+ result = call("--version")
234
+ if result.returncode:
235
+ fail("herdr_unavailable", detail=payload(result))
236
+ source = Path(__file__).resolve()
237
+ cli = shutil.which("herdr-turn")
238
+ installed = bool(cli) and Path(cli).resolve(strict=False) == source
239
+ print(json.dumps({
240
+ "ok": installed,
241
+ "herdr": result.stdout.strip(),
242
+ "cli": cli,
243
+ "installed": installed,
244
+ }, ensure_ascii=False))
245
+ raise SystemExit(0 if installed else 1)
246
+
247
+ if os.environ.get("HERDR_ENV") != "1":
248
+ fail("not_inside_herdr")
249
+
250
+ if args.command == "run":
251
+ name = args.name or f"{args.kind}turn_{os.getpid()}"
252
+ _, revision = start_agent(args.kind, name, args.timeout)
253
+ submit(name, args.prompt, args.timeout, args.lines, revision)
254
+
255
+ state = call("agent", "get", args.target)
256
+ if state.returncode:
257
+ fail("agent_get_failed", detail=payload(state))
258
+ agent = payload(state).get("result", {}).get("agent", {})
259
+ if agent.get("agent_status") not in {"idle", "done"}:
260
+ fail("agent_not_settled", agent_status=agent.get("agent_status"))
261
+ submit(args.target, args.prompt, args.timeout, args.lines, agent.get("revision", 0))
262
+
263
+
264
+ if __name__ == "__main__":
265
+ main()
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "herdr-turn-coordinator",
3
+ "version": "0.1.0",
4
+ "description": "Preserve interactive Herdr agent TUIs without model-driven status polling",
5
+ "license": "MIT",
6
+ "author": "KarthusLorin",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/KarthusLorin/herdr-turn-coordinator.git"
10
+ },
11
+ "homepage": "https://github.com/KarthusLorin/herdr-turn-coordinator#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/KarthusLorin/herdr-turn-coordinator/issues"
14
+ },
15
+ "bin": {
16
+ "herdr-turn": "herdr_turn.py"
17
+ },
18
+ "files": [
19
+ "herdr_turn.py",
20
+ "herdr-plugin.toml"
21
+ ],
22
+ "os": [
23
+ "darwin",
24
+ "linux"
25
+ ],
26
+ "scripts": {
27
+ "test": "python3 -m unittest -v",
28
+ "prepublishOnly": "npm test"
29
+ },
30
+ "keywords": [
31
+ "herdr",
32
+ "ai-agents",
33
+ "cli",
34
+ "terminal"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "registry": "https://registry.npmjs.org/"
39
+ }
40
+ }