@bom0792/herdgate 0.9.29 → 0.9.31
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/.agents/skills/herdr/SKILL.md +81 -0
- package/.agents/skills/herdr/herdr_pi.py +272 -0
- package/.agents/skills/herdr/profiles.example.toml +18 -0
- package/.agents/skills/herdr-advisor/SKILL.md +12 -0
- package/.agents/skills/herdr-committee/SKILL.md +13 -0
- package/.agents/skills/herdr-handoff/SKILL.md +19 -0
- package/.agents/skills/herdr-help/SKILL.md +14 -0
- package/.agents/skills/herdr-plugin/SKILL.md +21 -0
- package/DEPLOY.md +27 -0
- package/README.md +43 -0
- package/bin/herdgate.mjs +6 -1
- package/bin/home-tui.mjs +2 -0
- package/bin/pi-skills.mjs +99 -0
- package/dist-readme.md +6 -1
- package/package.json +5 -2
- package/plugin/server/ssh.mjs +12 -4
- package/scripts/bench-mobile-tui.mjs +246 -0
- package/scripts/install-pi-skills.mjs +4 -0
- package/src/host/mobile-tui.ts +11 -1
- package/windows/install-cli.mjs +15 -5
- package/windows/setup-tui.mjs +1 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr
|
|
3
|
+
description: 'Vận hành Herdr TUI qua CLI: xem hoặc điều khiển pane, tab, workspace, worktree, agent, session và máy SSH. Chỉ dùng khi người dùng yêu cầu dùng Herdr; không tự khởi chạy agent hoặc thay đổi phiên chỉ vì có thể chạy song song.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr TUI
|
|
7
|
+
|
|
8
|
+
Herdr quản lý terminal. Workspace chứa tab, tab chứa pane; agent là tiến trình được Herdr nhận diện trong pane, không phải thực thể điều phối độc lập kiểu Paseo. Dùng skill này cho thao tác runtime hoặc làm nền cho advisor/committee/handoff. Hỏi thông tin, soạn skill hay thảo luận phương án không phải yêu cầu chạy lệnh thay đổi phiên.
|
|
9
|
+
|
|
10
|
+
## Xác định đúng phiên và CLI
|
|
11
|
+
|
|
12
|
+
Cần Herdr TUI CLI và server tương thích; khi chạy agent, cần kind đã cài và khởi chạy được trên **máy đích** (với Pi, cần cấu hình model và quyền truy cập của máy đó). Skill không đóng gói binary, model, token hay integration hook; không tự cài các thành phần thiếu.
|
|
13
|
+
|
|
14
|
+
Trước mọi thao tác với phiên sống, kiểm tra `HERDR_ENV=1` và có `HERDR_PANE_ID`; nếu thiếu, dừng và báo, không tự dò hay thao tác trên phiên đang focus từ ngoài Herdr. Có thể đọc docs/help offline mà không attach. Chọn ví dụ theo shell thực tế, không yêu cầu cài Bash trên Windows.
|
|
15
|
+
|
|
16
|
+
Bash/Git Bash:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
if [ "${HERDR_ENV:-}" = 1 ] && [ -n "${HERDR_PANE_ID:-}" ]; then
|
|
20
|
+
H=${HERDR_BIN_PATH:-herdr}
|
|
21
|
+
"$H" status && "$H" pane current --current
|
|
22
|
+
else
|
|
23
|
+
printf "%s\n" "Không ở trong pane Herdr; không điều khiển phiên." >&2
|
|
24
|
+
fi
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
PowerShell:
|
|
28
|
+
|
|
29
|
+
```powershell
|
|
30
|
+
if ($env:HERDR_ENV -eq '1' -and $env:HERDR_PANE_ID) {
|
|
31
|
+
$H = if ($env:HERDR_BIN_PATH) { $env:HERDR_BIN_PATH } else { 'herdr' }
|
|
32
|
+
& $H status
|
|
33
|
+
if ($LASTEXITCODE -eq 0) { & $H pane current --current }
|
|
34
|
+
} else {
|
|
35
|
+
Write-Warning 'Không ở trong pane Herdr; không điều khiển phiên.'
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Ưu tiên `HERDR_BIN_PATH` của phiên; chỉ dùng `herdr` trên PATH khi biến này không được cấp. Giữ nguyên context Herdr do pane cung cấp, không tự đoán socket hay session. Đọc `status` và kết quả `pane current --current` để xác minh đúng phiên trước khi gửi lệnh. Dùng `--skill`, `--help` hoặc help từng nhóm (`agent`, `pane`, `worktree`, `plugin`) để xác nhận các cờ/method cần dùng ở bản thực tế. Không chạy `herdr` trần để dò lệnh (launch/attach), không dò bằng lệnh con đột biến không tham số. Nếu binary không chạy được, thiếu tính năng hoặc không tương thích, báo chứ không tự cập nhật, restart hay đổi binary.
|
|
40
|
+
|
|
41
|
+
Các mẫu lệnh còn lại dùng cú pháp Bash. Trong PowerShell, gọi binary bằng `& $H` và dùng tham số/biến tương ứng. Truyền dữ liệu như path và brief bằng các phần tử argv riêng. Với native CLI trên Windows, nếu shell không giữ nguyên được dấu nháy hoặc brief nhiều dòng (ví dụ chế độ truyền đối số cũ của PowerShell), dùng runtime hỗ trợ argv trực tiếp hoặc dừng và báo giới hạn. Với Git Bash gọi `herdr.exe`, khi cần giữ nguyên path/brief/argv, dùng `MSYS2_ARG_CONV_EXCL='*'` cho **lời gọi đó** và truyền path native của máy đích. Không sửa cấu hình shell toàn cục.
|
|
42
|
+
|
|
43
|
+
## Chọn thao tác và target
|
|
44
|
+
|
|
45
|
+
- Read-only: `workspace list`, `tab list --workspace "$HERDR_WORKSPACE_ID"`, `pane list --workspace "$HERDR_WORKSPACE_ID"`, `agent list`, `session list --json`, `machine list --json`. `pane process-info`/`pane read` dùng khi cần đọc tiến trình thường; `agent get`/`agent read` khi cần đối chiếu agent được nhận diện. Chỉ đọc đối tượng nằm trong scope yêu cầu, không đổ toàn bộ transcript/log ra câu trả lời.
|
|
46
|
+
- Parse JSON, chỉ dùng ID thật. Agent target là tên live duy nhất hoặc pane ID đang chứa agent, không phải terminal ID hay kind `pi`. Kiểm tra tên chưa được dùng, dạng `[a-z][a-z0-9_-]{0,31}`. Sau move, phát hiện lại pane ID. Không dùng focus hiện tại làm fallback cho `--current`.
|
|
47
|
+
- Máy SSH: chỉ khi người dùng chỉ định; dùng cùng prefix `--machine <label-or-id>` cho discovery, launch, prompt, wait và read. Xác minh client/server hai đầu, dùng ID/path lấy ở máy đích và pane đích rõ ràng (không dùng `--current`/ID local trên máy remote). Không tự start máy đích, cài phần mềm, attach/takeover hoặc chuyển sang local khi lỗi.
|
|
48
|
+
- `workspace create` là terminal context, không phải tạo project registry. `worktree create` tạo/mở checkout (có thể tạo branch); `worktree open` mở checkout có sẵn. Chỉ thay topology/cwd khác khi được yêu cầu, kiểm tra Git base và trust; không thêm `--trust-repository` để lách Git. `workspace close` khác `worktree remove`; không dùng `--group`/`--force` hay đóng tài nguyên phiên đang dùng chỉ để dọn tiện.
|
|
49
|
+
- `pane run` chạy lệnh thường trong shell pane trống: phản hồi là đã xếp input, không chứng minh command chạy xong; `pane wait-output` có thể match output cũ. Dùng marker mới nếu cần quan sát lần chạy. Không thay `agent prompt` bằng raw keystrokes khi gửi việc.
|
|
50
|
+
- Herdr không có profile registry kiểu Paseo; xem tùy chọn profile Pi bên dưới. Không giả định có Paseo MCP, schedule/heartbeat bền hoặc quyền SLP native. Không dựng vòng polling, schedule bên ngoài, tự gửi tiếp hoặc dùng skill này thay `slp-gate`.
|
|
51
|
+
|
|
52
|
+
## Tùy chọn Pi: profile portable và phản hồi có cấu trúc
|
|
53
|
+
|
|
54
|
+
Nếu có Python 3.11+ và file `herdr_pi.py` đi kèm **trong thư mục của skill này**, dùng helper qua đường dẫn phát hiện từ vị trí `SKILL.md`, không dựa vào cwd cố định. Tên lệnh Python có thể là `python`, `python3` hoặc `py -3`. Bộ skill thuần terminal vẫn dùng được nếu không có helper hoặc Python.
|
|
55
|
+
|
|
56
|
+
- **Profile:** nếu người dùng chọn profile, dùng `profile list --file <catalog.toml>` hoặc `profile show <name> --file <catalog.toml>`. Có mẫu `profiles.example.toml` cùng thư mục; catalog thật do người dùng chọn, không tự copy credentials hay model config của máy khác. Xem `notes` để chọn profile khi được giao quyền chọn; notes không phải prompt. Xác minh model/thinking hỗ trợ trên máy đích. Truyền `pi_args` dưới dạng đối số riêng sau `--` của `agent start`, không eval. Nếu profile người dùng chỉ định không dùng được, báo và hỏi thay vì tự đổi.
|
|
57
|
+
- **Đối chiếu:** trước khi gửi việc cho Pi, gọi `new-request`, giữ ID và đặt nguyên `marker` trả về ở **dòng đầu prompt**. Một ID mới cho mỗi agent và mỗi vòng; chỉ gửi một lần qua `agent prompt`. Sau đó gọi `observe <request-id> --pane <pane-id>` cho pane Pi local có session path do integration báo. Nếu biết file session tuyệt đối trên chính máy đọc, có thể dùng `--session-file <path>` thay `--pane`; không đọc path của máy SSH từ local. Nếu đã biết ID phiên Pi lúc gửi, thêm `--expect-session <id>` cho cả hai kiểu đọc để không nhận nhầm kết quả từ phiên fork khác ID. Nếu không có ID đã xác minh, báo kết quả là quan sát không ghim phiên. Chỉ truyền `--include-answer` khi cần đọc phần trả lời và đúng phạm vi.
|
|
58
|
+
- **Đọc kết quả:** `response_observed` = tìm thấy assistant reply cùng nhánh cho marker đó, không phải proof agent đã idle/hoàn tất task; `request_observed` = thấy user entry nhưng chưa thấy phản hồi phù hợp; `request_not_observed` hoặc `unverified` **không** suy ra chưa gửi. Không tự resend, không tự chuyển sang session khác. Có thể đọc terminal để chẩn đoán, nhưng ghi rõ đó là nguồn riêng, không biến thành receipt. Nếu thiếu integration hay file không đọc được, dùng luồng terminal và báo giới hạn.
|
|
59
|
+
|
|
60
|
+
## Quy trình chung khi được yêu cầu tạo agent
|
|
61
|
+
|
|
62
|
+
1. Xác định cwd, kind và flags mà người dùng muốn. Không có profile chung của Herdr; dùng help/catalog của CLI con, ví dụ `pi --list-models` nếu cần chọn model. Mặc định ưu tiên Pi đang dùng nếu kind/bin sẵn có, không tự chuyển host, tài khoản/provider hay model khi lỗi. Tôn trọng model/flags chỉ định; cờ riêng đặt sau `--`.
|
|
63
|
+
2. Mặc định tạo sibling pane trong tab hiện tại, giữ cwd và không giật focus. `pane layout --pane "$HERDR_PANE_ID"` giúp chọn `right`/`down` phù hợp. Xác định cwd tuyệt đối trên chính máy đích: local Unix dùng `pwd -P`, Windows PowerShell dùng `(Get-Location).ProviderPath` trong thư mục filesystem, Windows Git Bash dùng `pwd -W`. Với SSH, xác minh cwd bằng thông tin workspace/pane của máy đích hoặc đường dẫn do người dùng cung cấp; không chuyển đổi cwd local thành cwd remote. Chỉ dùng existing pane khi người dùng chỉ định và xác minh đó là shell trống. Ví dụ dưới đây là mẫu, không tự chạy khi chỉ đọc skill:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
"$H" pane split --current --direction right --cwd "$target_cwd" --no-focus
|
|
67
|
+
# Đọc .result.pane.pane_id, dùng làm giá trị pane_id.
|
|
68
|
+
"$H" agent start "$agent_name" --kind pi --pane "$pane_id" --timeout 30000
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Không dùng lại Pi session cũ (`--continue`/`--resume`) cho agent mới. `agent start` không tự tạo pane; nếu lỗi hoặc agent bị kẹt lúc khởi động, xác minh pane và agent trước khi làm gì tiếp. Không reset pane hay khởi chạy lần hai mù.
|
|
72
|
+
3. Xác minh đúng agent và `idle`/`done` bằng `agent get`, kiểm tra UI nếu chưa rõ pane có sẵn sàng. Gửi brief có phạm vi, yêu cầu không tự ủy quyền tiếp và marker kết quả mới riêng cho task/agent. Truyền brief dạng một đối số, không `eval` hay chèn vào chuỗi shell; không đưa credential, toàn bộ log hay transcript nhạy cảm vào prompt/argv. Với brief dài, tóm gọn; nếu cần dẫn file thì xác minh quyền đọc và đường dẫn trên đúng máy.
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
"$H" agent prompt "$pane_id" "$brief" --wait --timeout 120000
|
|
76
|
+
"$H" agent get "$pane_id"
|
|
77
|
+
"$H" agent read "$pane_id" --source recent-unwrapped --lines 120
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
4. `--timeout` là mili giây. `agent prompt --wait` chờ lifecycle, không gắn receipt riêng cho turn. `blocked` nghĩa là cần xem UI và hỏi người dùng; không tự approve. `working`/`unknown` không phải hoàn thành. `timeout`/`agent_prompt_stalled` có thể đã gửi; kiểm tra state/output hoặc báo chưa rõ, không tự gửi lại. `idle`/`done` chỉ xác nhận settled: đọc output, đối chiếu marker và phần trả lời thực (marker bị echo trong prompt không phải kết quả). Nếu thiếu transcript, báo thiếu bằng chứng; chỉ khi người dùng cho phép ghi file mới dùng file kết quả trên cùng máy như fallback.
|
|
81
|
+
5. Báo tên agent, pane, cùng kết quả hoặc trạng thái chưa xác minh; dừng đúng giới hạn. Không tự đóng pane có việc đang chạy hay pane người dùng; không dọn tài nguyên nếu chưa được yêu cầu. Worktree là checkout riêng, **không phải OS sandbox**.
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Portable Pi profiles and read-only observation of Herdr/Pi requests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import shutil
|
|
11
|
+
import stat
|
|
12
|
+
import subprocess
|
|
13
|
+
import tomllib
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
MAX_PROFILE_BYTES = 64 * 1024
|
|
17
|
+
MAX_SESSION_BYTES = 32 * 1024 * 1024
|
|
18
|
+
MAX_ANSWER_CHARS = 24_000
|
|
19
|
+
NAME = re.compile(r"[a-z][a-z0-9_-]{0,63}")
|
|
20
|
+
MODEL = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9._-]*(?:/[a-zA-Z0-9][a-zA-Z0-9._-]*)+")
|
|
21
|
+
PANE = re.compile(r"w[0-9]+:p[0-9]+")
|
|
22
|
+
THINKING = {"off", "minimal", "low", "medium", "high", "xhigh", "max"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Unverified(Exception):
|
|
26
|
+
"""An input or observation cannot be used as evidence."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_profiles(path: Path) -> dict:
|
|
30
|
+
try:
|
|
31
|
+
with path.open("rb") as source:
|
|
32
|
+
data = source.read(MAX_PROFILE_BYTES + 1)
|
|
33
|
+
if len(data) > MAX_PROFILE_BYTES:
|
|
34
|
+
raise Unverified("profile_file_too_large")
|
|
35
|
+
doc = tomllib.loads(data.decode("utf-8"))
|
|
36
|
+
except (OSError, UnicodeError, ValueError) as exc:
|
|
37
|
+
raise Unverified("profile_file_unreadable_or_invalid") from exc
|
|
38
|
+
version = doc.get("schema_version")
|
|
39
|
+
profiles = doc.get("profiles")
|
|
40
|
+
if (set(doc) != {"schema_version", "profiles"} or type(version) is not int
|
|
41
|
+
or version != 1 or not isinstance(profiles, dict) or not profiles):
|
|
42
|
+
raise Unverified("invalid_profile_schema")
|
|
43
|
+
result = {}
|
|
44
|
+
for name, values in sorted(profiles.items()):
|
|
45
|
+
if not NAME.fullmatch(name) or not isinstance(values, dict):
|
|
46
|
+
raise Unverified("invalid_profile")
|
|
47
|
+
if values.keys() - {"notes", "model", "thinking"}:
|
|
48
|
+
raise Unverified("unsupported_profile_field")
|
|
49
|
+
notes = values.get("notes", "")
|
|
50
|
+
if not isinstance(notes, str) or len(notes) > 500:
|
|
51
|
+
raise Unverified("invalid_profile_notes")
|
|
52
|
+
args = []
|
|
53
|
+
if "model" in values:
|
|
54
|
+
model = values["model"]
|
|
55
|
+
if not isinstance(model, str) or len(model) > 200 or not MODEL.fullmatch(model):
|
|
56
|
+
raise Unverified("invalid_profile_model")
|
|
57
|
+
args.extend(["--model", model])
|
|
58
|
+
if "thinking" in values:
|
|
59
|
+
thinking = values["thinking"]
|
|
60
|
+
if not isinstance(thinking, str) or thinking not in THINKING:
|
|
61
|
+
raise Unverified("invalid_profile_thinking")
|
|
62
|
+
args.extend(["--thinking", thinking])
|
|
63
|
+
result[name] = {"name": name, "notes": notes, "kind": "pi", "pi_args": args}
|
|
64
|
+
return result
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def marker(request_id: uuid.UUID) -> str:
|
|
68
|
+
return f"[herdr-request:{request_id}]"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def file_signature(info: os.stat_result) -> tuple:
|
|
72
|
+
# Windows stat/fstat can disagree on ctime for the same file.
|
|
73
|
+
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def read_snapshot(path: Path) -> bytes:
|
|
77
|
+
if not path.is_absolute() or path.suffix.lower() != ".jsonl" or path.drive.startswith("\\\\"):
|
|
78
|
+
raise Unverified("expected_absolute_local_session_path")
|
|
79
|
+
try:
|
|
80
|
+
info = path.stat()
|
|
81
|
+
if not stat.S_ISREG(info.st_mode):
|
|
82
|
+
raise Unverified("expected_regular_session_file")
|
|
83
|
+
if info.st_size > MAX_SESSION_BYTES:
|
|
84
|
+
raise Unverified("session_too_large")
|
|
85
|
+
with path.open("rb") as source:
|
|
86
|
+
before = os.fstat(source.fileno())
|
|
87
|
+
data = source.read(MAX_SESSION_BYTES + 1)
|
|
88
|
+
after = os.fstat(source.fileno())
|
|
89
|
+
current = path.stat()
|
|
90
|
+
except OSError as exc:
|
|
91
|
+
raise Unverified("session_unreadable") from exc
|
|
92
|
+
if not (file_signature(info) == file_signature(before) == file_signature(after) == file_signature(current)
|
|
93
|
+
and len(data) == before.st_size):
|
|
94
|
+
raise Unverified("session_changed_during_read")
|
|
95
|
+
return data
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def text_content(content) -> str:
|
|
99
|
+
if isinstance(content, str):
|
|
100
|
+
return content
|
|
101
|
+
if isinstance(content, list) and all(isinstance(item, dict) for item in content):
|
|
102
|
+
texts = [item.get("text") for item in content if item.get("type") == "text"]
|
|
103
|
+
if all(isinstance(value, str) for value in texts):
|
|
104
|
+
return "\n".join(texts)
|
|
105
|
+
raise Unverified("invalid_message_content")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def unique_fields(pairs):
|
|
109
|
+
row = {}
|
|
110
|
+
for key, value in pairs:
|
|
111
|
+
if key in row:
|
|
112
|
+
raise Unverified("duplicate_session_field")
|
|
113
|
+
row[key] = value
|
|
114
|
+
return row
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def observe_snapshot(data: bytes, request_id: uuid.UUID, include_answer: bool = False,
|
|
118
|
+
expected_session: str | None = None) -> dict:
|
|
119
|
+
if not data or not data.endswith(b"\n"):
|
|
120
|
+
raise Unverified("incomplete_session_snapshot")
|
|
121
|
+
entries = set()
|
|
122
|
+
matched = None
|
|
123
|
+
descendants = set()
|
|
124
|
+
parents_with_child = set()
|
|
125
|
+
assistant = None
|
|
126
|
+
boundary = None
|
|
127
|
+
session_id = None
|
|
128
|
+
for i, line in enumerate(data.split(b"\n")[:-1]):
|
|
129
|
+
try:
|
|
130
|
+
row = json.loads(line.decode("utf-8"), object_pairs_hook=unique_fields)
|
|
131
|
+
except (ValueError, RecursionError) as exc:
|
|
132
|
+
raise Unverified("invalid_session_json") from exc
|
|
133
|
+
if not isinstance(row, dict) or not isinstance(row.get("type"), str):
|
|
134
|
+
raise Unverified("invalid_session_entry")
|
|
135
|
+
entry_type = row["type"]
|
|
136
|
+
entry_id = row.get("id")
|
|
137
|
+
if not isinstance(entry_id, str) or not entry_id:
|
|
138
|
+
raise Unverified("invalid_session_entry_id")
|
|
139
|
+
if i == 0:
|
|
140
|
+
version = row.get("version")
|
|
141
|
+
if entry_type != "session" or type(version) is not int or version != 3:
|
|
142
|
+
raise Unverified("unsupported_session_format")
|
|
143
|
+
if expected_session is not None and entry_id != expected_session:
|
|
144
|
+
raise Unverified("unexpected_session_id")
|
|
145
|
+
session_id = entry_id
|
|
146
|
+
continue
|
|
147
|
+
parent = row.get("parentId")
|
|
148
|
+
if (entry_type == "session" or entry_id in entries or "parentId" not in row
|
|
149
|
+
or (parent is not None and (not isinstance(parent, str) or parent not in entries))):
|
|
150
|
+
raise Unverified("invalid_session_tree")
|
|
151
|
+
entries.add(entry_id)
|
|
152
|
+
msg = row.get("message") if entry_type == "message" else {}
|
|
153
|
+
if not isinstance(msg, dict) or (entry_type == "message" and not isinstance(msg.get("role"), str)):
|
|
154
|
+
raise Unverified("invalid_session_message")
|
|
155
|
+
role = msg.get("role")
|
|
156
|
+
if role == "user" and text_content(msg.get("content")).partition("\n")[0].rstrip("\r") == marker(request_id):
|
|
157
|
+
if matched is not None:
|
|
158
|
+
raise Unverified("duplicate_request_marker")
|
|
159
|
+
matched = entry_id
|
|
160
|
+
descendants.add(entry_id)
|
|
161
|
+
elif parent in descendants:
|
|
162
|
+
if parent in parents_with_child:
|
|
163
|
+
raise Unverified("ambiguous_request_branch")
|
|
164
|
+
parents_with_child.add(parent)
|
|
165
|
+
if role == "user":
|
|
166
|
+
boundary = entry_id
|
|
167
|
+
else:
|
|
168
|
+
descendants.add(entry_id)
|
|
169
|
+
if role == "assistant":
|
|
170
|
+
assistant = (entry_id, msg)
|
|
171
|
+
|
|
172
|
+
if session_id is None:
|
|
173
|
+
raise Unverified("missing_session_header")
|
|
174
|
+
result = {"request_id": str(request_id), "session_id": session_id}
|
|
175
|
+
if matched is None:
|
|
176
|
+
return {**result, "status": "request_not_observed"}
|
|
177
|
+
result.update(request_entry_id=matched, status="request_observed")
|
|
178
|
+
if boundary:
|
|
179
|
+
result["next_user_entry_id"] = boundary
|
|
180
|
+
if assistant and assistant[1].get("stopReason") == "stop":
|
|
181
|
+
content = assistant[1].get("content")
|
|
182
|
+
if isinstance(content, list) and any(
|
|
183
|
+
isinstance(block, dict) and block.get("type") == "toolCall" for block in content):
|
|
184
|
+
return result
|
|
185
|
+
answer = text_content(content).strip()
|
|
186
|
+
if answer:
|
|
187
|
+
result.update(status="response_observed", response_entry_id=assistant[0])
|
|
188
|
+
if include_answer:
|
|
189
|
+
result.update(answer=answer[:MAX_ANSWER_CHARS], answer_truncated=len(answer) > MAX_ANSWER_CHARS)
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def pane_binding(pane: str) -> tuple[str, str, Path]:
|
|
194
|
+
if not PANE.fullmatch(pane):
|
|
195
|
+
raise Unverified("expected_explicit_pane_id")
|
|
196
|
+
if os.environ.get("HERDR_ENV") != "1" or not os.environ.get("HERDR_PANE_ID"):
|
|
197
|
+
raise Unverified("not_in_herdr_pane")
|
|
198
|
+
binary = os.environ.get("HERDR_BIN_PATH") or shutil.which("herdr")
|
|
199
|
+
if not binary or (os.name == "nt" and Path(binary).suffix.lower() != ".exe"):
|
|
200
|
+
raise Unverified("herdr_native_binary_unavailable")
|
|
201
|
+
try:
|
|
202
|
+
run = subprocess.run([binary, "agent", "get", pane], capture_output=True, timeout=5, check=True)
|
|
203
|
+
agent = json.loads(run.stdout)["result"]["agent"]
|
|
204
|
+
session = agent["agent_session"]
|
|
205
|
+
terminal = agent["terminal_id"]
|
|
206
|
+
if (agent.get("pane_id") != pane or agent.get("agent") != "pi" or not isinstance(terminal, str)
|
|
207
|
+
or not terminal or session.get("agent") != "pi" or session.get("kind") != "path"
|
|
208
|
+
or session.get("source") != "herdr:pi" or not isinstance(session.get("value"), str)):
|
|
209
|
+
raise Unverified("pane_has_no_reported_pi_session")
|
|
210
|
+
return pane, terminal, Path(session["value"])
|
|
211
|
+
except (OSError, KeyError, TypeError, AttributeError, ValueError, RecursionError, subprocess.SubprocessError) as exc:
|
|
212
|
+
raise Unverified("pane_session_lookup_failed") from exc
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def observe(request_id: uuid.UUID, pane: str | None, session_file: Path | None,
|
|
216
|
+
include_answer: bool = False, expected_session: str | None = None) -> dict:
|
|
217
|
+
binding = pane_binding(pane) if pane else None
|
|
218
|
+
path = binding[2] if binding else session_file
|
|
219
|
+
if path is None:
|
|
220
|
+
raise Unverified("missing_session_target")
|
|
221
|
+
result = observe_snapshot(read_snapshot(path), request_id, include_answer, expected_session)
|
|
222
|
+
if binding and pane_binding(binding[0]) != binding:
|
|
223
|
+
raise Unverified("pane_session_changed_during_read")
|
|
224
|
+
return result
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def main(argv=None) -> int:
|
|
228
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
229
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
230
|
+
profile = commands.add_parser("profile", help="read a local, explicitly selected TOML profile catalog")
|
|
231
|
+
profile_commands = profile.add_subparsers(dest="action", required=True)
|
|
232
|
+
for action in ("list", "show"):
|
|
233
|
+
sub = profile_commands.add_parser(action)
|
|
234
|
+
sub.add_argument("--file", type=Path, required=True)
|
|
235
|
+
if action == "show":
|
|
236
|
+
sub.add_argument("name")
|
|
237
|
+
commands.add_parser("new-request", help="generate a request ID and prompt marker; never sends it")
|
|
238
|
+
query = commands.add_parser("observe", help="observe a single request without sending or waiting")
|
|
239
|
+
query.add_argument("request_id", type=uuid.UUID)
|
|
240
|
+
target = query.add_mutually_exclusive_group(required=True)
|
|
241
|
+
target.add_argument("--pane", help="explicit local Herdr pane ID")
|
|
242
|
+
target.add_argument("--session-file", type=Path, help="absolute local path to a Pi JSONL session")
|
|
243
|
+
query.add_argument("--expect-session", help="require the expected Pi session header ID")
|
|
244
|
+
query.add_argument("--include-answer", action="store_true", help="allow returning assistant text")
|
|
245
|
+
args = parser.parse_args(argv)
|
|
246
|
+
code = 0
|
|
247
|
+
try:
|
|
248
|
+
if args.command == "profile":
|
|
249
|
+
profiles = load_profiles(args.file)
|
|
250
|
+
if args.action == "list":
|
|
251
|
+
result = {"profiles": [{"name": item["name"], "notes": item["notes"]} for item in profiles.values()]}
|
|
252
|
+
elif args.name in profiles:
|
|
253
|
+
result = {"profile": profiles[args.name]}
|
|
254
|
+
else:
|
|
255
|
+
raise Unverified("unknown_profile")
|
|
256
|
+
elif args.command == "new-request":
|
|
257
|
+
request_id = uuid.uuid4()
|
|
258
|
+
result = {"request_id": str(request_id), "marker": marker(request_id)}
|
|
259
|
+
else:
|
|
260
|
+
result = observe(args.request_id, args.pane, args.session_file, args.include_answer, args.expect_session)
|
|
261
|
+
code = 0 if result["status"] == "response_observed" else 1
|
|
262
|
+
except Unverified as exc:
|
|
263
|
+
result = {"status": "unverified", "reason": str(exc)}
|
|
264
|
+
if args.command == "observe":
|
|
265
|
+
result["request_id"] = str(args.request_id)
|
|
266
|
+
code = 2
|
|
267
|
+
print(json.dumps(result))
|
|
268
|
+
return code
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
if __name__ == "__main__":
|
|
272
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
schema_version = 1
|
|
2
|
+
|
|
3
|
+
# These examples use the destination machine's default Pi model.
|
|
4
|
+
# To pin a model, add model = "provider/model-id" after verifying it locally.
|
|
5
|
+
[profiles.advisor]
|
|
6
|
+
notes = "Short independent review; checks assumptions and evidence."
|
|
7
|
+
thinking = "high"
|
|
8
|
+
|
|
9
|
+
[profiles.committee-rca]
|
|
10
|
+
notes = "Root-cause analysis; compare competing explanations."
|
|
11
|
+
thinking = "high"
|
|
12
|
+
|
|
13
|
+
[profiles.committee-review]
|
|
14
|
+
notes = "Challenge conclusions and identify missing evidence."
|
|
15
|
+
thinking = "high"
|
|
16
|
+
|
|
17
|
+
[profiles.handoff]
|
|
18
|
+
notes = "Continue the brief within its stated scope and acceptance criteria."
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr-advisor
|
|
3
|
+
description: 'Dùng một agent trong Herdr TUI để lấy góc nhìn thứ hai hoặc phản biện chỉ đọc. Chỉ khởi chạy khi người dùng yêu cầu advisor qua Herdr; không giao việc triển khai.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr Advisor
|
|
7
|
+
|
|
8
|
+
Đọc [Herdr TUI](../herdr/SKILL.md) trước. Nếu chỉ được hỏi cách dùng, giải thích, không tạo pane. Xác minh đang ở Herdr, đúng cwd và kind/model. Hỗ trợ yêu cầu dạng `[--kind <kind>] <câu hỏi>` hoặc profile Pi theo catalog được chọn như skill gốc. Model/thinking nếu có thì kiểm qua CLI con, không suy diễn từ Paseo profile.
|
|
9
|
+
|
|
10
|
+
1. Chốt đúng **một** câu hỏi. Tạo **một** agent mới tên như `advisor-<slug>` bằng split/agent start theo skill gốc. Giữ workspace/cwd hiện tại và focus; trừ khi người dùng yêu cầu chỗ khác. Không tự mở thêm agent thứ hai. Có thể dùng kind/model khác nếu được yêu cầu hoặc đã được người dùng cho chọn và đã xác minh sẵn sàng.
|
|
11
|
+
2. Gửi brief: câu hỏi, hiện trạng, thay đổi đã thử, đường dẫn/commit liên quan và các giả định cần phản biện. Yêu cầu **chỉ đọc: không sửa/tạo/xóa file, không chạy lệnh có tác dụng phụ, không gọi agent khác**. Đề nghị trả về nhận định, bằng chứng, rủi ro và phương án khuyến nghị; cuối phản hồi ghi marker riêng theo task. Đây là ràng buộc tác vụ, không phải phân quyền OS.
|
|
12
|
+
3. Gửi một lần bằng `agent prompt --wait --timeout …`. Nếu dùng Pi với helper, tạo request marker trước khi gửi và ưu tiên `observe` cho đúng request; nếu không có helper thì dùng `agent get` và `agent read` kèm giới hạn. Không dùng trạng thái `done` làm đáp án và không gửi lại mù khi stall/timeout. Tổng hợp tách rõ **ý kiến advisor** và **khuyến nghị của mình**; nếu không đọc được kết quả, nói rõ lý do. Dừng sau vòng này; không chỉnh code hay đóng pane thay người dùng.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr-committee
|
|
3
|
+
description: 'Dùng hai agent trong Herdr TUI để phân tích độc lập, phản biện và đề xuất kế hoạch cho bài toán khó. Chỉ khởi chạy khi người dùng yêu cầu committee qua Herdr; không triển khai code.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr Committee
|
|
7
|
+
|
|
8
|
+
Đọc [Herdr TUI](../herdr/SKILL.md) trước. Chỉ bắt đầu khi người dùng yêu cầu thực thi. Lấy tối đa **hai agent mới** trong hai pane độc lập. Mặc định dùng cùng cwd/tab đang làm, giữ focus bằng `--no-focus`, chọn hướng split theo layout. Tôn trọng kind/model mà người dùng chọn; có thể dùng hai profile Pi trong catalog người dùng chọn nếu đã xác minh được máy đích. Nếu chỉ có một kind sẵn, dùng hai góc nhìn khác nhau (ví dụ RCA và phản biện) và nói rõ không có đa dạng provider; không âm thầm đổi service/tài khoản.
|
|
9
|
+
|
|
10
|
+
1. Khung bài toán chung: mục tiêu, hiện tượng, phạm vi, bằng chứng, thử nghiệm đã thất bại và ràng buộc. Cùng một dữ kiện cho hai agent; khác câu hỏi/góc nhìn. Prompt yêu cầu **chỉ đọc**, không sửa/tạo/xóa file, không chạy lệnh có tác dụng phụ, không tạo thêm agent. Read-only là ràng buộc tác vụ, không phải sandbox.
|
|
11
|
+
2. Tạo pane theo thứ tự, lấy hai ID khác nhau từ JSON; xác minh hai agent đã sẵn sàng và chưa có turn đang chạy. Gửi brief độc lập đến từng đích, có marker mới khác nhau. Với Pi/helper, tạo UUID riêng và đặt marker đúng dòng đầu cho từng lần gửi, rồi `observe` riêng theo pane/ID. Chạy hai lời gọi `agent prompt --wait --timeout …` độc lập cùng lúc nếu có thực thi song song; kiểm cả hai exit result. Không dùng `agent wait` rời như bằng chứng prompt đã được nhận.
|
|
12
|
+
3. Đọc từng kết quả, so sánh nguyên nhân, bằng chứng và điểm bất đồng. Nếu hữu ích, thực hiện **tối đa một vòng** phản biện cho mỗi agent đã sẵn sàng: gửi lập luận đối lập tóm tắt, không gửi transcript thô hoặc secret. Dùng marker mới, timeout hữu hạn; không tự approve, không retry mù, không mở thêm agent thay thế.
|
|
13
|
+
4. Báo điểm đồng thuận, điểm bất đồng chưa giải quyết, hướng thử nghiệm/plan và giới hạn dữ liệu. Báo riêng agent blocked/timeout/không có bằng chứng; không hạ xuống một advisor rồi gọi đó là kết luận của committee. Không triển khai code hay tự đóng pane. Nếu cần vòng mới, hỏi người dùng.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr-handoff
|
|
3
|
+
description: 'Bàn giao công việc hiện tại cho một agent mới trong Herdr TUI với brief tự chứa và tiêu chí nghiệm thu. Chỉ chạy khi người dùng yêu cầu chuyển việc qua Herdr; hỗ trợ worktree riêng nếu được chỉ định.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr Handoff
|
|
7
|
+
|
|
8
|
+
Đọc [Herdr TUI](../herdr/SKILL.md) trước. Handoff là **giao việc cho một agent mới**, không phải `--handoff` của Herdr (chuyển phiên/tiến trình khi update/attach), không copy toàn bộ session và không chuyển quyền Lead/Peer hay quyền nghiệm thu.
|
|
9
|
+
|
|
10
|
+
1. Xác minh yêu cầu, scope và người nhận. Giữ loại nhiệm vụ: điều tra vẫn chỉ đọc; fix thì mới được sửa trong phạm vi; review không biến thành rewrite. Nếu có thay đổi chưa commit, nói rõ file/commit nào agent mới thực sự nhìn thấy. Không để hai agent sửa chồng cùng phạm vi trong một checkout.
|
|
11
|
+
2. Mặc định dùng pane mới trong tab/cwd hiện tại như skill gốc. Nếu được yêu cầu worktree, xác minh repo và base Git, chọn tên branch mới không đụng branch sẵn; dùng worktree open nếu người dùng chỉ định checkout đã có. Mẫu cho branch mới, sau khi đã xác minh đầu vào:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
"$H" worktree create --cwd "$repo" --branch "$branch" --base "$base" --no-focus
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Lấy `.result.workspace.workspace_id`, `.result.root_pane.pane_id` và checkout từ response; xác minh cwd/pane trống trước `agent start`. Dùng profile Pi nếu người dùng chọn và máy đích hỗ trợ. Worktree không mang theo thay đổi chưa commit của checkout gốc. Không tự copy, cherry-pick, stash, commit hoặc push để làm brief “chạy được”; nếu thiếu input, hỏi người dùng. Không tự thêm `--trust-repository`.
|
|
18
|
+
3. Brief tự chứa: mục tiêu và phần việc còn lại; repo/cwd/branch/base; file và bằng chứng; hiện trạng và lần thử thất bại; quyết định đã khóa; mục không được động; tiêu chí nghiệm thu, phép kiểm chứng được phép và cách báo blocked. Không gửi credential hoặc nguyên transcript. Yêu cầu phản hồi nhận việc có marker riêng, nhắc lại scope hoặc blocker và không tự ủy quyền. Nếu người dùng chỉ yêu cầu chuẩn bị brief, dừng ở brief.
|
|
19
|
+
4. Gửi một lần bằng `agent prompt` theo skill gốc. Với Pi/helper, đặt marker request ở dòng đầu và giữ ID để đối chiếu sau; không tự resend nếu chưa thấy ACK. Chỉ dùng `--wait` có timeout nếu người dùng muốn chờ kết quả; không bắt agent dừng sau ACK nếu mục tiêu là làm tiếp. Báo agent/pane/workspace và trạng thái đã quan sát: “đã submit” khác “đã nhận/đang làm” và “đã hoàn tất”. ACK nhìn thấy phải là câu trả lời, không phải echo prompt; nếu không biết, báo chưa xác minh. Sau bàn giao không tự triển khai song song hoặc đóng pane.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr-help
|
|
3
|
+
description: 'Giải thích và chẩn đoán Herdr TUI: cài đặt, phiên đang chạy, CLI/server, ConPTY, SSH và nhận diện agent/Pi. Ưu tiên chỉ đọc; không dùng để điều khiển agent hoặc tự sửa cấu hình.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr Help
|
|
7
|
+
|
|
8
|
+
Phân biệt **Herdr TUI binary, server phiên, Herdr Desktop/Core/mod, extension trong agent**. Đừng dùng tài liệu Desktop mod để suy diễn plugin TUI, hay phiên bản client để kết luận server đã cập nhật. Hỏi người dùng đang thao tác ở đâu nếu chưa rõ.
|
|
9
|
+
|
|
10
|
+
1. Đọc [index tài liệu stable](https://herdr.dev/llms.txt); dùng trang đúng phiên bản/chủ đề, preview index chỉ cho bản preview. [Agent guide](https://herdr.dev/agent-guide.md) phù hợp setup lần đầu. Đối chiếu help thực tế trước khi đưa lệnh. Khi hostname/phiên chưa rõ, không query phiên đang focus từ ngoài; vẫn có thể kiểm `--version`/`--help`.
|
|
11
|
+
2. Nếu ở managed pane, dùng guard và `HERDR_BIN_PATH` của [skill gốc](../herdr/SKILL.md). So sánh `command -v herdr` hoặc `Get-Command herdr -All`, `herdr --version`, binary trong `HERDR_BIN_PATH` và `status`. Đọc trường client/server, endpoint/protocol compatibility và stale; khác version nhưng compatible không tự động là lỗi cần restart. Trên Windows lưu ý ConPTY, Windows OpenSSH và named pipe; không áp Unix socket/keybinding/handoff làm mặc định.
|
|
12
|
+
3. Nhận diện sai agent: xem `agent get <target>`, `agent explain <target>`, `pane process-info --pane <id>` và `integration status` nếu có. Với Pi, tìm extension Herdr-báo-trạng-thái theo output, kiểm xem Pi có chạy `--no-extensions` hoặc không ở Herdr. File có mặt chưa chứng minh đã nạp; agent status không chứng minh turn hoàn tất. Không tự cài lại extension.
|
|
13
|
+
4. Lỗi remote: phân biệt local với saved SSH machine; đọc `machine status <machine> --json` khi có target rõ. Không `machine reconnect` thay người dùng khi cần xác thực tương tác; không stop/thay server remote. Lỗi log: lấy đường dẫn theo `--help` hoặc docs đúng OS, chỉ đọc đoạn liên quan và che nội dung nhạy cảm. Tránh dump config/env/log đầy đủ.
|
|
14
|
+
5. Trả lời bằng hiện tượng, bằng chứng, nguyên nhân đã xác minh hoặc giả thuyết còn lại và bước ít rủi ro nhất. Không tự update, đổi PATH/config, reload, dừng/kill tiến trình, đổi session hay bật integration; nêu tác dụng phụ và xin phép nếu cần.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: herdr-plugin
|
|
3
|
+
description: 'Thiết kế, viết hoặc chẩn đoán plugin Herdr TUI dùng herdr-plugin.toml, actions, event/startup hooks, terminal panes và CLI/socket. Không dùng cho Herdr Desktop mod, Pi extension hay Paseo plugin.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Herdr TUI Plugin
|
|
7
|
+
|
|
8
|
+
Xác nhận người dùng muốn **plugin Herdr TUI**. Mở [index Herdr](https://herdr.dev/llms.txt) và docs Plugins, Socket API đúng bản; xem help `herdr plugin` và `herdr api schema --json`. Khi đọc phiên sống, tuân thủ guard/target của [skill gốc](../herdr/SKILL.md). Nếu đề bài nói Desktop/Core, mod UI hoặc extension Pi, xác định runtime khác trước; không tạo nhầm manifest.
|
|
9
|
+
|
|
10
|
+
## Thiết kế và viết
|
|
11
|
+
|
|
12
|
+
- Dùng thư mục riêng với `herdr-plugin.toml` và script/binary. Manifest có `id`, `name`, `version`, `min_herdr_version`; khai báo `platforms` chính xác. Chọn `[[actions]]` cho thao tác theo yêu cầu, `[[events]]` cho sự kiện xác nhận có trong bản đích, `[[startup]]` cho init hữu hạn, `[[panes]]` cho UI terminal, `[[link_handlers]]` nếu thực sự cần. Event hook không phải preflight authorization, scheduler hay daemon được supervise.
|
|
13
|
+
- `command` là argv array; không chèn dữ liệu context vào chuỗi shell. Ưu tiên `HERDR_BIN_PATH` gọi CLI; dùng socket trực tiếp chỉ nếu có lý do (Unix socket khác Windows named pipe). Parse context `HERDR_PLUGIN_CONTEXT_JSON`/ID đúng phiên, không dựa vào focus hay suy đoán field thiếu. Chỉ lưu config/state vào `HERDR_PLUGIN_CONFIG_DIR` và `HERDR_PLUGIN_STATE_DIR`; không log prompt/secret và không ghi credentials vào repo.
|
|
14
|
+
- Windows: xác minh launcher/PATH/argv; đừng bê ví dụ `sh` vào Windows nếu không khai báo dependency/platform. Tránh gọi SDK/RPC hoặc native non-terminal UI của Paseo như thể Herdr có đối ứng. Plugin chạy với quyền người dùng, không sandbox; không hứa cổng cưỡng chế SLP, authority hay delivery receipt chỉ từ manifest/events.
|
|
15
|
+
|
|
16
|
+
## Kiểm chứng và vận hành
|
|
17
|
+
|
|
18
|
+
1. Trước hết kiểm manifest, input/argv, dữ liệu có thể thiếu và lỗi command bằng test offline; chẩn đoán chỉ đọc bằng `plugin list --plugin <id> --json`, `plugin action list --plugin <id>`, `plugin log list --plugin <id> --limit 20` nếu CLI hỗ trợ. Không invoke action để dò lỗi nếu action có thể đổi state.
|
|
19
|
+
2. Xem trước mọi build/startup/event/action command, trust nguồn và quyền scope. **Không** chạy link/install/enable/update/invoke/unlink khi mới được yêu cầu viết hay kiểm tra. Nếu người dùng yêu cầu chạy thử, chọn phiên thử riêng; xác nhận đăng ký plugin **global theo user** ngay cả khi có named session. Một phiên test không cô lập đăng ký plugin, file, môi trường hay quyền OS.
|
|
20
|
+
3. Với source local được duyệt, `plugin link <absolute-path> --disabled` là đăng ký không bật nếu bản CLI hỗ trợ, không phải cách test offline. Link không tự build. Enable/run là bước riêng, báo trước tác dụng phụ. Startup hook chạy khi server khởi động, không chạy lại chỉ vì link/enable/reload config; không restart server đang phục vụ để test nếu chưa được phép.
|
|
21
|
+
4. Báo riêng phần đã đọc, đã test offline, đã link/enable hay đã chạy thực tế; không đánh đồng “plugin xuất hiện trong list” với “hook đã chạy đúng”.
|
package/DEPLOY.md
CHANGED
|
@@ -208,6 +208,33 @@ existing `ws` dependency from the npm installation; the standalone plugin uses
|
|
|
208
208
|
Node's native WebSocket by default. Restart only the publisher. Remove the line
|
|
209
209
|
to restore the public transport. No client SSH configuration changes are needed.
|
|
210
210
|
|
|
211
|
+
For the standalone Linux Mobile TUI publisher (`src/host/mobile-tui.ts`),
|
|
212
|
+
set `HERDGATE_AGENT_LOOPBACK_PORT` in its **process environment** (for systemd,
|
|
213
|
+
a drop-in with `[Service]` and `Environment=HERDGATE_AGENT_LOOPBACK_PORT=8833`,
|
|
214
|
+
using the actual local port). Keep the public `HERDGATE_URL`, the existing room
|
|
215
|
+
and the device scope. Only enable this when the Gate is on the same machine.
|
|
216
|
+
Restart that Mobile publisher alone in a maintenance window and verify its
|
|
217
|
+
journal reports `cloud hello: … via loopback 127.0.0.1:…`. Reconnect Mobile
|
|
218
|
+
and test the existing entry. Remove the drop-in setting and restart the same
|
|
219
|
+
publisher to roll back. This does not change the public WSS leg on the VPS,
|
|
220
|
+
the SSH host key, or the Herdr server.
|
|
221
|
+
|
|
222
|
+
## Measure Mobile latency
|
|
223
|
+
|
|
224
|
+
For a local baseline with an isolated Herdr 0.9.5 server, pane, Gate and TCP
|
|
225
|
+
edge (no live rooms or keys), run:
|
|
226
|
+
|
|
227
|
+
```sh
|
|
228
|
+
TEST_HERDR_BIN="$(command -v herdr)" node scripts/bench-mobile-tui.mjs 25
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Compare native Herdr, the Core adapter over local pipes, and the full Mobile
|
|
232
|
+
transport over loopback. The script reports key-to-ANSI, Send-to-ACK and
|
|
233
|
+
Send-to-ANSI separately; attach is measured separately from steady-state
|
|
234
|
+
input. This does not include cellular RTT or the official app's rendering.
|
|
235
|
+
An observe/read-only TUI attachment instead polls every 1.25 seconds; its
|
|
236
|
+
refresh interval is not comparable to the native interactive stream.
|
|
237
|
+
|
|
211
238
|
## Keep it running
|
|
212
239
|
|
|
213
240
|
On this machine (Linux + systemd) a user unit keeps the gate up; the tunnel is a second unit:
|
package/README.md
CHANGED
|
@@ -350,6 +350,23 @@ Set `HERDR_SOCKET_PATH` if needed to select the existing TUI session. Without
|
|
|
350
350
|
mode, use a separate room and set that variable to the exact existing `act`
|
|
351
351
|
device ID. The publisher never auto-approves new `act` pairings.
|
|
352
352
|
|
|
353
|
+
### Mobile TUI latency (0.9.30+)
|
|
354
|
+
|
|
355
|
+
Interactive Mobile TUI sends the first output after an idle period immediately,
|
|
356
|
+
while continuing to batch bursts. This applies to the Mobile TUI adapter on
|
|
357
|
+
Windows and Linux, not to real Core or read-only snapshot polling.
|
|
358
|
+
|
|
359
|
+
For a standalone Linux Mobile publisher on the **same machine** as the Gate,
|
|
360
|
+
opt into `HERDGATE_AGENT_LOOPBACK_PORT` to avoid routing that leg through the
|
|
361
|
+
public Gate. Keep the canonical HTTPS `HERDGATE_URL`; the room token and
|
|
362
|
+
public Host check still apply. See [deployment and rollback](DEPLOY.md#when-the-publisher-and-gateway-run-on-the-same-machine).
|
|
363
|
+
Do not set loopback on a laptop or other host with a remote Gate.
|
|
364
|
+
|
|
365
|
+
On Windows, `herdgate update` deploys the new adapter and preserves the
|
|
366
|
+
existing Mobile mode and device. On Linux, update and restart standalone
|
|
367
|
+
Mobile services separately; `herdgate update` updates only the main TUI
|
|
368
|
+
publisher. Neither operation updates the Gate or the VPS edge.
|
|
369
|
+
|
|
353
370
|
## The PWA (the device side)
|
|
354
371
|
|
|
355
372
|
The cloud serves the PWA itself (`src/web/`, `HERDGATE_WEB_ROOT`, `HERDGATE_NO_WEB=1` to disable). A phone
|
|
@@ -373,6 +390,32 @@ Verified live: real Herdr → publisher → cloud → **headless Chrome** signed
|
|
|
373
390
|
|
|
374
391
|
Going public: [DEPLOY.md](DEPLOY.md) (cloudflared, on this machine).
|
|
375
392
|
|
|
393
|
+
## Herdr skills for Pi
|
|
394
|
+
|
|
395
|
+
The npm package bundles six skills: `herdr`, `herdr-advisor`, `herdr-committee`,
|
|
396
|
+
`herdr-handoff`, `herdr-help` and `herdr-plugin` (sources: [`.agents/skills/`](.agents/skills)).
|
|
397
|
+
Starting with `0.9.31`, a global npm install with scripts enabled, the Windows
|
|
398
|
+
`herdgate install` bootstrap, and successful npm publisher `setup`, `migrate` or
|
|
399
|
+
`update` sync them for the current user. A local npm dependency install, a bare
|
|
400
|
+
`npx` fetch and a standalone host ZIP do not install user skills.
|
|
401
|
+
|
|
402
|
+
Pi discovers the managed pack in `~/.pi/agent/skills/herdgate`, or
|
|
403
|
+
`$PI_CODING_AGENT_DIR/skills/herdgate` for a custom agent directory. Use `/reload`
|
|
404
|
+
in an open Pi session or open Pi again; try `/skill:herdr-help`. Herdgate does not
|
|
405
|
+
install Pi, change its settings/trust, install an extension, or start an agent.
|
|
406
|
+
Python 3.11+ is optional for the profile and JSONL observation helper.
|
|
407
|
+
|
|
408
|
+
`herdgate pi-skills` syncs just the pack without touching the publisher. Set
|
|
409
|
+
`HERDGATE_NO_PI_SKILLS=1` before installation or update to skip syncing. The
|
|
410
|
+
installer leaves other skill folders and locally edited packs alone. Existing
|
|
411
|
+
same-name skills can cause Pi collision diagnostics; keep one copy active.
|
|
412
|
+
To remove only the managed copy, back up or remove the `skills/herdgate` folder
|
|
413
|
+
in your Pi profile; skip sync on later installs if you want it to stay removed.
|
|
414
|
+
The source checkout still provides project skills under the normal Pi trust rules.
|
|
415
|
+
|
|
416
|
+
For users working in this checkout: [skill guide](docs/herdr-skills/HERDR_SKILLS_GUIDE.md)
|
|
417
|
+
and [Herdgate research notes](docs/herdr-skills/HERDGATE_PI_OBSERVATION.md).
|
|
418
|
+
|
|
376
419
|
## Herdr-relay lineage
|
|
377
420
|
|
|
378
421
|
herdgate borrows its *ideas* from [herdr-relay](https://github.com/Lapis0875/herdr-relay) — hello-first token
|
package/bin/herdgate.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import { homedir, hostname } from "node:os";
|
|
|
11
11
|
import { spawnSync } from "node:child_process";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
13
|
import { manageCloud, resolveCloud } from "./cloud-config.mjs";
|
|
14
|
+
import { trySyncPiSkills } from "./pi-skills.mjs";
|
|
14
15
|
import { readConfig } from "../plugin/server/common.mjs";
|
|
15
16
|
import { withLatest } from "../windows/npm-update.mjs";
|
|
16
17
|
import { windowsNode } from "../windows/node-runtime.mjs";
|
|
@@ -21,6 +22,7 @@ const ROOT = dirname(HERE); // <pkg>
|
|
|
21
22
|
const help = `herdgate — every machine, one herd
|
|
22
23
|
|
|
23
24
|
herdgate install [--no-path] Install the persistent Windows command (no publisher restart).
|
|
25
|
+
herdgate pi-skills Sync the bundled skills into your Pi profile.
|
|
24
26
|
herdgate cloud add <name> <https-url>
|
|
25
27
|
herdgate cloud list
|
|
26
28
|
herdgate pair --cloud <name> Pair this machine with owner approval.
|
|
@@ -347,7 +349,10 @@ function managePublisher(cmd, args) {
|
|
|
347
349
|
|
|
348
350
|
const [cmd, ...args] = process.argv.slice(2);
|
|
349
351
|
try {
|
|
350
|
-
if (cmd === "setup-host")
|
|
352
|
+
if (cmd === "setup-host") {
|
|
353
|
+
setupHost();
|
|
354
|
+
trySyncPiSkills();
|
|
355
|
+
} else if (cmd === "pi-skills" && !args.length) trySyncPiSkills();
|
|
351
356
|
else if (cmd === "cloud") manageCloud(args);
|
|
352
357
|
else if (cmd === "pair") pairHost(args);
|
|
353
358
|
else if (process.platform === "win32" && (
|
package/bin/home-tui.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { dirname, isAbsolute, join } from 'node:path';
|
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
10
|
import { readConfig } from '../plugin/server/common.mjs';
|
|
11
|
+
import { trySyncPiSkills } from './pi-skills.mjs';
|
|
11
12
|
|
|
12
13
|
const unit = 'herdgate-home-tui.service';
|
|
13
14
|
const marker = '# Managed by Herdgate CLI\n';
|
|
@@ -136,6 +137,7 @@ async function setup(args) {
|
|
|
136
137
|
}
|
|
137
138
|
throw error;
|
|
138
139
|
}
|
|
140
|
+
trySyncPiSkills();
|
|
139
141
|
console.log('Herdgate publisher connected to Gate; no Herdr process was restarted.');
|
|
140
142
|
} finally { rmSync(lock, { recursive: true, force: true }); }
|
|
141
143
|
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Install only shipped resources into Pi's user skill directory; never edit Pi settings.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
export const piSkillFiles = [
|
|
9
|
+
...['herdr', 'herdr-advisor', 'herdr-committee', 'herdr-handoff', 'herdr-help', 'herdr-plugin'].map(name => `${name}/SKILL.md`),
|
|
10
|
+
'herdr/herdr_pi.py', 'herdr/profiles.example.toml',
|
|
11
|
+
].sort();
|
|
12
|
+
const source = fileURLToPath(new URL('../.agents/skills/', import.meta.url));
|
|
13
|
+
const marker = '.herdgate-skills-v1';
|
|
14
|
+
const stat = path => {
|
|
15
|
+
try { return lstatSync(path); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const packDirs = new Set(piSkillFiles.map(name => name.split('/')[0]));
|
|
19
|
+
const packFiles = new Set(piSkillFiles);
|
|
20
|
+
function hasExactLayout(root) {
|
|
21
|
+
const dirs = readdirSync(root, { withFileTypes: true });
|
|
22
|
+
if (dirs.length !== packDirs.size + 1) return false;
|
|
23
|
+
let count = 0;
|
|
24
|
+
for (const dir of dirs) {
|
|
25
|
+
if (dir.name === marker && dir.isFile()) continue;
|
|
26
|
+
if (!packDirs.has(dir.name) || !dir.isDirectory()) return false;
|
|
27
|
+
for (const entry of readdirSync(join(root, dir.name), { withFileTypes: true })) {
|
|
28
|
+
if (!entry.isFile() || !packFiles.has(`${dir.name}/${entry.name}`)) return false;
|
|
29
|
+
count++;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return count === packFiles.size;
|
|
33
|
+
}
|
|
34
|
+
const digest = files => {
|
|
35
|
+
const hash = createHash('sha256');
|
|
36
|
+
for (const [path, bytes] of files) hash.update(`${path}\0${bytes.length}\0`).update(bytes);
|
|
37
|
+
return hash.digest('hex');
|
|
38
|
+
};
|
|
39
|
+
const readPack = root => piSkillFiles.map(name => [name, readFileSync(join(root, name))]);
|
|
40
|
+
|
|
41
|
+
function syncPiSkills() {
|
|
42
|
+
if (process.env.HERDGATE_NO_PI_SKILLS === '1' || !stat(source)) return;
|
|
43
|
+
const home = homedir();
|
|
44
|
+
const override = process.env.PI_CODING_AGENT_DIR;
|
|
45
|
+
const agent = override ? resolve(override === '~' ? home : /^~[\\/]/.test(override) ? join(home, override.slice(2)) : override) : join(home, '.pi', 'agent');
|
|
46
|
+
const skills = join(agent, 'skills');
|
|
47
|
+
const dest = join(skills, 'herdgate');
|
|
48
|
+
const lock = join(skills, '.herdgate-skills.lock');
|
|
49
|
+
const files = readPack(source);
|
|
50
|
+
const next = digest(files);
|
|
51
|
+
mkdirSync(skills, { recursive: true, mode: 0o700 });
|
|
52
|
+
try { mkdirSync(lock, { mode: 0o700 }); }
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error.code !== 'EEXIST') throw error;
|
|
55
|
+
throw new Error('another skill sync is in progress (or left a stale .herdgate-skills.lock)');
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const existing = stat(dest);
|
|
59
|
+
if (existing) {
|
|
60
|
+
if (!existing.isDirectory() || !stat(join(dest, marker))?.isFile()) {
|
|
61
|
+
throw new Error('the destination is not managed by Herdgate; left untouched');
|
|
62
|
+
}
|
|
63
|
+
const prior = readFileSync(join(dest, marker), 'utf8');
|
|
64
|
+
if (!hasExactLayout(dest) || prior !== `${digest(readPack(dest))}\n`) {
|
|
65
|
+
throw new Error('the installed skill pack is locally modified; left untouched');
|
|
66
|
+
}
|
|
67
|
+
if (prior === `${next}\n`) return;
|
|
68
|
+
}
|
|
69
|
+
// Hidden staging/backup directories are not auto-discovered by Pi.
|
|
70
|
+
const stage = mkdtempSync(join(skills, '.herdgate-stage-'));
|
|
71
|
+
const backup = join(stage, 'previous');
|
|
72
|
+
const pending = join(stage, 'next');
|
|
73
|
+
try {
|
|
74
|
+
for (const [name, bytes] of files) {
|
|
75
|
+
const path = join(pending, name);
|
|
76
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
77
|
+
writeFileSync(path, bytes, { flag: 'wx', mode: 0o600 });
|
|
78
|
+
}
|
|
79
|
+
writeFileSync(join(pending, marker), `${next}\n`, { flag: 'wx', mode: 0o600 });
|
|
80
|
+
if (existing) renameSync(dest, backup);
|
|
81
|
+
try { renameSync(pending, dest); }
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (existing) renameSync(backup, dest);
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
rmSync(backup, { recursive: true, force: true });
|
|
87
|
+
} finally {
|
|
88
|
+
// If rollback also failed, preserve the backup rather than deleting the user's old pack.
|
|
89
|
+
if (stat(backup)) console.error(`Herdgate: previous skill pack kept at ${backup}`);
|
|
90
|
+
else rmSync(stage, { recursive: true, force: true });
|
|
91
|
+
}
|
|
92
|
+
console.error(`Herdgate: ${existing ? 'updated' : 'installed'} Pi skills at ${dest} (use /reload in Pi).`);
|
|
93
|
+
} finally { rmdirSync(lock); }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function trySyncPiSkills() {
|
|
97
|
+
try { syncPiSkills(); }
|
|
98
|
+
catch (error) { console.error(`Herdgate: could not sync Pi skills: ${error.message}`); }
|
|
99
|
+
}
|
package/dist-readme.md
CHANGED
|
@@ -45,6 +45,8 @@ khi cài mới hoặc `herdgate migrate`
|
|
|
45
45
|
để tiếp quản publisher cũ. Nếu bản cũ chưa lưu mode, khai đúng chế độ đang dùng:
|
|
46
46
|
`--mobile-act d_device`, `--mobile-read d_device`, `--hc <path>` hoặc `--plain`.
|
|
47
47
|
Không dừng publisher hay pair lại trước. `herdgate update` giữ mode đã lưu.
|
|
48
|
+
Bản npm từ 0.9.31 tự đồng bộ bộ skill vào profile Pi của user khi cài/cập nhật
|
|
49
|
+
Herdgate. Dùng `/reload` trong Pi để nhận thay đổi. ZIP này không chứa bộ skill.
|
|
48
50
|
|
|
49
51
|
Nếu dùng ZIP, mở PowerShell ở thư mục vừa giải nén. Trỏ thẳng đến Node 22 nếu
|
|
50
52
|
máy có nhiều bản Node (sửa đường dẫn nếu cần):
|
|
@@ -73,7 +75,10 @@ Mặc định publisher chỉ mở cầu nối TUI, không dùng desktop app hay
|
|
|
73
75
|
Mobile là opt-in: `--hc <path>` dùng Core thật; `--mobile-tui d_device`
|
|
74
76
|
chỉ đọc pane; `--mobile-tui-act d_device` cho phép nhập và resize đối với
|
|
75
77
|
đúng thiết bị đã được duyệt `act`. Adapter TUI không phải bản thay thế đầy đủ
|
|
76
|
-
cho Core.
|
|
78
|
+
cho Core. Từ `0.9.30`, Mobile TUI Act gửi ngay phản hồi đầu tiên sau lúc rảnh;
|
|
79
|
+
không cần bật thêm tùy chọn trên Windows. Loopback chỉ dành cho publisher
|
|
80
|
+
Linux chạy cùng máy với Gate, không dành cho laptop dùng Gate từ xa.
|
|
81
|
+
Cài ZIP không tự migrate hay nâng cấp máy nhà, Gate hoặc VPS.
|
|
77
82
|
|
|
78
83
|
## Bộ gồm
|
|
79
84
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bom0792/herdgate",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.31",
|
|
4
4
|
"description": "Cloud relay hub for herdr-core: every machine dials out, phones and browsers follow (PWA + SSH leg, E2E payloads).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"ssh-bridge": "node src/cloud/ssh-bridge.ts",
|
|
16
16
|
"ssh-tcp-edge": "node src/cloud/ssh-tcp-edge.ts",
|
|
17
17
|
"mobile-tui": "node src/host/mobile-tui.ts",
|
|
18
|
-
"postinstall": "node scripts/patch-ssh2.mjs"
|
|
18
|
+
"postinstall": "node scripts/patch-ssh2.mjs && node scripts/install-pi-skills.mjs"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"ssh2": "^1.17.0",
|
|
@@ -32,6 +32,9 @@
|
|
|
32
32
|
},
|
|
33
33
|
"files": [
|
|
34
34
|
"bin",
|
|
35
|
+
".agents/skills/herdr*/SKILL.md",
|
|
36
|
+
".agents/skills/herdr/herdr_pi.py",
|
|
37
|
+
".agents/skills/herdr/profiles.example.toml",
|
|
35
38
|
"src",
|
|
36
39
|
"app-mod",
|
|
37
40
|
"plugin",
|
package/plugin/server/ssh.mjs
CHANGED
|
@@ -89,7 +89,11 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
|
|
|
89
89
|
if (c.flushTimer) return;
|
|
90
90
|
c.flushTimer = setTimeout(() => {
|
|
91
91
|
c.flushTimer = null;
|
|
92
|
-
if (
|
|
92
|
+
if (c.closed || !c.outBuf.length) return;
|
|
93
|
+
sendOut(c, false);
|
|
94
|
+
// On a busy interactive channel keep batching subsequent chunks. After
|
|
95
|
+
// an idle period, the next response can leave without the batch delay.
|
|
96
|
+
if (c.lowLatency) scheduleFlush(c);
|
|
93
97
|
}, FLUSH_MS);
|
|
94
98
|
c.flushTimer.unref?.();
|
|
95
99
|
};
|
|
@@ -170,11 +174,15 @@ export function createSshBridge({ send, scopeOf, log = () => {}, resolve = resol
|
|
|
170
174
|
}
|
|
171
175
|
// Only the dedicated local read-only adapter may parse framed read RPC itself.
|
|
172
176
|
const trusted = !tui && scope === "read" && (trustedReadCore === bin || mobile);
|
|
173
|
-
const
|
|
177
|
+
const lowLatency = mobile && scope === "act" && args.includes("connect");
|
|
178
|
+
const c = { device, ch, scope, proc, trustedReadCore: trusted, lowLatency, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
|
|
174
179
|
channels.set(key(device, ch), c);
|
|
175
180
|
const onData = (chunk) => {
|
|
176
|
-
c.outBuf = Buffer.concat([c.outBuf, chunk]);
|
|
177
|
-
if (c.
|
|
181
|
+
c.outBuf = c.outBuf.length ? Buffer.concat([c.outBuf, chunk]) : chunk;
|
|
182
|
+
if (c.lowLatency && !c.flushTimer) {
|
|
183
|
+
sendOut(c, false);
|
|
184
|
+
scheduleFlush(c);
|
|
185
|
+
} else if (c.outBuf.length >= FLUSH_BYTES) sendOut(c, false);
|
|
178
186
|
else scheduleFlush(c);
|
|
179
187
|
};
|
|
180
188
|
proc.stdout?.on("data", onData);
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Runs an isolated Herdr server, Gate, publisher and TCP edge. Never uses live rooms or keys.
|
|
3
|
+
import assert from 'node:assert/strict';
|
|
4
|
+
import { execFile, spawn } from 'node:child_process';
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { once } from 'node:events';
|
|
7
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { dirname, join, resolve } from 'node:path';
|
|
10
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { promisify, stripVTControlCharacters } from 'node:util';
|
|
13
|
+
import { Client } from 'ssh2';
|
|
14
|
+
import { HerdGateAgent } from '../src/agent/index.ts';
|
|
15
|
+
import { startCloud } from '../src/cloud/gateway.ts';
|
|
16
|
+
import { startTcpEdge } from '../src/cloud/ssh-tcp-edge.ts';
|
|
17
|
+
import { State } from '../src/cloud/stores.ts';
|
|
18
|
+
import { createSshBridge } from '../plugin/server/ssh.mjs';
|
|
19
|
+
import { openTerminal } from '../plugin/server/mobile-tui-stream.mjs';
|
|
20
|
+
|
|
21
|
+
const run = promisify(execFile);
|
|
22
|
+
const herdr = process.env.TEST_HERDR_BIN;
|
|
23
|
+
if (!herdr || resolve(herdr) !== herdr) throw new Error('Set TEST_HERDR_BIN to the absolute path to Herdr');
|
|
24
|
+
const rounds = Number(process.argv[2] ?? 24);
|
|
25
|
+
if (!Number.isInteger(rounds) || rounds < 1 || rounds > 100) throw new Error('Pass 1 to 100 rounds');
|
|
26
|
+
const root = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
27
|
+
const adapter = join(root, 'plugin/server/mobile-tui-core.mjs');
|
|
28
|
+
const dir = await mkdtemp(join(tmpdir(), 'herdgate-mobile-bench-'));
|
|
29
|
+
const env = {
|
|
30
|
+
HOME: dir, PATH: process.env.PATH, LANG: process.env.LANG,
|
|
31
|
+
SHELL: '/bin/sh', XDG_CONFIG_HOME: join(dir, 'config'), XDG_STATE_HOME: join(dir, 'state'),
|
|
32
|
+
XDG_DATA_HOME: join(dir, 'data'), HERDR_SOCKET_PATH: join(dir, 'herdr.sock'), HERDR_BIN_PATH: herdr,
|
|
33
|
+
};
|
|
34
|
+
const host = (...args) => run(herdr, args, { env, cwd: dir, timeout: 5000 });
|
|
35
|
+
const stats = (samples) => {
|
|
36
|
+
if (!samples.length) return undefined;
|
|
37
|
+
const s = samples.toSorted((a, b) => a - b);
|
|
38
|
+
const at = (p) => +s[Math.ceil(p * s.length) - 1].toFixed(1);
|
|
39
|
+
return { n: s.length, p50: at(0.50), p95: at(0.95), max: at(1) };
|
|
40
|
+
};
|
|
41
|
+
const deadline = (promise, label) => {
|
|
42
|
+
const ctrl = new AbortController();
|
|
43
|
+
return Promise.race([promise, delay(6500, undefined, { signal: ctrl.signal, ref: false }).then(() => { throw new Error(`Timeout: ${label}`); })]).finally(() => ctrl.abort());
|
|
44
|
+
};
|
|
45
|
+
const elapsed = (since) => performance.now() - since;
|
|
46
|
+
const rpc = (id, method, params) => JSON.stringify({ jsonrpc: '2.0', id, method, params });
|
|
47
|
+
const marker = () => randomBytes(5).toString('hex');
|
|
48
|
+
|
|
49
|
+
async function coreBench(input, output, letters) {
|
|
50
|
+
let buf = Buffer.alloc(0);
|
|
51
|
+
let id = 0;
|
|
52
|
+
const raw = output[Symbol.asyncIterator]();
|
|
53
|
+
const fill = async () => {
|
|
54
|
+
const next = await raw.next();
|
|
55
|
+
assert.ok(!next.done, 'Core stream ended');
|
|
56
|
+
buf = Buffer.concat([buf, next.value]);
|
|
57
|
+
};
|
|
58
|
+
const send = (channel, kind, payload = Buffer.alloc(0)) => {
|
|
59
|
+
const head = Buffer.alloc(9);
|
|
60
|
+
head.writeUInt32LE(channel);
|
|
61
|
+
head[4] = kind;
|
|
62
|
+
head.writeUInt32LE(payload.length, 5);
|
|
63
|
+
input.write(Buffer.concat([head, payload]));
|
|
64
|
+
};
|
|
65
|
+
const read = async () => {
|
|
66
|
+
while (buf.length < 9) await fill();
|
|
67
|
+
const end = 9 + buf.readUInt32LE(5);
|
|
68
|
+
while (buf.length < end) await fill();
|
|
69
|
+
const value = { channel: buf.readUInt32LE(0), kind: buf[4], body: buf.subarray(9, end), time: performance.now() };
|
|
70
|
+
buf = buf.subarray(end);
|
|
71
|
+
if (value.channel !== 0 && value.kind === 0) {
|
|
72
|
+
const credit = Buffer.alloc(4);
|
|
73
|
+
credit.writeUInt32LE(value.body.length);
|
|
74
|
+
send(value.channel, 1, credit);
|
|
75
|
+
}
|
|
76
|
+
return value;
|
|
77
|
+
};
|
|
78
|
+
const request = (method, params) => {
|
|
79
|
+
send(0, 0, Buffer.from(rpc(++id, method, params)));
|
|
80
|
+
return id;
|
|
81
|
+
};
|
|
82
|
+
const response = async (want) => {
|
|
83
|
+
for (;;) {
|
|
84
|
+
const f = await read();
|
|
85
|
+
if (f.channel !== 0) continue;
|
|
86
|
+
const reply = JSON.parse(f.body.toString());
|
|
87
|
+
if (reply.id !== want) continue;
|
|
88
|
+
assert.ok(reply.result, JSON.stringify(reply.error));
|
|
89
|
+
return reply.result;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const helloStart = performance.now();
|
|
93
|
+
input.write(rpc(++id, 'hello', { framed: true }) + '\n');
|
|
94
|
+
await deadline((async () => {
|
|
95
|
+
while (!buf.includes(10)) await fill();
|
|
96
|
+
const nl = buf.indexOf(10);
|
|
97
|
+
assert.equal(JSON.parse(buf.subarray(0, nl)).result.framed, true);
|
|
98
|
+
buf = buf.subarray(nl + 1);
|
|
99
|
+
})(), 'Core hello');
|
|
100
|
+
const hello = elapsed(helloStart);
|
|
101
|
+
const { terminals } = await deadline(response(request('terminal.list')), 'list');
|
|
102
|
+
assert.equal(terminals.length, 1, 'benchmark must address only its isolated pane');
|
|
103
|
+
const terminal = terminals[0].address;
|
|
104
|
+
const attachStart = performance.now();
|
|
105
|
+
const { channel } = await deadline(response(request('terminal.attach', { terminal, cols: 120, rows: 28 })), 'attach');
|
|
106
|
+
for (;;) {
|
|
107
|
+
const f = await deadline(read(), 'first paint');
|
|
108
|
+
if (f.channel === channel && f.kind === 0) break;
|
|
109
|
+
}
|
|
110
|
+
const attach = elapsed(attachStart);
|
|
111
|
+
const key = [], sendPaint = [], sendAck = [], keyPaintBytes = [];
|
|
112
|
+
for (let i = 0; i < rounds; i++) {
|
|
113
|
+
const wanted = `k-${marker()}`;
|
|
114
|
+
const start = performance.now();
|
|
115
|
+
send(channel, 0, Buffer.from(wanted));
|
|
116
|
+
let text = '', bytes = 0;
|
|
117
|
+
while (!text.includes(wanted)) {
|
|
118
|
+
const f = await deadline(read(), 'key echo');
|
|
119
|
+
assert.equal(f.channel, channel);
|
|
120
|
+
assert.notEqual(f.kind, 2);
|
|
121
|
+
if (f.kind !== 0) continue;
|
|
122
|
+
text += stripVTControlCharacters(f.body.toString());
|
|
123
|
+
bytes += f.body.length;
|
|
124
|
+
}
|
|
125
|
+
key.push(elapsed(start));
|
|
126
|
+
keyPaintBytes.push(bytes);
|
|
127
|
+
send(channel, 0, Buffer.from([0x15])); // Ctrl+U clears the isolated shell line.
|
|
128
|
+
await delay(125);
|
|
129
|
+
// Alternate every glyph. Herdr can omit unchanged cells from its ANSI deltas.
|
|
130
|
+
const letter = letters[i % 2];
|
|
131
|
+
const suffix = letter.repeat(12);
|
|
132
|
+
const command = `printf '\\033[2J\\033[H'; printf '%s' ${Array(12).fill(letter).join(' ')}; printf '\\n'`;
|
|
133
|
+
const startSend = performance.now();
|
|
134
|
+
const req = request('terminal.send', { terminal, text: command });
|
|
135
|
+
let ack = false, painted = false, seen = '';
|
|
136
|
+
while (!ack || !painted) {
|
|
137
|
+
const f = await deadline(read(), `Send ${i + 1} (ack=${ack}, painted=${painted})`);
|
|
138
|
+
if (f.channel === 0) {
|
|
139
|
+
const msg = JSON.parse(f.body);
|
|
140
|
+
if (msg.id === req) {
|
|
141
|
+
assert.ok(msg.result, JSON.stringify(msg.error));
|
|
142
|
+
sendAck.push(f.time - startSend);
|
|
143
|
+
ack = true;
|
|
144
|
+
}
|
|
145
|
+
} else if (f.channel === channel && f.kind === 0 && !painted) {
|
|
146
|
+
seen += stripVTControlCharacters(f.body.toString());
|
|
147
|
+
if (seen.includes(suffix)) {
|
|
148
|
+
painted = true;
|
|
149
|
+
sendPaint.push(f.time - startSend);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
await delay(125);
|
|
154
|
+
}
|
|
155
|
+
send(channel, 2);
|
|
156
|
+
return { hello, attach, keyMs: stats(key), sendPaintMs: stats(sendPaint), sendAckMs: stats(sendAck), keyPaintBytes: stats(keyPaintBytes) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
let server, cloud, edge, publisher, bridge;
|
|
160
|
+
try {
|
|
161
|
+
await mkdir(join(dir, 'config/herdr'), { recursive: true });
|
|
162
|
+
server = spawn(herdr, ['server'], { env, cwd: dir, stdio: 'ignore' });
|
|
163
|
+
const until = performance.now() + 5000;
|
|
164
|
+
while (!await host('status', 'server', '--json').then(({ stdout }) => JSON.parse(stdout).running, () => false)) {
|
|
165
|
+
if (performance.now() > until) throw new Error('Isolated Herdr server did not start');
|
|
166
|
+
await delay(50);
|
|
167
|
+
}
|
|
168
|
+
await host('workspace', 'create', '--cwd', dir, '--label', 'bench-mobile', '--focus');
|
|
169
|
+
const panes = JSON.parse((await host('pane', 'list')).stdout).result.panes;
|
|
170
|
+
assert.equal(panes.length, 1);
|
|
171
|
+
const pane = panes[0];
|
|
172
|
+
await host('pane', 'run', pane.pane_id, "PS1='bench> '; export PS1");
|
|
173
|
+
// Measure Herdr's native controller alone, before Core framing and SSH.
|
|
174
|
+
const oldSocket = process.env.HERDR_SOCKET_PATH;
|
|
175
|
+
process.env.HERDR_SOCKET_PATH = env.HERDR_SOCKET_PATH;
|
|
176
|
+
const nativeSamples = [];
|
|
177
|
+
let native;
|
|
178
|
+
try {
|
|
179
|
+
native = await openTerminal(herdr, pane.terminal_id, 120, 28);
|
|
180
|
+
for (let i = 0; i < rounds; i++) {
|
|
181
|
+
const wanted = `n-${marker()}`;
|
|
182
|
+
const start = performance.now();
|
|
183
|
+
await native.send({ type: 'terminal.input', bytes: Buffer.from(wanted).toString('base64') });
|
|
184
|
+
let text = '';
|
|
185
|
+
while (!text.includes(wanted)) {
|
|
186
|
+
const paint = await deadline(native.frames.next(), 'native echo');
|
|
187
|
+
assert.equal(paint.done, false);
|
|
188
|
+
text += stripVTControlCharacters(paint.value.bytes.toString());
|
|
189
|
+
}
|
|
190
|
+
nativeSamples.push(elapsed(start));
|
|
191
|
+
await native.send({ type: 'terminal.input', bytes: 'FQ==' });
|
|
192
|
+
await delay(150);
|
|
193
|
+
}
|
|
194
|
+
} finally {
|
|
195
|
+
native?.close();
|
|
196
|
+
if (oldSocket === undefined) delete process.env.HERDR_SOCKET_PATH;
|
|
197
|
+
else process.env.HERDR_SOCKET_PATH = oldSocket;
|
|
198
|
+
}
|
|
199
|
+
console.log(JSON.stringify({ route: 'Herdr native controller', keyMs: stats(nativeSamples) }));
|
|
200
|
+
await delay(250);
|
|
201
|
+
const child = spawn(process.execPath, [adapter, '--interactive', 'connect'], { env, cwd: dir });
|
|
202
|
+
const childExit = once(child, 'close');
|
|
203
|
+
try { console.log(JSON.stringify({ route: 'Core adapter (local pipes)', ...await coreBench(child.stdin, child.stdout, 'AB') })); }
|
|
204
|
+
finally { child.stdin.end(); await deadline(childExit, 'adapter exit').catch(() => child.kill()); }
|
|
205
|
+
await delay(250);
|
|
206
|
+
|
|
207
|
+
const account = { id: 'bench', name: 'bench', token: marker() };
|
|
208
|
+
const statePath = join(dir, 'gate.json');
|
|
209
|
+
const state = new State([account], statePath);
|
|
210
|
+
const room = state.addRoom(account.id, 'bench');
|
|
211
|
+
const { device, secret } = state.addDevice(room.room, 'bench-act', 'act');
|
|
212
|
+
cloud = await startCloud({ accounts: [account], statePath, log: () => {}, ssh: { port: 0, keyPath: join(dir, 'gate-key.json') } });
|
|
213
|
+
edge = await startTcpEdge({ gate: `http://127.0.0.1:${cloud.port}`, port: 0 });
|
|
214
|
+
bridge = createSshBridge({
|
|
215
|
+
tuiOnly: true, mobileTuiAdapter: { device: device.id, scope: 'act', script: adapter },
|
|
216
|
+
scopeOf: (id) => publisher.scopeOf(id), send: (id, body) => publisher.send(id, body),
|
|
217
|
+
spawnImpl: (bin, args, opts) => spawn(bin, args, { ...opts, env, cwd: dir }),
|
|
218
|
+
});
|
|
219
|
+
publisher = new HerdGateAgent({ endpoint: `ws://127.0.0.1:${cloud.port}/v1/agent/ws`, roomToken: room.token, adapter: {
|
|
220
|
+
info: () => ({ name: 'bench', version: 'test' }), onFrame: (id, body) => { bridge.handle(id, body); },
|
|
221
|
+
onDevices: () => {}, onPairAsk: () => false,
|
|
222
|
+
} });
|
|
223
|
+
publisher.start();
|
|
224
|
+
await deadline(publisher.firstHello, 'publisher hello');
|
|
225
|
+
const client = new Client();
|
|
226
|
+
client.on('error', () => {});
|
|
227
|
+
try {
|
|
228
|
+
const start = performance.now();
|
|
229
|
+
const ready = once(client, 'ready');
|
|
230
|
+
client.connect({ host: '127.0.0.1', port: edge.port, username: device.id, password: secret, readyTimeout: 5000 });
|
|
231
|
+
await deadline(ready, 'SSH ready');
|
|
232
|
+
const sshReady = elapsed(start);
|
|
233
|
+
const stream = await deadline(new Promise((res, rej) => client.exec('hc connect', (err, channel) => err ? rej(err) : res(channel))), 'SSH exec');
|
|
234
|
+
stream.stderr.resume();
|
|
235
|
+
console.log(JSON.stringify({ route: 'TCP edge + Gate + publisher (all local)', sshReady, ...await coreBench(stream, stream, 'CD') }));
|
|
236
|
+
stream.end();
|
|
237
|
+
} finally { client.end(); }
|
|
238
|
+
} finally {
|
|
239
|
+
bridge?.closeAll();
|
|
240
|
+
publisher?.stop();
|
|
241
|
+
await edge?.close();
|
|
242
|
+
await cloud?.close();
|
|
243
|
+
await host('server', 'stop').catch(() => {});
|
|
244
|
+
if (server && server.exitCode === null && server.signalCode === null) server.kill();
|
|
245
|
+
await rm(dir, { recursive: true, force: true });
|
|
246
|
+
}
|
package/src/host/mobile-tui.ts
CHANGED
|
@@ -9,6 +9,13 @@ const url = new URL(process.env.HERDGATE_URL);
|
|
|
9
9
|
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
10
10
|
throw new Error("HERDGATE_URL must be an HTTPS origin");
|
|
11
11
|
}
|
|
12
|
+
const loopback = process.env.HERDGATE_AGENT_LOOPBACK_PORT;
|
|
13
|
+
if (loopback !== undefined && (!/^[1-9]\d{0,4}$/.test(loopback) || Number(loopback) > 65535)) {
|
|
14
|
+
throw new Error("HERDGATE_AGENT_LOOPBACK_PORT must be a port from 1 to 65535");
|
|
15
|
+
}
|
|
16
|
+
const endpoint = loopback
|
|
17
|
+
? `ws://127.0.0.1:${loopback}/v1/agent/ws`
|
|
18
|
+
: `wss://${url.host}/v1/agent/ws`;
|
|
12
19
|
const token = process.env.HERDGATE_ROOM_TOKEN;
|
|
13
20
|
if (!token) throw new Error("configure a dedicated room token for the TUI mobile pilot");
|
|
14
21
|
const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
|
|
@@ -35,7 +42,10 @@ const bridge = createSshBridge({
|
|
|
35
42
|
});
|
|
36
43
|
|
|
37
44
|
const agent = new HerdGateAgent({
|
|
38
|
-
endpoint
|
|
45
|
+
endpoint, roomToken: token,
|
|
46
|
+
log: (line) => log(loopback && line.startsWith("cloud hello:") ? `${line} via loopback 127.0.0.1:${loopback}` : line),
|
|
47
|
+
// Only a co-located Gate may use plaintext. Preserve its public Host check.
|
|
48
|
+
wsOptions: loopback ? { headers: { Host: url.host }, agent: false, handshakeTimeout: 5000, perMessageDeflate: false } : undefined,
|
|
39
49
|
adapter: {
|
|
40
50
|
info: () => ({ name, version: "tui-core-pilot", capabilities: [controller ? "interactive" : "read-only"] }),
|
|
41
51
|
onPairAsk: () => false,
|
package/windows/install-cli.mjs
CHANGED
|
@@ -16,7 +16,7 @@ function directory(path) {
|
|
|
16
16
|
if (!lstatSync(path).isDirectory()) throw new Error(`expected a real directory: ${path}`);
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
function inputs() {
|
|
19
|
+
async function inputs() {
|
|
20
20
|
function files(dir) {
|
|
21
21
|
return readdirSync(join(source, dir), { withFileTypes: true }).flatMap((file) => {
|
|
22
22
|
const name = `${dir}/${file.name}`;
|
|
@@ -26,11 +26,16 @@ function inputs() {
|
|
|
26
26
|
const runtime = ["plugin", "windows"];
|
|
27
27
|
// ZIPs built before the standalone command do not contain these npm assets.
|
|
28
28
|
for (const dir of ["bin", "app-mod", "templates"]) if (stat(join(source, dir))?.isDirectory()) runtime.push(dir);
|
|
29
|
-
|
|
29
|
+
const assets = runtime.flatMap(files);
|
|
30
|
+
if (stat(join(source, ".agents", "skills"))?.isDirectory()) {
|
|
31
|
+
const { piSkillFiles } = await import("../bin/pi-skills.mjs");
|
|
32
|
+
assets.push(...piSkillFiles.map(name => `.agents/skills/${name}`));
|
|
33
|
+
}
|
|
34
|
+
return assets.sort();
|
|
30
35
|
}
|
|
31
36
|
|
|
32
|
-
function installRelease(releases) {
|
|
33
|
-
const files = inputs().map((name) => [name, readFileSync(join(source, name))]);
|
|
37
|
+
async function installRelease(releases) {
|
|
38
|
+
const files = (await inputs()).map((name) => [name, readFileSync(join(source, name))]);
|
|
34
39
|
const hash = createHash("sha256");
|
|
35
40
|
for (const [name, contents] of files) hash.update(`${name}\0${contents.length}\0`).update(contents);
|
|
36
41
|
const id = `tui-${hash.digest("hex").slice(0, 16)}`;
|
|
@@ -168,7 +173,7 @@ try {
|
|
|
168
173
|
const lock = join(root, ".installing");
|
|
169
174
|
mkdirSync(lock);
|
|
170
175
|
try {
|
|
171
|
-
const id = use ?? installRelease(releases);
|
|
176
|
+
const id = use ?? await installRelease(releases);
|
|
172
177
|
if (stage) {
|
|
173
178
|
console.log(id);
|
|
174
179
|
} else if (command) {
|
|
@@ -187,6 +192,11 @@ try {
|
|
|
187
192
|
installShim(root, "herdgate-tui.cmd", "current\\windows\\cli.mjs", "@rem Herdgate TUI CLI");
|
|
188
193
|
console.log(`Herdgate TUI CLI: ${id}\nShim: ${join(root, "bin", "herdgate-tui.cmd")}`);
|
|
189
194
|
}
|
|
195
|
+
// Stage/rollback never install skills; sync only after a successful install or CLI refresh.
|
|
196
|
+
if (!stage && (command || !use) && stat(join(source, "bin", "pi-skills.mjs"))?.isFile()) {
|
|
197
|
+
const { trySyncPiSkills } = await import("../bin/pi-skills.mjs");
|
|
198
|
+
trySyncPiSkills();
|
|
199
|
+
}
|
|
190
200
|
} finally {
|
|
191
201
|
rmSync(lock, { force: true, recursive: true });
|
|
192
202
|
}
|
package/windows/setup-tui.mjs
CHANGED
|
@@ -14,6 +14,7 @@ function invoke(file, args) {
|
|
|
14
14
|
const child = spawnSync(process.execPath, [file, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout: 30_000 });
|
|
15
15
|
if (child.error) throw child.error;
|
|
16
16
|
if (child.status !== 0) throw new Error(child.stderr.trim() || `${args[0]} failed (${child.status})`);
|
|
17
|
+
if (child.stderr) process.stderr.write(child.stderr);
|
|
17
18
|
return child.stdout.trim();
|
|
18
19
|
}
|
|
19
20
|
function storedProfile(path) {
|