@bom0792/herdgate 0.9.36 → 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.
@@ -83,3 +83,38 @@ Nếu có Python 3.11+ và file `herdr_pi.py` đi kèm **trong thư mục của
83
83
 
84
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ờ.
85
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.36",
3
+ "version": "0.9.37",
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": {
@@ -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) };
@@ -16,7 +16,7 @@ import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, su
16
16
  import { createSshBridge } from "./ssh.mjs";
17
17
  import { findBody, findReceipt, journalBase as receiptJournalBase, publicReceipt, watchReceipts } from "./pi-receipts.mjs";
18
18
  import { openWatchStore } from "./pi-receipt-watch.mjs";
19
- import { JOB_ID, MAX_PENDING, MAX_PROMPT, appendJob, jobsFile, publicJob, queueDepth, readHeartbeat, readJobs, workerBase } from "./pi-worker.mjs";
19
+ import { JOB_ID, MAX_PENDING, MAX_PROMPT, WORKSPACE_NAME, appendJob, jobsFile, publicJob, queueDepth, readHeartbeat, readJobs, workerBase } from "./pi-worker.mjs";
20
20
  import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
21
21
  import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
22
22
 
@@ -222,6 +222,8 @@ async function publisherLoop() {
222
222
  if (payload && typeof payload === "object" && typeof payload.op === "string" && payload.op.startsWith("e2e")) log(`e2e: op ${payload.op} from ${device}`);
223
223
  if (!payload || typeof payload !== "object") return null;
224
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)`);
225
227
  const ch = new HostChannel(await e2eSelfKey());
226
228
  if (wsRef !== ws || ws.readyState !== 1 || !devices.some(d => d.id === device)) return { reply: null };
227
229
  e2eSessions.set(device, ch);
@@ -336,6 +338,12 @@ async function publisherLoop() {
336
338
  for (const sub of targets) {
337
339
  store.markDelivered(sub.device, entry.id);
338
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);
339
347
  }
340
348
  };
341
349
 
@@ -523,6 +531,12 @@ async function publisherLoop() {
523
531
  if (!prompt.trim() || prompt.length > MAX_PROMPT) {
524
532
  return void replyTo({ op: "error", code: "bad-prompt", message: `worker.submit needs a prompt of 1..${MAX_PROMPT} chars` });
525
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
+ }
526
540
  let jobs;
527
541
  try { jobs = readJobs(file); }
528
542
  catch (e) {
@@ -540,11 +554,12 @@ async function publisherLoop() {
540
554
  return void replyTo({ op: "error", code: "queue-full", message: `worker queue is full (${MAX_PENDING} pending)` });
541
555
  }
542
556
  const jobId = id || randomUUID();
543
- 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 } : {}) }); }
544
559
  catch (e) {
545
560
  return void replyTo({ op: "error", code: "worker-queue", message: `queue append failed: ${e instanceof Error ? e.message : String(e)}` });
546
561
  }
547
- log(`worker: ${m.device} submitted ${jobId} (${prompt.length} chars)`);
562
+ log(`worker: ${m.device} submitted ${jobId} (${prompt.length} chars${workspaceName ? `, ws ${workspaceName}` : ""})`);
548
563
  return void replyTo({ op: "worker.submitted", id: jobId, state: "queued", duplicate: false });
549
564
  }
550
565
  if (op === "view") {