@bom0792/herdgate 0.9.28 → 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/README.md CHANGED
@@ -11,27 +11,24 @@ Both remote connections are outbound; the cloud gateway binds loopback.
11
11
 
12
12
  - **One gate, three identities** — accounts (people), rooms (hosts), devices (browsers). Hosts pair by a
13
13
  GitHub-style device flow; devices pair into a room; `act` scope needs the host's own approval.
14
- - **Opaque payloads** — the cloud routes frames between legs and never inspects, logs or persists them.
15
- End-to-end encryption can be added later without changing the cloud.
16
- - **No inbound ports on your machines** — publishers dial out over wss; the gate is published through
17
- `cloudflared`; and the phone app's SSH leg reaches machines with no open port at all via the
18
- one-file [`ssh-bridge`](DEPLOY.md#the-ssh-leg-is-not-a-cloudflare-tcp-leg--three-ways-in) on any
19
- reachable host — auth and the read-only allowlist stay in the cloud, the bridge carries no secrets;
20
- identity provider (no Cloudflare Access needed, none of its headers trusted).
14
+ - **Separate payload and SSH channels** — the relay routes application frames without interpreting their
15
+ contents, and the payload channel supports Noise_XX between device and host. SSH terminates at the Gate;
16
+ it is not client-to-publisher Noise E2E.
17
+ - **No inbound ports on publishers** — they dial out over WSS. Use a public HTTPS Gate for desktop TUI
18
+ connections. For Herdr Mobile on cellular, a [tokenless TCP edge](DEPLOY.md#deploy-the-tokenless-tcp-edge-on-a-vps)
19
+ can forward SSH to the Gate without VPN, without storing room or owner credentials on the VPS.
21
20
 
22
21
  ## Status
23
22
 
24
- v0.6.0 — gateway (HTTP + 2 WS legs), pairing flows, routing, presence, rate limits, state persistence; agent
25
- SDK with reconnect; **a real Herdr plugin** (`plugin/`) using Herdr's official extension surface; an app mod,
26
- a PWA, an SSH leg for the Herdr phone app, **room-stream resume** — a phone that drops off wifi replays
27
- what it missed (frames + presence) instead of losing them — **end-to-end payloads** — Noise_XX between
28
- device and host inside the opaque channel, so the cloud routes ciphertext it cannot read — and **push
29
- wake**: VAPID-signed silent pings that raise a phone from its sleep when the host has news; 28 tests. All
30
- of it verified live through a real Cloudflare Tunnel (gate.phuongnb.io.vn), push subscription and all, and systemd user units (gateway, tunnel, publisher) keeping it alive.
23
+ | Client | What it connects to | What it can do |
24
+ |---|---|---|
25
+ | Browser/PWA | Herdgate publisher over HTTPS/WSS | View Herdr metadata and read pane snapshots; no terminal input |
26
+ | Herdr TUI | An existing Herdr TUI session over SSH/WSS | Connect and control it with an approved `act` device and its own SSH key |
27
+ | Herdr Mobile (Core) | A real `herdr-core` runtime over SSH | Core terminals and the Core API, subject to the device scope |
28
+ | Herdr Mobile (TUI adapter) | Existing Herdr TUI panes over SSH | Read-only snapshots, or opt-in Send, keys, Interrupt and native attach/resize for one approved `act` device; not the full Core API |
31
29
 
32
- The Herdr adapter is read-only: it runs `herdr api snapshot` and serves workspaces/tabs/panes/agents/status to
33
- paired devices. It never reads a pane, sends a keystroke, or prompts an agent. Terminal content is a later
34
- slice, by design. No third-party plugin or relay is a dependency — only Herdr's own CLI.
30
+ The Gateway also supports bounded room-stream resume and VAPID push wake. Pairing, publisher updates and
31
+ Mobile authorization are separate: changing the publisher release does not move a room or grant a new scope.
35
32
 
36
33
  ## Layout
37
34
 
@@ -108,8 +105,9 @@ Devices pair into the room and ask for `{op:"view"}`; the host answers with the
108
105
 
109
106
  ## The SSH leg (the Herdr phone app)
110
107
 
111
- The phone app adds machines over SSH — herdgate terminates that SSH itself, so "add a machine" points at the
112
- gate and the session lands on the host's real `herdr-core`:
108
+ The phone app adds machines over SSH. Herdgate terminates SSH at the Gate; use the Gate's reachable SSH
109
+ address or the TCP edge's address. Each entry uses the device ID and key for that room. A Core entry lands
110
+ on the host's real `herdr-core`; the opt-in TUI adapter described below lands on existing TUI panes instead:
113
111
 
114
112
  ```sh
115
113
  ssh -p 2222 d_xxxxxxxx@your-gate # password = the device key shown once at pair time
@@ -121,11 +119,12 @@ ssh -p 2222 d_xxxxxxxx@your-gate # password = the device key shown once a
121
119
  prompts without a terminal. Register the adding machine's `~/.ssh/id_ed25519.pub` in the PWA (SSH →
122
120
  *Public keys*, or `POST /v1/device/sshkey`) and the add is passwordless — Ed25519/RSA/ECDSA, signatures
123
121
  verified per RFC 4252 §7.
124
- - `read` devices get a filtered channel: mutating calls (`terminal.send`, `file.write`, …) are refused **on
125
- the host** with a real JSON-RPC error, and live-terminal mode is downgraded. `act` devices (approved on the
126
- host) get byte-transparent access.
127
- - Only `hc …` and the fixed Herdr TUI bridge commands below run — no remote shell, SFTP or SSH port forwarding.
128
- - The host needs `herdr-core` (`hc`) on PATH or `HERDGATE_HC_BIN`.
122
+ - For real Core, the host rejects mutating calls from `read` devices and downgrades their framed hello.
123
+ An approved `act` device gets byte-transparent Core RPC. The separate TUI adapter enforces its own
124
+ read-only and interactive allowlists.
125
+ - Herdgate only starts supported Core exec commands or fixed Herdr bridge commands. It does not offer
126
+ a generic SSH shell, SFTP or SSH port forwarding.
127
+ - Real Core mode requires `herdr-core` (`hc`); the TUI adapter does not.
129
128
 
130
129
  **Note:** ssh2 1.17.0 has a malformed `server-sig-algs` EXT_INFO (a missing comma garbles the
131
130
  algorithm list) that makes real OpenSSH clients silently abandon publickey auth right after
@@ -180,7 +179,18 @@ client-to-publisher Noise E2E. No third-party relay or inbound client port is ne
180
179
 
181
180
  ### Manage a paired publisher from one CLI
182
181
 
183
- Install the command once with `npm install -g @bom0792/herdgate` (Node 22+).
182
+ Install the command once (Node 22+). On Linux, use `npm install -g @bom0792/herdgate`.
183
+ On Windows, use the npm bootstrap instead; it installs the persistent command
184
+ without requiring admin rights, a separate global npm install, or a running publisher:
185
+
186
+ ```powershell
187
+ npx --yes @bom0792/herdgate@latest install
188
+ ```
189
+
190
+ Open a new PowerShell after installation. In a shell with the old PATH, or if
191
+ User PATH registration is blocked, call
192
+ `& "$env:LOCALAPPDATA\Herdgate\cli\bin\herdgate.cmd"` with the same arguments.
193
+ Use `install --no-path` to create only that shim, without modifying User PATH.
184
194
  Use your own cloud URL; there is no built-in Gate address.
185
195
 
186
196
  ```sh
@@ -211,15 +221,18 @@ rooms or upgrade the VPS.
211
221
  ### Windows as a TUI host
212
222
 
213
223
  Use this only where remote control is approved by the machine's owner/IT.
214
- With Node 22+ on Windows and an existing Gate pairing, use one command to
215
- install and start the TUI publisher (add the relevant Mobile flag if enabled):
224
+ With Node 22+ on Windows and an existing Gate pairing, install and start the
225
+ TUI publisher (add the relevant Mobile flag if enabled):
216
226
 
217
227
  ```powershell
218
- npx --yes @bom0792/herdgate@latest tui setup --mobile-tui-act d_device
219
- npx --yes @bom0792/herdgate@latest tui status
228
+ npx --yes @bom0792/herdgate@latest setup --mobile-act d_device
229
+ npx --yes @bom0792/herdgate@latest status
220
230
  ```
221
231
 
222
- Omit `--mobile-tui-act d_device` for TUI-only setup. The first setup or
232
+ Omit `--mobile-act d_device` for a new TUI-only setup. Since `0.9.29`, Windows
233
+ `setup` and `migrate` from npm also install the durable `herdgate` command on
234
+ first success, even when invoked from `npx`. Use `--no-path` on the first
235
+ setup or migration if you do not want the User PATH entry. The first setup or
223
236
  migration from a manual install needs the desired mode once; it is saved
224
237
  locally only after the publisher connects. For subsequent updates:
225
238
 
@@ -230,17 +243,56 @@ herdgate update
230
243
  The update validates the new release before touching the old publisher. It
231
244
  preserves the device ID and mode, restarts only the publisher if needed, and
232
245
  tries to restore the old release if the new worker cannot connect. Pairing
233
- and SSH keys are not rewritten. Use `install-tui` for install without starting.
246
+ and SSH keys are not rewritten. Before opening a new shell, or if Windows policy
247
+ blocks User PATH registration, use the full path to the Node-pinned shim:
248
+
249
+ ```powershell
250
+ & "$env:LOCALAPPDATA\Herdgate\cli\bin\herdgate.cmd" update
251
+ ```
252
+
253
+ Use `install-tui` for install without starting.
254
+
255
+ #### Windows: `npx` resolves the wrong Node
256
+
257
+ Check the runtime using its full path (adjust it if installed elsewhere):
258
+
259
+ ```powershell
260
+ $node = 'C:\Program Files\nodejs\node.exe'
261
+ & $node --version
262
+ & $node -p 'typeof(WebSocket)'
263
+ ```
234
264
 
235
- The ZIP remains an alternative: extract it and run `node .\windows\install-cli.mjs`.
265
+ Expect Node 22+ and `function`. Starting with `0.9.28`, the main Windows CLI can
266
+ relaunch publisher-management commands using Node under `Program Files` if npm
267
+ started it with an older Node. It does not change `PATH` or override options
268
+ that disable WebSocket. If the fallback cannot find your installation, bypass the
269
+ `npm` and `npx` shims entirely. Example for an existing Mobile Act publisher:
270
+
271
+ ```powershell
272
+ $npm = Join-Path (Split-Path $node) 'node_modules\npm\bin\npm-cli.js'
273
+ $dir = Join-Path $env:TEMP ('herdgate-' + [guid]::NewGuid())
274
+ & $node $npm install --prefix $dir --no-save --ignore-scripts --no-audit --no-fund @bom0792/herdgate@0.9.29
275
+ if ($LASTEXITCODE -ne 0) { throw 'Herdgate installation failed' }
276
+ & $node "$dir\node_modules\@bom0792\herdgate\bin\herdgate.mjs" migrate --mobile-act d_device
277
+ ```
278
+
279
+ Replace `d_device` with the existing approved device ID, or use your actual
280
+ saved/legacy mode. Do not stop the publisher first. The **migration's own**
281
+ `"state":"connected"` output means it finished and saved the mode; `status`
282
+ can still report the old publisher after a failed migration. Verify both TUI
283
+ and Mobile before cleaning up the temporary npm directory.
284
+
285
+ The ZIP remains an alternative: extract it and run `& $node .\windows\install-cli.mjs`.
236
286
 
237
287
  The installer stores each build under `%LOCALAPPDATA%\Herdgate\cli\releases`.
238
288
  The directory junction `current` selects the build used by the stable
239
289
  `bin\herdgate-tui.cmd` shim. Rerun `npx --yes @bom0792/herdgate@latest install-tui`
240
290
  to switch builds. The `tui` subcommand forwards to the installed build; use
241
291
  `tui versions` and `tui use <release-id>` to list/select existing builds.
242
- If you add `%LOCALAPPDATA%\Herdgate\cli\bin` to User PATH, you can also run
243
- `herdgate-tui` directly. The installer does not change PATH.
292
+ The legacy `install-tui` and ZIP installer do not change PATH. The npm
293
+ `install` and first npm `setup`/`migrate` can register the directory in User PATH.
294
+ The main command is stored independently of the publisher selection: rolling
295
+ back the publisher does not remove `herdgate` or tie it to the npm cache.
244
296
 
245
297
  After pairing the laptop and starting its default session with the official
246
298
  Herdr Windows 0.9.5 package, run `herdgate-tui start <path-to-herdr.exe>`.
@@ -256,24 +308,23 @@ in to Herdr Mobile support with the installed Core executable:
256
308
  ```powershell
257
309
  $hc = (Get-Command herdr-core.exe -ErrorAction Stop).Source
258
310
  & $hc server status --json
259
- herdgate-tui stop
260
- herdgate-tui start --hc "$hc"
311
+ herdgate setup --hc "$hc"
261
312
  ```
262
313
 
263
314
  If Core is not running, start it locally with `& $hc server start`. The `--hc`
264
315
  flag keeps the TUI bridge enabled and adds Core access for `act` devices only.
265
316
  The publisher restart interrupts remote connections, not the local TUI server.
266
317
  In `--hc` mode, Herdr Mobile sees Core terminals, not TUI panes.
267
- To expose TUI panes directly instead, use `herdgate-tui start --mobile-tui d_device`
268
- with the ID of a paired `read` device in this laptop’s room. This opt-in mode
318
+ To expose TUI panes directly instead, use `herdgate setup --mobile-read d_device`
319
+ with the ID of a paired `read` device in this laptop's room. This opt-in mode
269
320
  serves only that device with a read-only Core protocol adapter, needs no `hc`
270
321
  binary, and leaves the normal TUI bridge and its existing `act` devices intact.
271
322
  Opening an individual pane in Herdr Mobile shows a periodically refreshed
272
323
  text snapshot of its visible screen. The adapter does not forward keystrokes,
273
324
  resize the pane, or reproduce its full ANSI rendering or scrollback.
274
325
 
275
- For a phone explicitly approved to control this laptop, start the publisher
276
- with `--mobile-tui-act d_device` instead. The device must already have `act`
326
+ For a phone explicitly approved to control this laptop, use
327
+ `herdgate setup --mobile-act d_device` instead. The device must already have `act`
277
328
  scope, and the setting only enables the Core adapter for that device ID.
278
329
  Non-observe attach uses Herdr's native terminal session to forward ANSI output,
279
330
  keys and viewport resize. Resize changes the pane's real terminal size while
@@ -282,17 +333,14 @@ also mapped to TUI actions. The adapter does not implement Core-only features
282
333
  such as templates, task lifecycle or file operations. Enable this mode only
283
334
  where executing commands in existing panes from the phone is authorized.
284
335
 
285
- For the Linux home TUI bridge (laptop → home), the paired host can run:
336
+ ### Linux as a TUI host
286
337
 
287
- ```sh
288
- npx --yes @bom0792/herdgate@latest home-tui setup
289
- npx --yes @bom0792/herdgate@latest home-tui status
290
- ```
338
+ Run these commands as the user who owns the running Herdr server. For a newly
339
+ paired host use `herdgate setup`. For the previous Herdgate home service, use
340
+ `herdgate migrate` instead. Both install a durable systemd user service and
341
+ reuse the pairing and TUI socket. See the [migration checklist](DEPLOY.md#migrate-the-linux-tui-publisher).
291
342
 
292
- Use `home-tui setup --adopt` to migrate the previous home unit created by
293
- Herdgate; other custom units are not overwritten. The command installs a
294
- persistent systemd user service, reuses the existing room and TUI socket,
295
- and does not restart Herdr. Repeat `setup` to update the publisher.
343
+ ### Linux: standalone Mobile TUI publishers
296
344
 
297
345
  On Linux, use `npm run mobile-tui` (or `node src/host/mobile-tui.ts`) as the
298
346
  user running Herdr, with
@@ -302,6 +350,23 @@ Set `HERDR_SOCKET_PATH` if needed to select the existing TUI session. Without
302
350
  mode, use a separate room and set that variable to the exact existing `act`
303
351
  device ID. The publisher never auto-approves new `act` pairings.
304
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
+
305
370
  ## The PWA (the device side)
306
371
 
307
372
  The cloud serves the PWA itself (`src/web/`, `HERDGATE_WEB_ROOT`, `HERDGATE_NO_WEB=1` to disable). A phone
@@ -312,10 +377,10 @@ view the host publishes.
312
377
  HERDGATE_ACCOUNT_TOKEN=… npm start # → http://127.0.0.1:8787/ is the app
313
378
  ```
314
379
 
315
- Safety properties, all asserted in `test/web.test.ts`:
380
+ PWA safeguards (see `test/web.test.ts` and `test/web-pairing.test.ts`):
316
381
 
317
- - **no HTML from the wire** — every string is `textContent`; no `innerHTML`, no `document.write`;
318
- - **one op** — the client only ever asks a host for `{op:"view"}`; the host, not the cloud, decides the rest;
382
+ - **no HTML from the wire** — incoming strings are shown as text, not injected as HTML;
383
+ - **read-only publisher operations** — the PWA can request `view`, `term.list` and `term.read`, but cannot type into a pane;
319
384
  - **a locked-down CSP** — `default-src 'self'`, no inline script or style, `frame-ancestors 'none'`;
320
385
  - **static can't escape** — `realpath`-pinned root, dotfiles and traversal refused (including `%2e%2e`);
321
386
  - **API precedence** — `/v1/*` and `/healthz` are routed before static, so no file can shadow them.
@@ -325,6 +390,32 @@ Verified live: real Herdr → publisher → cloud → **headless Chrome** signed
325
390
 
326
391
  Going public: [DEPLOY.md](DEPLOY.md) (cloudflared, on this machine).
327
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
+
328
419
  ## Herdr-relay lineage
329
420
 
330
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";
@@ -20,6 +21,8 @@ const ROOT = dirname(HERE); // <pkg>
20
21
 
21
22
  const help = `herdgate — every machine, one herd
22
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.
23
26
  herdgate cloud add <name> <https-url>
24
27
  herdgate cloud list
25
28
  herdgate pair --cloud <name> Pair this machine with owner approval.
@@ -346,11 +349,14 @@ function managePublisher(cmd, args) {
346
349
 
347
350
  const [cmd, ...args] = process.argv.slice(2);
348
351
  try {
349
- if (cmd === "setup-host") setupHost();
352
+ if (cmd === "setup-host") {
353
+ setupHost();
354
+ trySyncPiSkills();
355
+ } else if (cmd === "pi-skills" && !args.length) trySyncPiSkills();
350
356
  else if (cmd === "cloud") manageCloud(args);
351
357
  else if (cmd === "pair") pairHost(args);
352
358
  else if (process.platform === "win32" && (
353
- ["setup", "migrate", "start", "update", "install-tui"].includes(cmd) ||
359
+ ["install", "setup", "migrate", "start", "update", "install-tui"].includes(cmd) ||
354
360
  (cmd === "tui" && ["setup", "migrate", "start", "update"].includes(args[0]))
355
361
  ) && (Number(process.versions.node.split(".")[0]) < 22 || typeof globalThis.WebSocket !== "function")) {
356
362
  const node = windowsNode();
@@ -359,6 +365,12 @@ try {
359
365
  process.exitCode = r.status ?? 1;
360
366
  } else if (["setup", "migrate", "start", "stop", "status", "update"].includes(cmd)) managePublisher(cmd, args);
361
367
  else if (cmd === "home-tui") runNode(join(HERE, "home-tui.mjs"), args);
368
+ else if (cmd === "install") {
369
+ if (args.length && !(args.length === 1 && args[0] === "--no-path") && !(args.length === 2 && args[0] === "--root" && args[1])) {
370
+ throw new Error("usage: herdgate install [--no-path | --root <dir>]");
371
+ }
372
+ runNode(join(ROOT, "windows", "install-cli.mjs"), ["--command", ...args]);
373
+ }
362
374
  else if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
363
375
  else if (cmd === "tui") {
364
376
  if (["setup", "migrate", "update"].includes(args[0])) runNode(join(ROOT, "windows", "setup-tui.mjs"), args);
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
@@ -7,7 +7,7 @@ phone/PWA của bạn.
7
7
  ## Yêu cầu
8
8
 
9
9
  - herdr desktop app (per-user, không cần admin) hoặc herdr TUI
10
- - `node` >= 22 trong PATH (kiểm tra: `node -v`)
10
+ - Node 22+ có WebSocket (kiểm tra: `node -v` và `node -p 'typeof(WebSocket)'`, kết quả sau phải là `function`)
11
11
  - Nút **Publish** trong panel yêu cầu Linux/macOS. Với Windows, dùng thử publisher TUI chạy nền bên dưới.
12
12
 
13
13
  ## Cài (Linux / macOS)
@@ -39,11 +39,22 @@ Máy giờ hiện trong PWA; phone pair thiết bị riêng để xem terminal.
39
39
  ## Thử Windows làm host TUI (không cần sshd)
40
40
 
41
41
  Chỉ bật nếu chính sách của máy cho phép điều khiển từ xa. Laptop phải đã pair
42
- trong Herdgate. Có thể cài từ npm bằng `npx --yes @bom0792/herdgate@latest install-tui`.
43
- Nếu dùng ZIP, mở PowerShell ở thư mục vừa giải nén:
42
+ trong Herdgate. Với npm trên Windows, chạy `npx --yes @bom0792/herdgate@latest install`
43
+ để cài lệnh `herdgate` cho user (không cần admin), rồi dùng `herdgate setup`
44
+ khi cài mới hoặc `herdgate migrate`
45
+ để tiếp quản publisher cũ. Nếu bản cũ chưa lưu mode, khai đúng chế độ đang dùng:
46
+ `--mobile-act d_device`, `--mobile-read d_device`, `--hc <path>` hoặc `--plain`.
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.
50
+
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
52
+ máy có nhiều bản Node (sửa đường dẫn nếu cần):
44
53
 
45
54
  ```powershell
46
- node .\windows\install-cli.mjs
55
+ $node = 'C:\Program Files\nodejs\node.exe'
56
+ & $node -p 'typeof(WebSocket)'
57
+ & $node .\windows\install-cli.mjs
47
58
  $bin = Join-Path $env:LOCALAPPDATA 'Herdgate\cli\bin'
48
59
  $env:Path = "$bin;$env:Path"
49
60
  herdgate-tui status
@@ -60,14 +71,24 @@ Nếu không cài `herdr.exe` trong `%LOCALAPPDATA%\HerdrPilot\v0.9.5`, truyền
60
71
  dẫn đầy đủ sau `start`. Khi `status` báo `connected`, có thể đóng PowerShell.
61
72
  `herdgate-tui stop` chỉ dừng publisher. Không tự khởi động khi đăng nhập.
62
73
  Máy điều khiển vẫn cần quyền `act` và SSH key riêng cho room của laptop.
63
- Gói này chỉ phục vụ TUI, không dùng luồng APP/`hc`.
74
+ Mặc định publisher chỉ mở cầu nối TUI, không dùng desktop app hay `hc`.
75
+ Mobile là opt-in: `--hc <path>` dùng Core thật; `--mobile-tui d_device`
76
+ chỉ đọc pane; `--mobile-tui-act d_device` cho phép nhập và resize đối với
77
+ đúng thiết bị đã được duyệt `act`. Adapter TUI không phải bản thay thế đầy đủ
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.
64
82
 
65
83
  ## Bộ gồm
66
84
 
67
85
  mod/herdgate/ → copy vào mods/ của herdr-app
68
86
  plugin/server/*.mjs → publisher (mod tự spawn bằng node)
69
87
  plugin/herdr-plugin.toml → nếu bạn dùng herdr TUI thay vì app
88
+ windows/ → bộ cài và CLI publisher Windows
70
89
 
71
90
  ## Gỡ
72
91
 
73
- rm -rf ~/.config/herdr-app/mods/herdgate ~/.config/herdr-app/herdgate
92
+ Dừng publisher trước. Để chỉ gỡ mod, xóa thư mục
93
+ `~/.config/herdr-app/mods/herdgate` (hoặc thư mục mod tương ứng trên hệ điều hành).
94
+ Giữ `~/.config/herdr-app/herdgate` nếu muốn dùng lại pairing đã có.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.28",
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,10 +32,15 @@
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",
38
41
  "scripts",
42
+ "DEPLOY.md",
43
+ "DESIGN.md",
39
44
  "dist-readme.md",
40
45
  "templates",
41
46
  "windows"
@@ -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 (!c.closed) sendOut(c, false);
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 c = { device, ch, scope, proc, trustedReadCore: trusted, inBuf: Buffer.alloc(0), outBuf: Buffer.alloc(0), flushTimer: null, malformed: 0, closed: false };
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.outBuf.length >= FLUSH_BYTES) sendOut(c, false);
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);