@bom0792/herdgate 0.9.35 → 0.9.36

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.
@@ -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`. 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.
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,13 @@ 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 --timeout 120000
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. `--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.
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**.
@@ -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 --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.
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` 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.
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. 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.
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 ${JSON.stringify(String(r.room.name))} --remote-session default`);
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.35",
3
+ "version": "0.9.36",
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": {
@@ -14,7 +14,8 @@ 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";
17
+ import { findBody, findReceipt, journalBase as receiptJournalBase, publicReceipt, watchReceipts } from "./pi-receipts.mjs";
18
+ import { openWatchStore } from "./pi-receipt-watch.mjs";
18
19
  import { JOB_ID, MAX_PENDING, MAX_PROMPT, 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";
@@ -294,6 +295,50 @@ async function publisherLoop() {
294
295
  }
295
296
  };
296
297
 
298
+ /** Push receipt settles only to devices that registered a durable watch for
299
+ * that request (Paseo-style finish subscriptions): delivery targets the
300
+ * subscriber, survives publisher restarts, and only an ack retires the
301
+ * intent. No broadcast to the whole room. */
302
+ let receiptWatch = null;
303
+ let watchStore = null;
304
+ const receiptsEnabled = () => process.env.HERDGATE_PI_RECEIPTS === "1";
305
+ const receiptBodyEnabled = () => receiptsEnabled() && process.env.HERDGATE_PI_RECEIPT_BODY === "1";
306
+ const watches = () => {
307
+ if (!receiptsEnabled()) return null;
308
+ watchStore ??= openWatchStore(receiptJournalBase());
309
+ return watchStore;
310
+ };
311
+ const pushReceiptTo = (device, entry) => {
312
+ const body = receiptBodyEnabled() && entry.status === "replied" ? findBody(receiptJournalBase(), entry.id) : null;
313
+ log(`receipts: pushed ${entry.status} ${entry.id} -> ${device}${body ? " (+body)" : ""}`);
314
+ void sendPayload(wsRef, device, { op: "receipt.push", hasBody: Boolean(body), ...publicReceipt(entry) });
315
+ };
316
+ const flushWatches = (device) => {
317
+ const store = watches();
318
+ if (!store) return;
319
+ store.sweep();
320
+ let replayed = 0;
321
+ for (const sub of store.pendingFor(device)) {
322
+ const entry = findReceipt(receiptJournalBase(), sub.requestId);
323
+ if (!entry) continue; // not settled yet; the watcher routes the settle
324
+ store.markDelivered(device, sub.requestId);
325
+ pushReceiptTo(device, entry);
326
+ replayed++;
327
+ }
328
+ if (replayed) log(`receipts: replayed ${replayed} unacknowledged push(es) to ${device}`);
329
+ };
330
+ const pushReceipt = (entry) => {
331
+ const store = watches();
332
+ if (!store) return;
333
+ store.sweep();
334
+ const targets = store.pendingAll().filter(sub => sub.requestId === entry.id);
335
+ if (!targets.length) return log(`receipts: settled ${entry.status} ${entry.id} (no subscriber)`);
336
+ for (const sub of targets) {
337
+ store.markDelivered(sub.device, entry.id);
338
+ pushReceiptTo(sub.device, entry);
339
+ }
340
+ };
341
+
297
342
  /** Wake phones that are away when something actually changed (throttled per device). */
298
343
  const lastWake = new Map(); // deviceId → epoch ms
299
344
  const wakeAway = (changed) => {
@@ -343,6 +388,11 @@ async function publisherLoop() {
343
388
  devices = m.devices ?? [];
344
389
  lifecycle?.setConnected(true);
345
390
  log(`connected to ${url}${loopbackPort ? ` via loopback 127.0.0.1:${loopbackPort}` : ""} (room ${m.roomId}, ${devices.length} device(s))`);
391
+ if (process.env.HERDGATE_PI_RECEIPTS === "1" && !receiptWatch) {
392
+ receiptWatch = watchReceipts(receiptJournalBase(), pushReceipt);
393
+ log(`receipts: journal push enabled (${receiptJournalBase()})`);
394
+ }
395
+ for (const d of devices) flushWatches(d.id);
346
396
  void publish(ws);
347
397
  if (timer) clearInterval(timer);
348
398
  timer = setInterval(() => void publish(ws), 30_000);
@@ -356,6 +406,7 @@ async function publisherLoop() {
356
406
  e2eSessions.delete(d.id);
357
407
  }
358
408
  devices = next;
409
+ for (const d of devices) flushWatches(d.id);
359
410
  void publish(ws);
360
411
  return;
361
412
  }
@@ -389,6 +440,30 @@ async function publisherLoop() {
389
440
  return void replyTo({ op: "receipt.result", id: id || null,
390
441
  ...publicReceipt(entry), ...(enabled ? {} : { reason: "pi_receipts_disabled" }) });
391
442
  }
443
+ if (op === "receipt.watch" || op === "receipt.ack") {
444
+ // Experimental (opt-in HERDGATE_PI_RECEIPTS=1): durable per-request push
445
+ // subscriptions. Registering targets receipt.push at this device only;
446
+ // an ack retires the intent after the controller has handled the report.
447
+ const id = typeof payload.id === "string" && JOB_ID.test(payload.id) ? payload.id : "";
448
+ if (!receiptsEnabled()) return void replyTo({ op: "receipt.watched", id: id || null, status: "unknown", reason: "pi_receipts_disabled" });
449
+ if (!id) return void replyTo({ op: "error", code: "receipt.watch", message: "invalid request id" });
450
+ const store = watches();
451
+ if (op === "receipt.ack") {
452
+ const retired = Boolean(store?.ack(m.device, id));
453
+ log(`receipts: ack ${id} from ${m.device} -> ${retired ? "retired" : "no pending intent"}`);
454
+ return void replyTo({ op: "receipt.acked", id, retired });
455
+ }
456
+ let subscription;
457
+ try {
458
+ subscription = store.register({ device: m.device, requestId: id, wantBody: payload.wantBody === true,
459
+ ...(Number.isFinite(payload.ttlMs) && payload.ttlMs > 0 ? { ttlMs: Math.min(payload.ttlMs, 24 * 60 * 60 * 1000) } : {}) });
460
+ } catch (error) {
461
+ return void replyTo({ op: "error", code: "receipt.watch", message: error.message });
462
+ }
463
+ const entry = findReceipt(receiptJournalBase(), id);
464
+ log(`receipts: ${m.device} watches ${id}${subscription.wantBody ? " (+body)" : ""} -> ${entry ? entry.status : "pending"}`);
465
+ return void replyTo({ op: "receipt.watched", id, ...(entry ? publicReceipt(entry) : { pending: true }) });
466
+ }
392
467
  if (op === "worker.health") {
393
468
  // Experimental (opt-in HERDGATE_PI_WORKER=1): liveness for the owner — queue
394
469
  // depth plus the last heartbeat written by the scheduler/worker experiment.
@@ -409,6 +484,18 @@ async function publisherLoop() {
409
484
  ? { queued, running, heartbeat: beat ? { ts: beat.ts, source: beat.source, ageSeconds: age } : null }
410
485
  : { reason: "pi_worker_disabled" }) });
411
486
  }
487
+ if (op === "receipt.body") {
488
+ // Experimental: serving archived replies is separate from metadata push.
489
+ const id = typeof payload.id === "string" && JOB_ID.test(payload.id) ? payload.id : "";
490
+ const base = receiptJournalBase();
491
+ const body = receiptBodyEnabled() && id && findReceipt(base, id)?.status === 'replied' ? findBody(base, id) : null;
492
+ log(`receipts: ${m.device} body ${id || "?"} -> ${body ? `${body.bytes}B${body.truncated ? " (capped)" : ""}` : "none"}`);
493
+ return void replyTo({ op: "receipt.body.result", id: id || null,
494
+ ...(body
495
+ ? { text: body.text, bytes: body.bytes, truncated: body.truncated }
496
+ : { reason: receiptBodyEnabled() ? "body_not_retained"
497
+ : process.env.HERDGATE_PI_RECEIPTS === "1" ? "pi_receipt_body_disabled" : "pi_receipts_disabled" }) });
498
+ }
412
499
  if (op === "worker.submit" || op === "worker.status") {
413
500
  // Experimental (opt-in HERDGATE_PI_WORKER=1): admission to the local Pi worker
414
501
  // queue (plugin/server/pi-worker.mjs). The publisher never runs Pi itself — a
@@ -0,0 +1,24 @@
1
+ export const WATCH_TTL_MS: number;
2
+ export const MAX_TTL_MS: number;
3
+ export const MAX_SUBS_PER_DEVICE: number;
4
+
5
+ export interface WatchSubscription {
6
+ device: string;
7
+ requestId: string;
8
+ wantBody: boolean;
9
+ createdAt: number;
10
+ expiresAt: number;
11
+ deliveredAt?: number;
12
+ }
13
+
14
+ export interface WatchStore {
15
+ register(input: { device: string; requestId: string; wantBody?: boolean; ttlMs?: number }): WatchSubscription;
16
+ markDelivered(device: string, requestId: string): boolean;
17
+ ack(device: string, requestId: string): boolean;
18
+ pendingFor(device: string): WatchSubscription[];
19
+ pendingAll(): WatchSubscription[];
20
+ sweep(now?: number): number;
21
+ }
22
+
23
+ export function watchFile(base: string): string;
24
+ export function openWatchStore(base: string): WatchStore;
@@ -0,0 +1,99 @@
1
+ // Durable receipt-push subscriptions (experimental; see experiments/pi-receipt).
2
+ // Lesson taken from Paseo's finish subscriptions: the notification intent is
3
+ // owned by the receiver's request id, persists across publisher restarts and
4
+ // device reconnects, and only an explicit acknowledgment retires it. Delivered
5
+ // but unacknowledged intents are re-offered on reconnect; nothing is resent to
6
+ // devices that did not register. Shared reader/writer for the publisher; no
7
+ // network access here. Same opt-in gate as receipt.get (HERDGATE_PI_RECEIPTS=1).
8
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { RECEIPT_ID } from './pi-receipts.mjs';
11
+
12
+ /** Matches the observer's arm TTL: a watch outlives the request it tracks. */
13
+ export const WATCH_TTL_MS = 10 * 60 * 1000;
14
+ export const MAX_TTL_MS = 24 * 60 * 60 * 1000;
15
+ export const MAX_SUBS_PER_DEVICE = 16;
16
+
17
+ /** Where the durable watch intents live, beside the receipt journals. */
18
+ export function watchFile(base) {
19
+ return join(base, 'watch.json');
20
+ }
21
+
22
+ function valid(device) {
23
+ return typeof device === 'string' && /^[\w.-]{1,64}$/.test(device);
24
+ }
25
+
26
+ function load(file) {
27
+ let raw;
28
+ try { raw = JSON.parse(readFileSync(file, 'utf8')); }
29
+ catch { return []; } // missing or unreadable -> empty, fail closed for replay
30
+ const list = Array.isArray(raw?.subscriptions) ? raw.subscriptions : [];
31
+ return list.filter(entry => valid(entry?.device) && RECEIPT_ID.test(entry?.requestId ?? '')
32
+ && typeof entry.wantBody === 'boolean' && Number.isFinite(entry?.createdAt) && Number.isFinite(entry?.expiresAt));
33
+ }
34
+
35
+ function save(file, subscriptions) {
36
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
37
+ const tmp = `${file}.tmp`;
38
+ writeFileSync(tmp, JSON.stringify({ v: 1, subscriptions }) + '\n', { mode: 0o600 });
39
+ rmSync(file, { force: true });
40
+ renameSync(tmp, file);
41
+ }
42
+
43
+ /**
44
+ * Sync, atomic, newest-wins store. Registering the same (device, requestId)
45
+ * supersedes the prior intent; ack removes it; sweep drops expired intents.
46
+ * pendingFor() lists what a reconnecting device must be re-offered.
47
+ */
48
+ export function openWatchStore(base) {
49
+ const file = watchFile(base);
50
+ const write = (subscriptions) => {
51
+ save(file, subscriptions);
52
+ return subscriptions;
53
+ };
54
+ let subscriptions = load(file);
55
+ return {
56
+ register({ device, requestId, wantBody = false, ttlMs = WATCH_TTL_MS }) {
57
+ if (!valid(device)) throw new Error('invalid_device');
58
+ if (!RECEIPT_ID.test(requestId ?? '')) throw new Error('invalid_request_id');
59
+ if (wantBody !== undefined && typeof wantBody !== 'boolean') throw new Error('invalid_want_body');
60
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || ttlMs > MAX_TTL_MS) throw new Error('invalid_ttl');
61
+ const now = Date.now();
62
+ subscriptions = subscriptions.filter(s => !(s.device === device && s.requestId === requestId));
63
+ subscriptions.push({ device, requestId, wantBody: Boolean(wantBody), createdAt: now, expiresAt: now + ttlMs });
64
+ const mine = subscriptions.filter(s => s.device === device);
65
+ if (mine.length > MAX_SUBS_PER_DEVICE) {
66
+ const drop = new Set(mine.slice(0, mine.length - MAX_SUBS_PER_DEVICE));
67
+ subscriptions = subscriptions.filter(s => !drop.has(s));
68
+ }
69
+ write(subscriptions);
70
+ return { ...subscriptions.find(s => s.device === device && s.requestId === requestId) };
71
+ },
72
+ markDelivered(device, requestId) {
73
+ const sub = subscriptions.find(s => s.device === device && s.requestId === requestId);
74
+ if (sub) { sub.deliveredAt = Date.now(); write(subscriptions); }
75
+ return Boolean(sub);
76
+ },
77
+ ack(device, requestId) {
78
+ const before = subscriptions.length;
79
+ subscriptions = subscriptions.filter(s => !(s.device === device && s.requestId === requestId));
80
+ if (subscriptions.length === before) return false;
81
+ write(subscriptions);
82
+ return true;
83
+ },
84
+ pendingFor(device) {
85
+ return subscriptions.filter(s => s.device === device && s.expiresAt > Date.now())
86
+ .map(({ id, ...rest }) => ({ ...rest }));
87
+ },
88
+ pendingAll() {
89
+ return subscriptions.filter(s => s.expiresAt > Date.now())
90
+ .map(({ id, ...rest }) => ({ ...rest }));
91
+ },
92
+ sweep(now = Date.now()) {
93
+ const before = subscriptions.length;
94
+ subscriptions = subscriptions.filter(s => s.expiresAt > now);
95
+ if (subscriptions.length !== before) write(subscriptions);
96
+ return before - subscriptions.length;
97
+ },
98
+ };
99
+ }
@@ -26,3 +26,15 @@ export function validEntry(entry: unknown): JournalEntry | null;
26
26
  export function readJournal(dir: string): JournalEntry[];
27
27
  export function findReceipt(base: string, id: string): JournalEntry | null;
28
28
  export function publicReceipt(entry: JournalEntry | null): PublicReceipt;
29
+ export function watchReceipts(
30
+ base: string,
31
+ onEntry: (entry: JournalEntry) => void,
32
+ options?: { intervalMs?: number },
33
+ ): () => void;
34
+ export const MAX_BODY_BYTES: number;
35
+ export interface ReceiptBody {
36
+ text: string;
37
+ truncated: boolean;
38
+ bytes: number;
39
+ }
40
+ export function findBody(base: string, id: string): ReceiptBody | null;
@@ -4,7 +4,10 @@
4
4
  import { createHash } from 'node:crypto';
5
5
  import { homedir } from 'node:os';
6
6
  import { join } from 'node:path';
7
- import { readFileSync, readdirSync } from 'node:fs';
7
+ import { closeSync, constants, fstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, watch } from 'node:fs';
8
+ import { StringDecoder } from 'node:string_decoder';
9
+
10
+ export const MAX_BODY_BYTES = 64 * 1024; // served size cap for one archived reply
8
11
 
9
12
  export const RECEIPT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
10
13
  const RECEIPTS = 'receipts.jsonl';
@@ -17,7 +20,12 @@ export function journalBase(env = process.env) {
17
20
  }
18
21
 
19
22
  export function scopeFor(cwd) {
20
- return createHash('sha256').update(cwd).digest('hex').slice(0, 16);
23
+ // Resolve symlinks before hashing (Paseo's import-matcher lesson): two panes
24
+ // entering the same workspace through different link paths must share one
25
+ // journal scope. Reads already scan every scope, so this only converges writes.
26
+ let real = cwd;
27
+ try { real = realpathSync(cwd); } catch { /* deleted cwd: keep the raw path */ }
28
+ return createHash('sha256').update(real).digest('hex').slice(0, 16);
21
29
  }
22
30
 
23
31
  export function validEntry(entry) {
@@ -28,7 +36,11 @@ function validEntryShape(entry) {
28
36
  return Boolean(entry && entry.v === 1 && RECEIPT_ID.test(entry.id ?? '')
29
37
  && ['replied', 'failed', 'canceled', 'unknown'].includes(entry.status)
30
38
  && typeof entry.sessionId === 'string' && typeof entry.ts === 'number'
31
- && ['reason', 'requestEntryId', 'responseEntryId', 'paneId'].every(key => entry[key] === undefined || typeof entry[key] === 'string'));
39
+ && ['reason', 'requestEntryId', 'responseEntryId', 'paneId'].every(key => entry[key] === undefined || typeof entry[key] === 'string')
40
+ && (entry.usage === undefined || (typeof entry.usage === 'object' && entry.usage !== null
41
+ && Object.keys(entry.usage).length > 0
42
+ && Object.keys(entry.usage).every(key => ['totalTokens', 'costUsd', 'durationMs'].includes(key))
43
+ && Object.values(entry.usage).every(value => Number.isFinite(value)))));
32
44
  }
33
45
 
34
46
  /** Parse a journal file; tolerate a torn tail and skip corrupt lines. */
@@ -75,3 +87,98 @@ export function publicReceipt(entry) {
75
87
  const { v, ts, sessionId, paneId, ...rest } = entry;
76
88
  return rest;
77
89
  }
90
+
91
+ /**
92
+ * Find the archived reply text for a request id across workspace scopes.
93
+ * Writers archive bodies only when configured to retain the reply. The
94
+ * served text is capped (truncated flags the cut). Exact id
95
+ * only, no enumeration; unreadable -> null (fail closed).
96
+ */
97
+ export function findBody(base, id) {
98
+ if (!RECEIPT_ID.test(id ?? '')) return null;
99
+ try {
100
+ for (const name of readdirSync(base)) {
101
+ if (!/^[0-9a-f]{16}$/.test(name)) continue;
102
+ let fd;
103
+ try {
104
+ fd = openSync(join(base, name, 'responses', `${id}.md`), constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
105
+ const stat = fstatSync(fd);
106
+ if (!stat.isFile()) continue;
107
+ const buf = Buffer.alloc(Math.min(stat.size, MAX_BODY_BYTES));
108
+ let read = 0;
109
+ while (read < buf.length) {
110
+ const n = readSync(fd, buf, read, buf.length - read, null);
111
+ if (!n) break;
112
+ read += n;
113
+ }
114
+ if (read !== buf.length) continue; // archive changed while reading
115
+ const truncated = stat.size > read;
116
+ const data = buf.subarray(0, read);
117
+ // For a capped reply, omit a final incomplete code point rather than substituting U+FFFD.
118
+ const text = truncated ? new StringDecoder('utf8').write(data) : data.toString('utf8');
119
+ return { text, truncated, bytes: stat.size };
120
+ } catch { continue; }
121
+ finally { if (fd !== undefined) closeSync(fd); }
122
+ }
123
+ return null;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Watch every workspace journal under base and hand each NEW settle to onEntry
131
+ * (unseen id, or a newer ts for a known id). The first scan is a baseline and
132
+ * emits nothing, so a restarting publisher does not replay old receipts.
133
+ * fs.watch (recursive where supported) gives low latency; a slow interval sweep
134
+ * covers missed events and platforms without recursive watch. A missing base
135
+ * directory just means the next sweep retries. Never throws to the caller.
136
+ */
137
+ export function watchReceipts(base, onEntry, { intervalMs = 4000 } = {}) {
138
+ let stopped = false;
139
+ const seen = new Map(); // id -> ts
140
+ let watcher = null;
141
+ let timer = null;
142
+ let sweepScheduled = false;
143
+ const sweep = emit => {
144
+ if (stopped) return;
145
+ let scopes = [];
146
+ try { scopes = readdirSync(base).filter(name => /^[0-9a-f]{16}$/.test(name)); }
147
+ catch { /* base not created yet */ }
148
+ for (const name of scopes) {
149
+ let entries;
150
+ try { entries = readJournal(join(base, name, RECEIPTS)); } catch { continue; }
151
+ for (const entry of entries) {
152
+ const prior = seen.get(entry.id);
153
+ if (prior !== undefined && prior >= entry.ts) continue;
154
+ seen.set(entry.id, entry.ts);
155
+ if (emit) { try { onEntry(entry); } catch { /* listener errors must not kill the sweep */ } }
156
+ }
157
+ }
158
+ };
159
+ const ensureWatcher = () => {
160
+ if (watcher || stopped) return;
161
+ try {
162
+ watcher = watch(base, { recursive: true }, () => {
163
+ if (sweepScheduled || stopped) return;
164
+ sweepScheduled = true;
165
+ const late = setTimeout(() => { sweepScheduled = false; sweep(true); }, 250);
166
+ late.unref?.();
167
+ });
168
+ watcher.on('error', () => { try { watcher?.close(); } catch { /* already closed */ } watcher = null; });
169
+ } catch { /* base missing or unsupported here; the interval retries */ }
170
+ };
171
+ sweep(false); // baseline only
172
+ ensureWatcher();
173
+ timer = setInterval(() => {
174
+ if (stopped) return;
175
+ ensureWatcher();
176
+ sweep(true);
177
+ }, intervalMs);
178
+ timer.unref?.();
179
+ return () => {
180
+ stopped = true;
181
+ try { watcher?.close(); } catch { /* already closed */ }
182
+ if (timer) clearInterval(timer);
183
+ };
184
+ }
@@ -35,7 +35,7 @@ import {
35
35
  import { AgentCodes } from "./pairing.ts";
36
36
  import { parseAuthorizedKey, sshKeyFingerprint } from "./sshd.ts";
37
37
  import { type Account, type DeviceRecord, type RoomRecord, State } from "./stores.ts";
38
- import { readJsonBody, randomId, sameSecret, sha256Hex } from "./util.ts";
38
+ import { pruneBudget, readJsonBody, randomId, sameSecret, sha256Hex } from "./util.ts";
39
39
  import { serveStatic } from "./static.ts";
40
40
  import { startSshd, type SshHandle, type SshConfig } from "./sshd.ts";
41
41
  import { pushEndpoint, sendWake } from "./push.ts";
@@ -235,12 +235,7 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
235
235
  if (loopbackOf(addr)) return `${addr}#${randomId("k")}`;
236
236
  return addr;
237
237
  };
238
- const pruneFails = (): void => {
239
- if (fails.size <= FAILS_MAX) return;
240
- const now = Date.now();
241
- for (const [k, f] of fails) if (now - f.at > 60_000) fails.delete(k);
242
- if (fails.size > FAILS_MAX) fails.clear();
243
- };
238
+ const pruneFails = (): void => pruneBudget(fails, FAILS_MAX, 60_000);
244
239
  const strike = (key: string): void => {
245
240
  pruneFails();
246
241
  const f = fails.get(key) ?? { n: 0, until: 0, at: Date.now() };
@@ -261,6 +256,11 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
261
256
  const MINT_PER_KEY = 10;
262
257
  const MINT_WINDOW_MS = 10 * 60_000;
263
258
  const mints = new Map<string, { n: number; until: number; at: number }>();
259
+ // The budget map itself must stay bounded too (audit
260
+ // gateway:mint-budget-map-unbounded): per-connection keys behind a
261
+ // same-host proxy must not accumulate forever.
262
+ const MINTS_MAX = 4_096;
263
+ const pruneMints = (): void => pruneBudget(mints, MINTS_MAX, MINT_WINDOW_MS);
264
264
 
265
265
  const sendText = (ws: WebSocket, text: string | Buffer): void => {
266
266
  if (ws.readyState !== WebSocket.OPEN) return;
@@ -826,10 +826,10 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
826
826
  // Two budgets so minting cannot be driven without limit (audit
827
827
  // pairing:unbounded-code-mint): a small per-client rate and a global
828
828
  // pending cap inside AgentCodes.
829
+ pruneMints();
829
830
  const m = mints.get(key) ?? { n: 0, until: 0, at: Date.now() };
830
831
  const now = Date.now();
831
832
  if (m.until > now) {
832
- mints.set(key, m);
833
833
  return json(res, 429, { error: "too many pairing codes; retry shortly" });
834
834
  }
835
835
  if (now - m.at > MINT_WINDOW_MS) m.n = 0;
package/src/cloud/sshd.ts CHANGED
@@ -23,7 +23,7 @@ import { dirname } from "node:path";
23
23
  import type { Duplex } from "node:stream";
24
24
  import ssh2Pkg from "ssh2";
25
25
  import { type State } from "./stores.ts";
26
- import { randomToken } from "./util.ts";
26
+ import { pruneBudget, randomToken } from "./util.ts";
27
27
 
28
28
  const { Server } = ssh2Pkg;
29
29
  const utils = (ssh2Pkg as unknown as { utils?: { generateKeyPairSync?(type: string): { private: string; public: string } } }).utils;
@@ -165,7 +165,11 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
165
165
 
166
166
  const hostKey = loadOrMintHostKey(deps);
167
167
  const channels = new Map<string, Channel>(); // `${deviceId}:${ch}` → channel
168
- const strikes = new Map<string, { n: number; until: number }>();
168
+ const strikes = new Map<string, { n: number; until: number; at: number }>();
169
+ // Bounded like the gateway's failed-hello map (audit
170
+ // sshd:auth-strike-map-unbounded): WSS tunnels each authenticate under a
171
+ // per-connection key, so failed-auth churn must not accumulate forever.
172
+ const STRIKES_MAX = 4_096;
169
173
 
170
174
  const ipOf = (ctx: { ip?: string }): string => ctx.ip ?? "?";
171
175
  const blocked = (ip: string): boolean => {
@@ -173,8 +177,10 @@ export async function startSshd(deps: SshDeps): Promise<SshHandle | null> {
173
177
  return Boolean(f && f.until > Date.now());
174
178
  };
175
179
  const strike = (ip: string): void => {
176
- const f = strikes.get(ip) ?? { n: 0, until: 0 };
180
+ pruneBudget(strikes, STRIKES_MAX, AUTH_BLOCK_MS);
181
+ const f = strikes.get(ip) ?? { n: 0, until: 0, at: Date.now() };
177
182
  f.n += 1;
183
+ f.at = Date.now();
178
184
  if (f.n >= AUTH_STRIKES) {
179
185
  f.until = Date.now() + AUTH_BLOCK_MS;
180
186
  f.n = 0;
package/src/cloud/util.ts CHANGED
@@ -45,3 +45,13 @@ export async function readJsonBody(req: import("node:http").IncomingMessage, max
45
45
  return null;
46
46
  }
47
47
  }
48
+
49
+ /** Drop idle abuse-budget entries; if the map is still over the hard cap,
50
+ * drop everything rather than growing without bound. Shared by the
51
+ * failed-hello, pairing-mint and SSH-auth strike maps (audits
52
+ * gateway:mint-budget-map-unbounded, sshd:auth-strike-map-unbounded). */
53
+ export function pruneBudget<K, V extends { at: number }>(map: Map<K, V>, max: number, windowMs: number, now = Date.now()): void {
54
+ if (map.size <= max) return;
55
+ for (const [k, v] of map) if (now - v.at > windowMs) map.delete(k);
56
+ if (map.size > max) map.clear();
57
+ }