@bom0792/herdgate 0.9.35 → 0.9.37
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 +44 -5
- package/.agents/skills/herdr-advisor/SKILL.md +1 -1
- package/.agents/skills/herdr-committee/SKILL.md +1 -1
- package/.agents/skills/herdr-handoff/SKILL.md +1 -1
- package/bin/herdgate.mjs +5 -1
- package/package.json +1 -1
- package/plugin/server/e2e.mjs +27 -0
- package/plugin/server/index.mjs +106 -4
- package/plugin/server/mobile-tui-core.mjs +590 -26
- package/plugin/server/mobile-tui-stream.mjs +4 -2
- package/plugin/server/pi-receipt-watch.d.mts +24 -0
- package/plugin/server/pi-receipt-watch.mjs +99 -0
- package/plugin/server/pi-receipts.d.mts +12 -0
- package/plugin/server/pi-receipts.mjs +114 -3
- package/plugin/server/pi-worker.d.mts +7 -0
- package/plugin/server/pi-worker.mjs +29 -1
- package/src/cloud/gateway.ts +8 -8
- package/src/cloud/sshd.ts +14 -11
- package/src/cloud/util.ts +10 -0
- package/src/web/app.css +23 -0
- package/src/web/app.js +175 -4
- package/src/web/e2e.js +29 -2
|
@@ -54,12 +54,13 @@ Các mẫu lệnh còn lại dùng cú pháp Bash. Trong PowerShell, gọi binar
|
|
|
54
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
55
|
|
|
56
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`.
|
|
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`. Muốn kết quả tự về thì đăng ký watch cho ID đó trước khi gửi (xem quy trình chung bước 4); sau đó `observe <request-id> --pane <pane-id>` chỉ để đối chiếu thêm khi báo cáo đã đến hoặc khi cần tra cứu. 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
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
59
|
|
|
60
60
|
## Quy trình chung khi được yêu cầu tạo agent
|
|
61
61
|
|
|
62
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
|
+
Pi mới dùng settings/provider/tài nguyên của user và workspace trên máy đích. Khi người dùng yêu cầu override, truyền cờ Pi đã xác minh sau `--` bằng argv riêng (ví dụ `--model provider/id --thinking high`; tool, skill, extension và session flags theo `pi --help` tại máy đích). `agent prompt` vào Pi đã mở dùng model/thinking hiện tại; không gắn cờ khởi chạy vào nội dung prompt.
|
|
63
64
|
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
|
|
|
65
66
|
```bash
|
|
@@ -72,10 +73,48 @@ Nếu có Python 3.11+ và file `herdr_pi.py` đi kèm **trong thư mục của
|
|
|
72
73
|
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
|
|
|
74
75
|
```bash
|
|
75
|
-
"$H" agent prompt "$pane_id" "$brief" --wait
|
|
76
|
-
"$H" agent get "$pane_id"
|
|
77
|
-
"$H" agent read "$pane_id" --source recent-unwrapped --lines 120
|
|
76
|
+
"$H" agent prompt "$pane_id" "$brief" # gửi một lần, KHÔNG --wait — không chờ kết quả
|
|
78
77
|
```
|
|
79
78
|
|
|
80
|
-
4.
|
|
79
|
+
4. **Subagent tự báo cáo lại; controller không chờ.** Đăng ký watch cho request ID **trước khi gửi**, kết quả tự đẩy về khi agent settle:
|
|
80
|
+
- Listener riêng (tiến trình/terminal khác controller): `node experiments/pi-receipt/query.mjs --gate … --device d --secret s --id <uuid> --wait --body --out <file-new>` — push đến thì tải reply, lưu file 0600 và ACK tự động.
|
|
81
|
+
- MCP client có cấu hình herdgate: `herdgate_receipt_wait` / `herdgate_receipt` / `herdgate_receipt_body`.
|
|
82
|
+
- Tự viết client: frame `receipt.watch {id, wantBody}` rồi `receipt.ack {id}` sau khi xử lý; mất kết nối thì publisher phát lại push chưa ACK khi nối lại.
|
|
83
|
+
|
|
84
|
+
Cấm: `agent prompt --wait`/`--timeout` để chờ nhiệm vụ (đó là chờ đồng bộ trên controller), vòng lặp `agent get`/`agent read`, `sleep`, polling pane. `agent start --timeout` chỉ chờ readiness khi khởi tạo agent — vẫn hợp lệ. `agent prompt` trả ok chứng nhận input đã xếp, không phải agent đã nhận việc hay hoàn thành. Khi báo cáo về: `replied` chứng minh có reply cuối đúng request (kèm usage), không khẳng định task nghiệp vụ thành công; `observe`/`agent read` chỉ để đối chiếu bổ sung sau khi báo cáo đến, hoặc khi người dùng yêu cầu tra cứu. Nếu chưa có watch/forwarder nào: ghi rõ "đã submit, báo cáo sẽ tự về" và kết thúc lượt, không chuyển sang chờ.
|
|
81
85
|
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**.
|
|
86
|
+
|
|
87
|
+
## Spawn subagent và mở lại session (Herdgate helper)
|
|
88
|
+
|
|
89
|
+
Pane chết không mất session — nhưng tra cứu tay thì phiến nghiệp. Dùng helper Herdgate
|
|
90
|
+
(`experiments/pi-spawn/spawn.mjs`): **một UUID làm cả request id lẫn `pi --session-id`**,
|
|
91
|
+
biết session ngay lúc spawn, quan hệ cha-con (session controller → session con) ghi bền
|
|
92
|
+
vào `spawns.jsonl` cạnh journal receipt:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
node experiments/pi-spawn/spawn.mjs spawn reviewer --cwd /home/bom/source # trả {id, paneId, bound:true}
|
|
96
|
+
# ... arm/watch/gửi việc theo id đó như quy trình trên ...
|
|
97
|
+
node experiments/pi-spawn/spawn.mjs list # cây con + pane còn sống không
|
|
98
|
+
node experiments/pi-spawn/spawn.mjs restore reviewer # mở lại ĐÚNG session, một lệnh
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Helper dùng `pi --session-id <id>` (mở session có id đó, không có thì tạo — idempotent);
|
|
102
|
+
chạy bên trong pane Herdr thì tự nhận parent session. Không lưu prompt/answer trong registry.
|
|
103
|
+
|
|
104
|
+
Thủ công (fallback khi không có helper):
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
Pane chết không mất session — Pi session là file. Khôi phục đúng quy trình (khác với quy tắc
|
|
108
|
+
"không resume cho agent mới": đây là trả lại đúng session cũ của pane đó):
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
PANE=$("$H" pane split --current --direction right --no-focus --cwd /home/bom/source | jq -r .result.pane.pane_id)
|
|
112
|
+
"$H" agent start <tên> --kind pi --pane "$PANE" --timeout 45000 -- --session <session-id|đường-dẫn-file>
|
|
113
|
+
"$H" pane list # xác minh agent_session trỏ đúng file session cũ
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Cờ sau `--` truyền thẳng cho Pi; **dùng `--session <id|path>`** — `--resume` không nhận id,
|
|
117
|
+
nó mở menu chọn tương tác và agent sẽ không ràng buộc session. **Không dùng `pane run 'pi …'`
|
|
118
|
+
để khởi chạy/khôi phục agent**: phản hồi của `pane run` chỉ là "input đã xếp", không chờ readiness,
|
|
119
|
+
không ràng buộc agent — agent sẽ hiện không có session và controller không quản lý được.
|
|
120
|
+
Muốn đóng agent: `/quit` trong pane đó, đợi shell prompt; đóng pane phải do người dùng quyết định.
|
|
@@ -9,4 +9,4 @@ description: 'Dùng một agent trong Herdr TUI để lấy góc nhìn thứ hai
|
|
|
9
9
|
|
|
10
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
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
|
|
12
|
+
3. Gửi một lần bằng `agent prompt` **không `--wait`**: advisor tự báo cáo lại qua watch receipt (đăng ký ID trước khi gửi — xem quy trình trong skill herdr); không polling, `sleep` hay vòng `agent get` chờ. Nếu dùng Pi với helper, tạo request marker trước khi gửi và `observe` đúng request **sau khi báo cáo về**; nếu không có helper thì `agent get`/`agent read` kèm giới hạn chỉ khi cần tra cứu. 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 báo cáo chưa về trong lượt này, nói rõ đang chờ push thay vì giả sử kết quả. Dừng sau vòng này; không chỉnh code hay đóng pane thay người dùng.
|
|
@@ -8,6 +8,6 @@ description: 'Dùng hai agent trong Herdr TUI để phân tích độc lập, ph
|
|
|
8
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
9
|
|
|
10
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`
|
|
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 đăng ký watch riêng cho từng ID (báo cáo tự đẩy về từng request — xem skill herdr); `observe` từng pane/ID chỉ để đối chiếu sau. Gửi hai lời gọi `agent prompt` (không `--wait`) độc lập; không polling hay `sleep` chờ từng agent. `agent prompt` trả ok chỉ chứng nhận input đã xếp, không phải agent đã nhận việc. Không dùng `agent wait` rời như bằng chứng prompt đã được nhận.
|
|
12
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
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.
|
|
@@ -16,4 +16,4 @@ description: 'Bàn giao công việc hiện tại cho một agent mới trong He
|
|
|
16
16
|
|
|
17
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
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
|
|
19
|
+
4. Gửi một lần bằng `agent prompt` theo skill gốc, **không `--wait`**: agent nhận việc tự báo cáo lại qua watch receipt cho ID đã đánh dấu (đăng ký trước khi gửi); không polling hay `sleep` chờ. Với Pi/helper, đặt marker request ở dòng đầu và giữ ID để watch/đối chiếu sau; không tự resend nếu chưa thấy ACK. 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.
|
package/bin/herdgate.mjs
CHANGED
|
@@ -387,6 +387,10 @@ function promptSecret(question) {
|
|
|
387
387
|
|
|
388
388
|
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
389
389
|
|
|
390
|
+
/** POSIX single-quoting: safe to paste into sh/bash for any label bytes
|
|
391
|
+
* (JSON quoting leaves $ and ` live inside double quotes). */
|
|
392
|
+
const shellQuote = (s) => `'${String(s).replaceAll("'", "'\\''")}'`;
|
|
393
|
+
|
|
390
394
|
function gateWs(origin) {
|
|
391
395
|
const url = origin.replace(/^http/, "ws") + "/v1/device/ws";
|
|
392
396
|
const ws = new WebSocket(url);
|
|
@@ -540,7 +544,7 @@ async function connectController() {
|
|
|
540
544
|
console.log(`paired this machine with ${results.length} machine(s) on ${origin} (scope ${scope}):`);
|
|
541
545
|
for (const r of results) {
|
|
542
546
|
console.log(` ${r.room.name} → ssh host '${r.alias}' (device ${r.deviceId}, key ${r.fp})`);
|
|
543
|
-
console.log(` herdr machine add ${r.alias} --label ${
|
|
547
|
+
console.log(` herdr machine add ${r.alias} --label ${shellQuote(r.room.name)} --remote-session default`);
|
|
544
548
|
}
|
|
545
549
|
console.log("The owner token and device secrets were not stored. The first ssh connection pins the gate's host key.");
|
|
546
550
|
console.log("If this machine was connected before, revoke its previous device in the PWA roster.");
|
package/package.json
CHANGED
package/plugin/server/e2e.mjs
CHANGED
|
@@ -22,6 +22,21 @@ export const NOISE_NAME = "Noise_XX_P256_AESGCM_SHA256";
|
|
|
22
22
|
export const KEY_LEN = 32;
|
|
23
23
|
export const PUB_LEN = 65; // uncompressed P-256 point: 0x04 ‖ X ‖ Y
|
|
24
24
|
|
|
25
|
+
/** Session lifetime (Paseo lesson: handshake lifetime). A transport key that lives
|
|
26
|
+
* forever erodes forward secrecy — compromising it exposes the WHOLE session since
|
|
27
|
+
* the handshake. Rotation fences exposure to the slice since the last handshake.
|
|
28
|
+
* Bounds: messages per direction (far under nonce exhaustion at 2^32) or wall time,
|
|
29
|
+
* whichever comes first. The device initiates; the host's `e2e.init` handler swaps
|
|
30
|
+
* the session in place, so rotation is just a fresh handshake. */
|
|
31
|
+
export const REKEY_AFTER_MESSAGES = 2 ** 24;
|
|
32
|
+
export const REKEY_AFTER_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
/** True when a READY channel has reached either lifetime bound. */
|
|
35
|
+
export function needsRekey(ch, now = Date.now()) {
|
|
36
|
+
if (!ch?.ready()) return false;
|
|
37
|
+
return ch.usage() >= REKEY_AFTER_MESSAGES || now - ch.handshakeAt >= REKEY_AFTER_MS;
|
|
38
|
+
}
|
|
39
|
+
|
|
25
40
|
// ---- byte helpers (kept dependency-free; typed arrays only) ----------------
|
|
26
41
|
|
|
27
42
|
export function b64e(u8) {
|
|
@@ -189,6 +204,7 @@ export class DeviceChannel {
|
|
|
189
204
|
sendCs = null;
|
|
190
205
|
recvCs = null;
|
|
191
206
|
hostFingerprint = null;
|
|
207
|
+
handshakeAt = 0; // set when Split() runs — the rotation clock starts at ready
|
|
192
208
|
constructor(self) {
|
|
193
209
|
this.#self = self;
|
|
194
210
|
}
|
|
@@ -218,12 +234,17 @@ export class DeviceChannel {
|
|
|
218
234
|
const [c1, c2] = await this.#hs.split();
|
|
219
235
|
this.sendCs = c1; // device → host
|
|
220
236
|
this.recvCs = c2; // host → device
|
|
237
|
+
this.handshakeAt = Date.now();
|
|
221
238
|
this.#e = null;
|
|
222
239
|
return { c: b64e(c) };
|
|
223
240
|
}
|
|
224
241
|
ready() {
|
|
225
242
|
return Boolean(this.sendCs && this.recvCs);
|
|
226
243
|
}
|
|
244
|
+
/** Messages carried under the current keys (max of both directions). */
|
|
245
|
+
usage() {
|
|
246
|
+
return Math.max(this.sendCs?.n ?? 0, this.recvCs?.n ?? 0);
|
|
247
|
+
}
|
|
227
248
|
async send(obj) {
|
|
228
249
|
const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
229
250
|
return { op: "e2e", n, c: b64e(ct) };
|
|
@@ -241,6 +262,7 @@ export class HostChannel {
|
|
|
241
262
|
sendCs = null;
|
|
242
263
|
recvCs = null;
|
|
243
264
|
deviceFingerprint = null;
|
|
265
|
+
handshakeAt = 0; // set when Split() runs — the rotation clock starts at ready
|
|
244
266
|
constructor(self) {
|
|
245
267
|
this.#self = self;
|
|
246
268
|
}
|
|
@@ -266,11 +288,16 @@ export class HostChannel {
|
|
|
266
288
|
const [c1, c2] = await this.#hs.split();
|
|
267
289
|
this.recvCs = c1; // device → host (c1 encrypts initiator→responder)
|
|
268
290
|
this.sendCs = c2; // host → device
|
|
291
|
+
this.handshakeAt = Date.now();
|
|
269
292
|
this.#e = null;
|
|
270
293
|
}
|
|
271
294
|
ready() {
|
|
272
295
|
return Boolean(this.sendCs && this.recvCs);
|
|
273
296
|
}
|
|
297
|
+
/** Messages carried under the current keys (max of both directions). */
|
|
298
|
+
usage() {
|
|
299
|
+
return Math.max(this.sendCs?.n ?? 0, this.recvCs?.n ?? 0);
|
|
300
|
+
}
|
|
274
301
|
async send(obj) {
|
|
275
302
|
const { ct, n } = await this.sendCs.encrypt(this.#hs.h, utf8e(JSON.stringify(obj)));
|
|
276
303
|
return { op: "e2e", n, c: b64e(ct) };
|
package/plugin/server/index.mjs
CHANGED
|
@@ -14,8 +14,9 @@ import { hostname, homedir } from "node:os";
|
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
15
|
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
|
|
16
16
|
import { createSshBridge } from "./ssh.mjs";
|
|
17
|
-
import { findReceipt, journalBase as receiptJournalBase, publicReceipt } from "./pi-receipts.mjs";
|
|
18
|
-
import {
|
|
17
|
+
import { findBody, findReceipt, journalBase as receiptJournalBase, publicReceipt, watchReceipts } from "./pi-receipts.mjs";
|
|
18
|
+
import { openWatchStore } from "./pi-receipt-watch.mjs";
|
|
19
|
+
import { JOB_ID, MAX_PENDING, MAX_PROMPT, WORKSPACE_NAME, appendJob, jobsFile, publicJob, queueDepth, readHeartbeat, readJobs, workerBase } from "./pi-worker.mjs";
|
|
19
20
|
import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
|
|
20
21
|
import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
|
|
21
22
|
|
|
@@ -221,6 +222,8 @@ async function publisherLoop() {
|
|
|
221
222
|
if (payload && typeof payload === "object" && typeof payload.op === "string" && payload.op.startsWith("e2e")) log(`e2e: op ${payload.op} from ${device}`);
|
|
222
223
|
if (!payload || typeof payload !== "object") return null;
|
|
223
224
|
if (payload.op === "e2e.init") {
|
|
225
|
+
const prior = e2eSessions.get(device);
|
|
226
|
+
if (prior?.ready()) log(`e2e: rotating session with ${device} (lifetime bound reached on the device)`);
|
|
224
227
|
const ch = new HostChannel(await e2eSelfKey());
|
|
225
228
|
if (wsRef !== ws || ws.readyState !== 1 || !devices.some(d => d.id === device)) return { reply: null };
|
|
226
229
|
e2eSessions.set(device, ch);
|
|
@@ -294,6 +297,56 @@ async function publisherLoop() {
|
|
|
294
297
|
}
|
|
295
298
|
};
|
|
296
299
|
|
|
300
|
+
/** Push receipt settles only to devices that registered a durable watch for
|
|
301
|
+
* that request (Paseo-style finish subscriptions): delivery targets the
|
|
302
|
+
* subscriber, survives publisher restarts, and only an ack retires the
|
|
303
|
+
* intent. No broadcast to the whole room. */
|
|
304
|
+
let receiptWatch = null;
|
|
305
|
+
let watchStore = null;
|
|
306
|
+
const receiptsEnabled = () => process.env.HERDGATE_PI_RECEIPTS === "1";
|
|
307
|
+
const receiptBodyEnabled = () => receiptsEnabled() && process.env.HERDGATE_PI_RECEIPT_BODY === "1";
|
|
308
|
+
const watches = () => {
|
|
309
|
+
if (!receiptsEnabled()) return null;
|
|
310
|
+
watchStore ??= openWatchStore(receiptJournalBase());
|
|
311
|
+
return watchStore;
|
|
312
|
+
};
|
|
313
|
+
const pushReceiptTo = (device, entry) => {
|
|
314
|
+
const body = receiptBodyEnabled() && entry.status === "replied" ? findBody(receiptJournalBase(), entry.id) : null;
|
|
315
|
+
log(`receipts: pushed ${entry.status} ${entry.id} -> ${device}${body ? " (+body)" : ""}`);
|
|
316
|
+
void sendPayload(wsRef, device, { op: "receipt.push", hasBody: Boolean(body), ...publicReceipt(entry) });
|
|
317
|
+
};
|
|
318
|
+
const flushWatches = (device) => {
|
|
319
|
+
const store = watches();
|
|
320
|
+
if (!store) return;
|
|
321
|
+
store.sweep();
|
|
322
|
+
let replayed = 0;
|
|
323
|
+
for (const sub of store.pendingFor(device)) {
|
|
324
|
+
const entry = findReceipt(receiptJournalBase(), sub.requestId);
|
|
325
|
+
if (!entry) continue; // not settled yet; the watcher routes the settle
|
|
326
|
+
store.markDelivered(device, sub.requestId);
|
|
327
|
+
pushReceiptTo(device, entry);
|
|
328
|
+
replayed++;
|
|
329
|
+
}
|
|
330
|
+
if (replayed) log(`receipts: replayed ${replayed} unacknowledged push(es) to ${device}`);
|
|
331
|
+
};
|
|
332
|
+
const pushReceipt = (entry) => {
|
|
333
|
+
const store = watches();
|
|
334
|
+
if (!store) return;
|
|
335
|
+
store.sweep();
|
|
336
|
+
const targets = store.pendingAll().filter(sub => sub.requestId === entry.id);
|
|
337
|
+
if (!targets.length) return log(`receipts: settled ${entry.status} ${entry.id} (no subscriber)`);
|
|
338
|
+
for (const sub of targets) {
|
|
339
|
+
store.markDelivered(sub.device, entry.id);
|
|
340
|
+
pushReceiptTo(sub.device, entry);
|
|
341
|
+
// A phone with the app closed misses the frame; the wake push brings it
|
|
342
|
+
// back so flushWatches can replay the settle (throttled per device).
|
|
343
|
+
const known = devices.find(d => d.id === sub.device);
|
|
344
|
+
if (known && known.connected !== false) continue;
|
|
345
|
+
log(`receipts: wake ${sub.device} (settle while offline)`);
|
|
346
|
+
wakeAway(true);
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
|
|
297
350
|
/** Wake phones that are away when something actually changed (throttled per device). */
|
|
298
351
|
const lastWake = new Map(); // deviceId → epoch ms
|
|
299
352
|
const wakeAway = (changed) => {
|
|
@@ -343,6 +396,11 @@ async function publisherLoop() {
|
|
|
343
396
|
devices = m.devices ?? [];
|
|
344
397
|
lifecycle?.setConnected(true);
|
|
345
398
|
log(`connected to ${url}${loopbackPort ? ` via loopback 127.0.0.1:${loopbackPort}` : ""} (room ${m.roomId}, ${devices.length} device(s))`);
|
|
399
|
+
if (process.env.HERDGATE_PI_RECEIPTS === "1" && !receiptWatch) {
|
|
400
|
+
receiptWatch = watchReceipts(receiptJournalBase(), pushReceipt);
|
|
401
|
+
log(`receipts: journal push enabled (${receiptJournalBase()})`);
|
|
402
|
+
}
|
|
403
|
+
for (const d of devices) flushWatches(d.id);
|
|
346
404
|
void publish(ws);
|
|
347
405
|
if (timer) clearInterval(timer);
|
|
348
406
|
timer = setInterval(() => void publish(ws), 30_000);
|
|
@@ -356,6 +414,7 @@ async function publisherLoop() {
|
|
|
356
414
|
e2eSessions.delete(d.id);
|
|
357
415
|
}
|
|
358
416
|
devices = next;
|
|
417
|
+
for (const d of devices) flushWatches(d.id);
|
|
359
418
|
void publish(ws);
|
|
360
419
|
return;
|
|
361
420
|
}
|
|
@@ -389,6 +448,30 @@ async function publisherLoop() {
|
|
|
389
448
|
return void replyTo({ op: "receipt.result", id: id || null,
|
|
390
449
|
...publicReceipt(entry), ...(enabled ? {} : { reason: "pi_receipts_disabled" }) });
|
|
391
450
|
}
|
|
451
|
+
if (op === "receipt.watch" || op === "receipt.ack") {
|
|
452
|
+
// Experimental (opt-in HERDGATE_PI_RECEIPTS=1): durable per-request push
|
|
453
|
+
// subscriptions. Registering targets receipt.push at this device only;
|
|
454
|
+
// an ack retires the intent after the controller has handled the report.
|
|
455
|
+
const id = typeof payload.id === "string" && JOB_ID.test(payload.id) ? payload.id : "";
|
|
456
|
+
if (!receiptsEnabled()) return void replyTo({ op: "receipt.watched", id: id || null, status: "unknown", reason: "pi_receipts_disabled" });
|
|
457
|
+
if (!id) return void replyTo({ op: "error", code: "receipt.watch", message: "invalid request id" });
|
|
458
|
+
const store = watches();
|
|
459
|
+
if (op === "receipt.ack") {
|
|
460
|
+
const retired = Boolean(store?.ack(m.device, id));
|
|
461
|
+
log(`receipts: ack ${id} from ${m.device} -> ${retired ? "retired" : "no pending intent"}`);
|
|
462
|
+
return void replyTo({ op: "receipt.acked", id, retired });
|
|
463
|
+
}
|
|
464
|
+
let subscription;
|
|
465
|
+
try {
|
|
466
|
+
subscription = store.register({ device: m.device, requestId: id, wantBody: payload.wantBody === true,
|
|
467
|
+
...(Number.isFinite(payload.ttlMs) && payload.ttlMs > 0 ? { ttlMs: Math.min(payload.ttlMs, 24 * 60 * 60 * 1000) } : {}) });
|
|
468
|
+
} catch (error) {
|
|
469
|
+
return void replyTo({ op: "error", code: "receipt.watch", message: error.message });
|
|
470
|
+
}
|
|
471
|
+
const entry = findReceipt(receiptJournalBase(), id);
|
|
472
|
+
log(`receipts: ${m.device} watches ${id}${subscription.wantBody ? " (+body)" : ""} -> ${entry ? entry.status : "pending"}`);
|
|
473
|
+
return void replyTo({ op: "receipt.watched", id, ...(entry ? publicReceipt(entry) : { pending: true }) });
|
|
474
|
+
}
|
|
392
475
|
if (op === "worker.health") {
|
|
393
476
|
// Experimental (opt-in HERDGATE_PI_WORKER=1): liveness for the owner — queue
|
|
394
477
|
// depth plus the last heartbeat written by the scheduler/worker experiment.
|
|
@@ -409,6 +492,18 @@ async function publisherLoop() {
|
|
|
409
492
|
? { queued, running, heartbeat: beat ? { ts: beat.ts, source: beat.source, ageSeconds: age } : null }
|
|
410
493
|
: { reason: "pi_worker_disabled" }) });
|
|
411
494
|
}
|
|
495
|
+
if (op === "receipt.body") {
|
|
496
|
+
// Experimental: serving archived replies is separate from metadata push.
|
|
497
|
+
const id = typeof payload.id === "string" && JOB_ID.test(payload.id) ? payload.id : "";
|
|
498
|
+
const base = receiptJournalBase();
|
|
499
|
+
const body = receiptBodyEnabled() && id && findReceipt(base, id)?.status === 'replied' ? findBody(base, id) : null;
|
|
500
|
+
log(`receipts: ${m.device} body ${id || "?"} -> ${body ? `${body.bytes}B${body.truncated ? " (capped)" : ""}` : "none"}`);
|
|
501
|
+
return void replyTo({ op: "receipt.body.result", id: id || null,
|
|
502
|
+
...(body
|
|
503
|
+
? { text: body.text, bytes: body.bytes, truncated: body.truncated }
|
|
504
|
+
: { reason: receiptBodyEnabled() ? "body_not_retained"
|
|
505
|
+
: process.env.HERDGATE_PI_RECEIPTS === "1" ? "pi_receipt_body_disabled" : "pi_receipts_disabled" }) });
|
|
506
|
+
}
|
|
412
507
|
if (op === "worker.submit" || op === "worker.status") {
|
|
413
508
|
// Experimental (opt-in HERDGATE_PI_WORKER=1): admission to the local Pi worker
|
|
414
509
|
// queue (plugin/server/pi-worker.mjs). The publisher never runs Pi itself — a
|
|
@@ -436,6 +531,12 @@ async function publisherLoop() {
|
|
|
436
531
|
if (!prompt.trim() || prompt.length > MAX_PROMPT) {
|
|
437
532
|
return void replyTo({ op: "error", code: "bad-prompt", message: `worker.submit needs a prompt of 1..${MAX_PROMPT} chars` });
|
|
438
533
|
}
|
|
534
|
+
// Optional routing key: a NAME from the host's workspaces.json allowlist —
|
|
535
|
+
// never a raw path. Unknown names fail closed on the worker side.
|
|
536
|
+
const workspaceName = payload.workspace;
|
|
537
|
+
if (workspaceName !== undefined && (typeof workspaceName !== "string" || !WORKSPACE_NAME.test(workspaceName))) {
|
|
538
|
+
return void replyTo({ op: "error", code: "bad-workspace", message: "worker.submit workspace must be a short lowercase name" });
|
|
539
|
+
}
|
|
439
540
|
let jobs;
|
|
440
541
|
try { jobs = readJobs(file); }
|
|
441
542
|
catch (e) {
|
|
@@ -453,11 +554,12 @@ async function publisherLoop() {
|
|
|
453
554
|
return void replyTo({ op: "error", code: "queue-full", message: `worker queue is full (${MAX_PENDING} pending)` });
|
|
454
555
|
}
|
|
455
556
|
const jobId = id || randomUUID();
|
|
456
|
-
try { appendJob(file, { v: 1, id: jobId, prompt, ts: Date.now(), state: "queued"
|
|
557
|
+
try { appendJob(file, { v: 1, id: jobId, prompt, ts: Date.now(), state: "queued",
|
|
558
|
+
...(workspaceName !== undefined ? { workspace: workspaceName } : {}) }); }
|
|
457
559
|
catch (e) {
|
|
458
560
|
return void replyTo({ op: "error", code: "worker-queue", message: `queue append failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
459
561
|
}
|
|
460
|
-
log(`worker: ${m.device} submitted ${jobId} (${prompt.length} chars)`);
|
|
562
|
+
log(`worker: ${m.device} submitted ${jobId} (${prompt.length} chars${workspaceName ? `, ws ${workspaceName}` : ""})`);
|
|
461
563
|
return void replyTo({ op: "worker.submitted", id: jobId, state: "queued", duplicate: false });
|
|
462
564
|
}
|
|
463
565
|
if (op === "view") {
|