@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.
@@ -0,0 +1,246 @@
1
+ #!/usr/bin/env node
2
+ // Runs an isolated Herdr server, Gate, publisher and TCP edge. Never uses live rooms or keys.
3
+ import assert from 'node:assert/strict';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { randomBytes } from 'node:crypto';
6
+ import { once } from 'node:events';
7
+ import { mkdir, mkdtemp, rm } from 'node:fs/promises';
8
+ import { tmpdir } from 'node:os';
9
+ import { dirname, join, resolve } from 'node:path';
10
+ import { setTimeout as delay } from 'node:timers/promises';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { promisify, stripVTControlCharacters } from 'node:util';
13
+ import { Client } from 'ssh2';
14
+ import { HerdGateAgent } from '../src/agent/index.ts';
15
+ import { startCloud } from '../src/cloud/gateway.ts';
16
+ import { startTcpEdge } from '../src/cloud/ssh-tcp-edge.ts';
17
+ import { State } from '../src/cloud/stores.ts';
18
+ import { createSshBridge } from '../plugin/server/ssh.mjs';
19
+ import { openTerminal } from '../plugin/server/mobile-tui-stream.mjs';
20
+
21
+ const run = promisify(execFile);
22
+ const herdr = process.env.TEST_HERDR_BIN;
23
+ if (!herdr || resolve(herdr) !== herdr) throw new Error('Set TEST_HERDR_BIN to the absolute path to Herdr');
24
+ const rounds = Number(process.argv[2] ?? 24);
25
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > 100) throw new Error('Pass 1 to 100 rounds');
26
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
27
+ const adapter = join(root, 'plugin/server/mobile-tui-core.mjs');
28
+ const dir = await mkdtemp(join(tmpdir(), 'herdgate-mobile-bench-'));
29
+ const env = {
30
+ HOME: dir, PATH: process.env.PATH, LANG: process.env.LANG,
31
+ SHELL: '/bin/sh', XDG_CONFIG_HOME: join(dir, 'config'), XDG_STATE_HOME: join(dir, 'state'),
32
+ XDG_DATA_HOME: join(dir, 'data'), HERDR_SOCKET_PATH: join(dir, 'herdr.sock'), HERDR_BIN_PATH: herdr,
33
+ };
34
+ const host = (...args) => run(herdr, args, { env, cwd: dir, timeout: 5000 });
35
+ const stats = (samples) => {
36
+ if (!samples.length) return undefined;
37
+ const s = samples.toSorted((a, b) => a - b);
38
+ const at = (p) => +s[Math.ceil(p * s.length) - 1].toFixed(1);
39
+ return { n: s.length, p50: at(0.50), p95: at(0.95), max: at(1) };
40
+ };
41
+ const deadline = (promise, label) => {
42
+ const ctrl = new AbortController();
43
+ return Promise.race([promise, delay(6500, undefined, { signal: ctrl.signal, ref: false }).then(() => { throw new Error(`Timeout: ${label}`); })]).finally(() => ctrl.abort());
44
+ };
45
+ const elapsed = (since) => performance.now() - since;
46
+ const rpc = (id, method, params) => JSON.stringify({ jsonrpc: '2.0', id, method, params });
47
+ const marker = () => randomBytes(5).toString('hex');
48
+
49
+ async function coreBench(input, output, letters) {
50
+ let buf = Buffer.alloc(0);
51
+ let id = 0;
52
+ const raw = output[Symbol.asyncIterator]();
53
+ const fill = async () => {
54
+ const next = await raw.next();
55
+ assert.ok(!next.done, 'Core stream ended');
56
+ buf = Buffer.concat([buf, next.value]);
57
+ };
58
+ const send = (channel, kind, payload = Buffer.alloc(0)) => {
59
+ const head = Buffer.alloc(9);
60
+ head.writeUInt32LE(channel);
61
+ head[4] = kind;
62
+ head.writeUInt32LE(payload.length, 5);
63
+ input.write(Buffer.concat([head, payload]));
64
+ };
65
+ const read = async () => {
66
+ while (buf.length < 9) await fill();
67
+ const end = 9 + buf.readUInt32LE(5);
68
+ while (buf.length < end) await fill();
69
+ const value = { channel: buf.readUInt32LE(0), kind: buf[4], body: buf.subarray(9, end), time: performance.now() };
70
+ buf = buf.subarray(end);
71
+ if (value.channel !== 0 && value.kind === 0) {
72
+ const credit = Buffer.alloc(4);
73
+ credit.writeUInt32LE(value.body.length);
74
+ send(value.channel, 1, credit);
75
+ }
76
+ return value;
77
+ };
78
+ const request = (method, params) => {
79
+ send(0, 0, Buffer.from(rpc(++id, method, params)));
80
+ return id;
81
+ };
82
+ const response = async (want) => {
83
+ for (;;) {
84
+ const f = await read();
85
+ if (f.channel !== 0) continue;
86
+ const reply = JSON.parse(f.body.toString());
87
+ if (reply.id !== want) continue;
88
+ assert.ok(reply.result, JSON.stringify(reply.error));
89
+ return reply.result;
90
+ }
91
+ };
92
+ const helloStart = performance.now();
93
+ input.write(rpc(++id, 'hello', { framed: true }) + '\n');
94
+ await deadline((async () => {
95
+ while (!buf.includes(10)) await fill();
96
+ const nl = buf.indexOf(10);
97
+ assert.equal(JSON.parse(buf.subarray(0, nl)).result.framed, true);
98
+ buf = buf.subarray(nl + 1);
99
+ })(), 'Core hello');
100
+ const hello = elapsed(helloStart);
101
+ const { terminals } = await deadline(response(request('terminal.list')), 'list');
102
+ assert.equal(terminals.length, 1, 'benchmark must address only its isolated pane');
103
+ const terminal = terminals[0].address;
104
+ const attachStart = performance.now();
105
+ const { channel } = await deadline(response(request('terminal.attach', { terminal, cols: 120, rows: 28 })), 'attach');
106
+ for (;;) {
107
+ const f = await deadline(read(), 'first paint');
108
+ if (f.channel === channel && f.kind === 0) break;
109
+ }
110
+ const attach = elapsed(attachStart);
111
+ const key = [], sendPaint = [], sendAck = [], keyPaintBytes = [];
112
+ for (let i = 0; i < rounds; i++) {
113
+ const wanted = `k-${marker()}`;
114
+ const start = performance.now();
115
+ send(channel, 0, Buffer.from(wanted));
116
+ let text = '', bytes = 0;
117
+ while (!text.includes(wanted)) {
118
+ const f = await deadline(read(), 'key echo');
119
+ assert.equal(f.channel, channel);
120
+ assert.notEqual(f.kind, 2);
121
+ if (f.kind !== 0) continue;
122
+ text += stripVTControlCharacters(f.body.toString());
123
+ bytes += f.body.length;
124
+ }
125
+ key.push(elapsed(start));
126
+ keyPaintBytes.push(bytes);
127
+ send(channel, 0, Buffer.from([0x15])); // Ctrl+U clears the isolated shell line.
128
+ await delay(125);
129
+ // Alternate every glyph. Herdr can omit unchanged cells from its ANSI deltas.
130
+ const letter = letters[i % 2];
131
+ const suffix = letter.repeat(12);
132
+ const command = `printf '\\033[2J\\033[H'; printf '%s' ${Array(12).fill(letter).join(' ')}; printf '\\n'`;
133
+ const startSend = performance.now();
134
+ const req = request('terminal.send', { terminal, text: command });
135
+ let ack = false, painted = false, seen = '';
136
+ while (!ack || !painted) {
137
+ const f = await deadline(read(), `Send ${i + 1} (ack=${ack}, painted=${painted})`);
138
+ if (f.channel === 0) {
139
+ const msg = JSON.parse(f.body);
140
+ if (msg.id === req) {
141
+ assert.ok(msg.result, JSON.stringify(msg.error));
142
+ sendAck.push(f.time - startSend);
143
+ ack = true;
144
+ }
145
+ } else if (f.channel === channel && f.kind === 0 && !painted) {
146
+ seen += stripVTControlCharacters(f.body.toString());
147
+ if (seen.includes(suffix)) {
148
+ painted = true;
149
+ sendPaint.push(f.time - startSend);
150
+ }
151
+ }
152
+ }
153
+ await delay(125);
154
+ }
155
+ send(channel, 2);
156
+ return { hello, attach, keyMs: stats(key), sendPaintMs: stats(sendPaint), sendAckMs: stats(sendAck), keyPaintBytes: stats(keyPaintBytes) };
157
+ }
158
+
159
+ let server, cloud, edge, publisher, bridge;
160
+ try {
161
+ await mkdir(join(dir, 'config/herdr'), { recursive: true });
162
+ server = spawn(herdr, ['server'], { env, cwd: dir, stdio: 'ignore' });
163
+ const until = performance.now() + 5000;
164
+ while (!await host('status', 'server', '--json').then(({ stdout }) => JSON.parse(stdout).running, () => false)) {
165
+ if (performance.now() > until) throw new Error('Isolated Herdr server did not start');
166
+ await delay(50);
167
+ }
168
+ await host('workspace', 'create', '--cwd', dir, '--label', 'bench-mobile', '--focus');
169
+ const panes = JSON.parse((await host('pane', 'list')).stdout).result.panes;
170
+ assert.equal(panes.length, 1);
171
+ const pane = panes[0];
172
+ await host('pane', 'run', pane.pane_id, "PS1='bench> '; export PS1");
173
+ // Measure Herdr's native controller alone, before Core framing and SSH.
174
+ const oldSocket = process.env.HERDR_SOCKET_PATH;
175
+ process.env.HERDR_SOCKET_PATH = env.HERDR_SOCKET_PATH;
176
+ const nativeSamples = [];
177
+ let native;
178
+ try {
179
+ native = await openTerminal(herdr, pane.terminal_id, 120, 28);
180
+ for (let i = 0; i < rounds; i++) {
181
+ const wanted = `n-${marker()}`;
182
+ const start = performance.now();
183
+ await native.send({ type: 'terminal.input', bytes: Buffer.from(wanted).toString('base64') });
184
+ let text = '';
185
+ while (!text.includes(wanted)) {
186
+ const paint = await deadline(native.frames.next(), 'native echo');
187
+ assert.equal(paint.done, false);
188
+ text += stripVTControlCharacters(paint.value.bytes.toString());
189
+ }
190
+ nativeSamples.push(elapsed(start));
191
+ await native.send({ type: 'terminal.input', bytes: 'FQ==' });
192
+ await delay(150);
193
+ }
194
+ } finally {
195
+ native?.close();
196
+ if (oldSocket === undefined) delete process.env.HERDR_SOCKET_PATH;
197
+ else process.env.HERDR_SOCKET_PATH = oldSocket;
198
+ }
199
+ console.log(JSON.stringify({ route: 'Herdr native controller', keyMs: stats(nativeSamples) }));
200
+ await delay(250);
201
+ const child = spawn(process.execPath, [adapter, '--interactive', 'connect'], { env, cwd: dir });
202
+ const childExit = once(child, 'close');
203
+ try { console.log(JSON.stringify({ route: 'Core adapter (local pipes)', ...await coreBench(child.stdin, child.stdout, 'AB') })); }
204
+ finally { child.stdin.end(); await deadline(childExit, 'adapter exit').catch(() => child.kill()); }
205
+ await delay(250);
206
+
207
+ const account = { id: 'bench', name: 'bench', token: marker() };
208
+ const statePath = join(dir, 'gate.json');
209
+ const state = new State([account], statePath);
210
+ const room = state.addRoom(account.id, 'bench');
211
+ const { device, secret } = state.addDevice(room.room, 'bench-act', 'act');
212
+ cloud = await startCloud({ accounts: [account], statePath, log: () => {}, ssh: { port: 0, keyPath: join(dir, 'gate-key.json') } });
213
+ edge = await startTcpEdge({ gate: `http://127.0.0.1:${cloud.port}`, port: 0 });
214
+ bridge = createSshBridge({
215
+ tuiOnly: true, mobileTuiAdapter: { device: device.id, scope: 'act', script: adapter },
216
+ scopeOf: (id) => publisher.scopeOf(id), send: (id, body) => publisher.send(id, body),
217
+ spawnImpl: (bin, args, opts) => spawn(bin, args, { ...opts, env, cwd: dir }),
218
+ });
219
+ publisher = new HerdGateAgent({ endpoint: `ws://127.0.0.1:${cloud.port}/v1/agent/ws`, roomToken: room.token, adapter: {
220
+ info: () => ({ name: 'bench', version: 'test' }), onFrame: (id, body) => { bridge.handle(id, body); },
221
+ onDevices: () => {}, onPairAsk: () => false,
222
+ } });
223
+ publisher.start();
224
+ await deadline(publisher.firstHello, 'publisher hello');
225
+ const client = new Client();
226
+ client.on('error', () => {});
227
+ try {
228
+ const start = performance.now();
229
+ const ready = once(client, 'ready');
230
+ client.connect({ host: '127.0.0.1', port: edge.port, username: device.id, password: secret, readyTimeout: 5000 });
231
+ await deadline(ready, 'SSH ready');
232
+ const sshReady = elapsed(start);
233
+ const stream = await deadline(new Promise((res, rej) => client.exec('hc connect', (err, channel) => err ? rej(err) : res(channel))), 'SSH exec');
234
+ stream.stderr.resume();
235
+ console.log(JSON.stringify({ route: 'TCP edge + Gate + publisher (all local)', sshReady, ...await coreBench(stream, stream, 'CD') }));
236
+ stream.end();
237
+ } finally { client.end(); }
238
+ } finally {
239
+ bridge?.closeAll();
240
+ publisher?.stop();
241
+ await edge?.close();
242
+ await cloud?.close();
243
+ await host('server', 'stop').catch(() => {});
244
+ if (server && server.exitCode === null && server.signalCode === null) server.kill();
245
+ await rm(dir, { recursive: true, force: true });
246
+ }
@@ -0,0 +1,4 @@
1
+ import { trySyncPiSkills } from '../bin/pi-skills.mjs';
2
+
3
+ // A dependency install or npx fetch is not a user-level setup request.
4
+ if (process.env.npm_config_global === 'true') trySyncPiSkills();
@@ -9,6 +9,13 @@ const url = new URL(process.env.HERDGATE_URL);
9
9
  if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
10
10
  throw new Error("HERDGATE_URL must be an HTTPS origin");
11
11
  }
12
+ const loopback = process.env.HERDGATE_AGENT_LOOPBACK_PORT;
13
+ if (loopback !== undefined && (!/^[1-9]\d{0,4}$/.test(loopback) || Number(loopback) > 65535)) {
14
+ throw new Error("HERDGATE_AGENT_LOOPBACK_PORT must be a port from 1 to 65535");
15
+ }
16
+ const endpoint = loopback
17
+ ? `ws://127.0.0.1:${loopback}/v1/agent/ws`
18
+ : `wss://${url.host}/v1/agent/ws`;
12
19
  const token = process.env.HERDGATE_ROOM_TOKEN;
13
20
  if (!token) throw new Error("configure a dedicated room token for the TUI mobile pilot");
14
21
  const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
@@ -35,7 +42,10 @@ const bridge = createSshBridge({
35
42
  });
36
43
 
37
44
  const agent = new HerdGateAgent({
38
- endpoint: `wss://${url.host}/v1/agent/ws`, roomToken: token, log,
45
+ endpoint, roomToken: token,
46
+ log: (line) => log(loopback && line.startsWith("cloud hello:") ? `${line} via loopback 127.0.0.1:${loopback}` : line),
47
+ // Only a co-located Gate may use plaintext. Preserve its public Host check.
48
+ wsOptions: loopback ? { headers: { Host: url.host }, agent: false, handshakeTimeout: 5000, perMessageDeflate: false } : undefined,
39
49
  adapter: {
40
50
  info: () => ({ name, version: "tui-core-pilot", capabilities: [controller ? "interactive" : "read-only"] }),
41
51
  onPairAsk: () => false,
@@ -1,7 +1,8 @@
1
1
  // Per-user installation. On Windows, directory junctions do not need admin or Developer Mode.
2
+ import { spawnSync } from "node:child_process";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
4
  import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
4
- import { basename, dirname, join, resolve } from "node:path";
5
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
6
7
 
7
8
  const source = fileURLToPath(new URL("../", import.meta.url));
@@ -15,14 +16,26 @@ function directory(path) {
15
16
  if (!lstatSync(path).isDirectory()) throw new Error(`expected a real directory: ${path}`);
16
17
  }
17
18
 
18
- function inputs() {
19
- return ["plugin/server", "windows"].flatMap((dir) => readdirSync(join(source, dir), { withFileTypes: true })
20
- .filter((file) => file.isFile() && file.name.endsWith(".mjs"))
21
- .map((file) => `${dir}/${file.name}`)).sort();
19
+ async function inputs() {
20
+ function files(dir) {
21
+ return readdirSync(join(source, dir), { withFileTypes: true }).flatMap((file) => {
22
+ const name = `${dir}/${file.name}`;
23
+ return file.isDirectory() ? files(name) : file.isFile() ? [name] : [];
24
+ });
25
+ }
26
+ const runtime = ["plugin", "windows"];
27
+ // ZIPs built before the standalone command do not contain these npm assets.
28
+ for (const dir of ["bin", "app-mod", "templates"]) if (stat(join(source, dir))?.isDirectory()) runtime.push(dir);
29
+ const assets = runtime.flatMap(files);
30
+ if (stat(join(source, ".agents", "skills"))?.isDirectory()) {
31
+ const { piSkillFiles } = await import("../bin/pi-skills.mjs");
32
+ assets.push(...piSkillFiles.map(name => `.agents/skills/${name}`));
33
+ }
34
+ return assets.sort();
22
35
  }
23
36
 
24
- function installRelease(releases) {
25
- const files = inputs().map((name) => [name, readFileSync(join(source, name))]);
37
+ async function installRelease(releases) {
38
+ const files = (await inputs()).map((name) => [name, readFileSync(join(source, name))]);
26
39
  const hash = createHash("sha256");
27
40
  for (const [name, contents] of files) hash.update(`${name}\0${contents.length}\0`).update(contents);
28
41
  const id = `tui-${hash.digest("hex").slice(0, 16)}`;
@@ -47,13 +60,13 @@ function installRelease(releases) {
47
60
  return id;
48
61
  }
49
62
 
50
- function selectRelease(root, releases, id) {
63
+ function selectRelease(root, releases, id, link = "current") {
51
64
  if (!releasePattern.test(id)) throw new Error("invalid release ID");
52
65
  const dest = join(releases, id);
53
66
  if (!stat(dest)?.isDirectory() || readFileSync(join(dest, "release.txt"), "utf8").trim() !== id) {
54
67
  throw new Error(`release not installed: ${id}`);
55
68
  }
56
- const current = join(root, "current");
69
+ const current = join(root, link);
57
70
  const old = stat(current);
58
71
  if (old) {
59
72
  if (!old.isSymbolicLink()) throw new Error(`refusing to replace a real file or directory: ${current}`);
@@ -79,17 +92,17 @@ function selectRelease(root, releases, id) {
79
92
  }
80
93
  }
81
94
 
82
- function installShim(root) {
95
+ function installShim(root, name, target, marker) {
83
96
  const bin = join(root, "bin");
84
97
  directory(bin);
85
- const shim = join(bin, "herdgate-tui.cmd");
98
+ const shim = join(bin, name);
86
99
  const previous = stat(shim);
87
- if (previous && (!previous.isFile() || !readFileSync(shim, "utf8").startsWith("@rem Herdgate TUI CLI\r\n"))) {
100
+ if (previous && (!previous.isFile() || !readFileSync(shim, "utf8").startsWith(marker + "\r\n"))) {
88
101
  throw new Error(`refusing to overwrite an unmanaged shim: ${shim}`);
89
102
  }
90
103
  // Match the Node used for install, not a node.exe from the caller's cwd.
91
104
  const node = process.execPath.replaceAll("%", "%%");
92
- const content = `@rem Herdgate TUI CLI\r\n@echo off\r\nsetlocal DisableDelayedExpansion\r\n"${node}" "%~dp0..\\current\\windows\\cli.mjs" %*\r\nexit /b %errorlevel%\r\n`;
105
+ const content = `${marker}\r\n@echo off\r\nsetlocal DisableDelayedExpansion\r\n"${node}" "%~dp0..\\${target}" %*\r\nexit /b %errorlevel%\r\n`;
93
106
  // Self-update is running from this batch file; never rewrite an unchanged shim.
94
107
  if (previous && readFileSync(shim, "utf8") === content) return;
95
108
  const staged = `${shim}.${randomUUID()}`;
@@ -101,36 +114,89 @@ function installShim(root) {
101
114
  }
102
115
  }
103
116
 
117
+ function registerUserPath(root) {
118
+ const system = process.env.SystemRoot;
119
+ if (!isAbsolute(system ?? "")) return false;
120
+ const powershell = join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
121
+ const script = `
122
+ $ErrorActionPreference = 'Stop'
123
+ $bin = $env:HERDGATE_INSTALL_BIN
124
+ if (!$bin -or $bin.Contains(';')) { exit 1 }
125
+ $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
126
+ try {
127
+ $old = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
128
+ if ($old -isnot [string]) { exit 1 }
129
+ foreach ($entry in $old.Split(';')) {
130
+ $expanded = [Environment]::ExpandEnvironmentVariables($entry.Trim().Trim([char]34))
131
+ if ($expanded.TrimEnd([char[]]@(92, 47)) -ieq $bin) { exit 0 }
132
+ }
133
+ $new = if ($old -and !$old.EndsWith(';')) { $old + ';' + $bin } else { $old + $bin }
134
+ if ($key.GetValueNames() -contains 'Path' -and $key.GetValueKind('Path') -eq 'ExpandString') {
135
+ if ($bin.Contains('%')) { exit 1 }
136
+ $key.SetValue('Path', $new, [Microsoft.Win32.RegistryValueKind]::ExpandString)
137
+ } else {
138
+ [Environment]::SetEnvironmentVariable('Path', $new, [EnvironmentVariableTarget]::User)
139
+ }
140
+ } finally { $key.Dispose() }
141
+ exit 0`;
142
+ const result = spawnSync(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
143
+ env: { ...process.env, HERDGATE_INSTALL_BIN: join(root, "bin") }, shell: false, windowsHide: true,
144
+ timeout: 15_000, encoding: "utf8",
145
+ });
146
+ return result.status === 0;
147
+ }
148
+
104
149
  try {
105
150
  if (process.platform === "win32" && typeof globalThis.WebSocket !== "function") throw new Error("run this installer with Node 22+ with WebSocket enabled");
106
151
  const args = process.argv.slice(2);
107
- let root = process.platform === "win32" && process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Herdgate", "cli") : null;
152
+ const defaultRoot = process.platform === "win32" && process.env.LOCALAPPDATA ? resolve(process.env.LOCALAPPDATA, "Herdgate", "cli") : null;
153
+ let root = defaultRoot;
108
154
  let use = null;
109
155
  let stage = false;
156
+ let command = false;
157
+ let userPath = true;
110
158
  while (args.length) {
111
159
  const flag = args.shift();
112
160
  if (flag === "--stage") { stage = true; continue; }
161
+ if (flag === "--command") { command = true; continue; }
162
+ if (flag === "--no-path") { userPath = false; continue; }
113
163
  const value = args.shift();
114
164
  if (flag === "--root" && value) root = resolve(value);
115
165
  else if (flag === "--use" && value) use = value;
116
- else throw new Error("usage: node windows/install-cli.mjs [--root <dir>] [--stage | --use <release-id>]");
166
+ else throw new Error("usage: node windows/install-cli.mjs [--root <dir>] [--stage | --use <release-id>] [--command [--no-path]]");
117
167
  }
118
168
  if (!root) throw new Error("this installer defaults to %LOCALAPPDATA% on Windows");
119
- if (stage && use) throw new Error("--stage and --use cannot be combined");
169
+ if ((stage && (use || command)) || (!command && !userPath)) throw new Error("invalid installer option combination");
120
170
  directory(root);
121
171
  const releases = join(root, "releases");
122
172
  directory(releases);
123
173
  const lock = join(root, ".installing");
124
174
  mkdirSync(lock);
125
175
  try {
126
- const id = use ?? installRelease(releases);
176
+ const id = use ?? await installRelease(releases);
127
177
  if (stage) {
128
178
  console.log(id);
179
+ } else if (command) {
180
+ if (!releasePattern.test(id) || !stat(join(releases, id, "bin", "herdgate.mjs"))?.isFile()) {
181
+ throw new Error("the standalone command requires the Herdgate npm package");
182
+ }
183
+ installShim(root, "herdgate.cmd", "command\\bin\\herdgate.mjs", "@rem Herdgate CLI");
184
+ selectRelease(root, releases, id, "command");
185
+ const shim = join(root, "bin", "herdgate.cmd");
186
+ if (userPath && defaultRoot && samePath(root, defaultRoot)) {
187
+ if (registerUserPath(root)) console.log(`Herdgate CLI: ${shim}\nOpen a new terminal for User PATH; in the current shell, use the full path above.`);
188
+ else console.log(`Herdgate CLI: ${shim}\nCould not register User PATH; invoke the shim by full path.`);
189
+ } else console.log(`Herdgate CLI: ${shim}`);
129
190
  } else {
130
191
  selectRelease(root, releases, id);
131
- installShim(root);
192
+ installShim(root, "herdgate-tui.cmd", "current\\windows\\cli.mjs", "@rem Herdgate TUI CLI");
132
193
  console.log(`Herdgate TUI CLI: ${id}\nShim: ${join(root, "bin", "herdgate-tui.cmd")}`);
133
194
  }
195
+ // Stage/rollback never install skills; sync only after a successful install or CLI refresh.
196
+ if (!stage && (command || !use) && stat(join(source, "bin", "pi-skills.mjs"))?.isFile()) {
197
+ const { trySyncPiSkills } = await import("../bin/pi-skills.mjs");
198
+ trySyncPiSkills();
199
+ }
134
200
  } finally {
135
201
  rmSync(lock, { force: true, recursive: true });
136
202
  }
@@ -14,6 +14,7 @@ function invoke(file, args) {
14
14
  const child = spawnSync(process.execPath, [file, ...args], { encoding: "utf8", shell: false, windowsHide: true, timeout: 30_000 });
15
15
  if (child.error) throw child.error;
16
16
  if (child.status !== 0) throw new Error(child.stderr.trim() || `${args[0]} failed (${child.status})`);
17
+ if (child.stderr) process.stderr.write(child.stderr);
17
18
  return child.stdout.trim();
18
19
  }
19
20
  function storedProfile(path) {
@@ -31,8 +32,10 @@ function writeProfile(path, args) {
31
32
  }
32
33
 
33
34
  async function setup() {
34
- const [cmd, ...requested] = process.argv.slice(2);
35
- if (cmd === "update" && requested.length) throw new Error("use herdgate setup to change publisher options");
35
+ const [cmd, ...options] = process.argv.slice(2);
36
+ const requested = options.filter(flag => flag !== "--no-path");
37
+ const noPath = requested.length !== options.length;
38
+ if (cmd === "update" && options.length) throw new Error("use herdgate setup to change publisher options");
36
39
  if (!["setup", "migrate", "update"].includes(cmd)) throw new Error("expected setup, migrate, or update");
37
40
  const plain = requested.includes("--plain");
38
41
  if (plain && requested.length !== 1) throw new Error("--plain cannot be combined with other publisher options");
@@ -81,10 +84,23 @@ async function setup() {
81
84
  const next = install("--stage");
82
85
  if (!releaseId.test(next)) throw new Error("installer did not return a release ID");
83
86
  cli(next, "check", ...args); // validate executable, pairing and Herdr before disrupting the old worker
87
+ const refreshCommand = () => {
88
+ // Older standalone bundles do not have the top-level npm CLI. Keep their compatibility shim usable.
89
+ if (!existsSync(join(releases, next, "bin", "herdgate.mjs"))) return;
90
+ const first = !existsSync(join(root, "bin", "herdgate.cmd"));
91
+ try {
92
+ const output = install("--command", "--use", next, ...(!first || noPath ? ["--no-path"] : []));
93
+ if (first) console.error(output);
94
+ } catch (error) {
95
+ // Command registration isn't part of the publisher transaction.
96
+ console.error(`herdgate tui: could not install the persistent command: ${errorText(error)}`);
97
+ }
98
+ };
84
99
  const oldStatus = status(prior ?? next);
85
100
  const running = !["stopped", "stale"].includes(oldStatus.state);
86
101
  if (prior === next && profile && JSON.stringify(args) === JSON.stringify(profile) && oldStatus.state === "connected") {
87
102
  install("--use", next); // refresh pinned Node shim, no worker restart
103
+ refreshCommand();
88
104
  console.log(JSON.stringify({ release: next, ...oldStatus }));
89
105
  return;
90
106
  }
@@ -95,6 +111,7 @@ async function setup() {
95
111
  triedStart = true;
96
112
  const result = await start(next, args);
97
113
  writeProfile(profilePath, args);
114
+ refreshCommand();
98
115
  console.log(JSON.stringify({ release: next, ...result }));
99
116
  } catch (cause) {
100
117
  try {