@bom0792/herdgate 0.9.36 → 0.9.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/herdr/SKILL.md +100 -0
- package/DESIGN.md +28 -0
- package/README.md +55 -1
- package/package.json +2 -1
- package/plugin/herdr-plugin.toml +17 -0
- package/plugin/server/attachments.mjs +184 -0
- package/plugin/server/e2e.mjs +27 -0
- package/plugin/server/git-safe.mjs +126 -0
- package/plugin/server/index.mjs +317 -5
- package/plugin/server/mobile-tui-core.mjs +701 -41
- package/plugin/server/mobile-tui-stream.mjs +262 -3
- package/plugin/server/pi-receipt-gc.mjs +183 -0
- package/plugin/server/pi-receipt-search.mjs +217 -0
- package/plugin/server/pi-receipts.mjs +125 -13
- package/plugin/server/pi-transcript.mjs +217 -0
- package/plugin/server/pi-usage.mjs +84 -0
- package/plugin/server/pi-wake.mjs +319 -0
- package/plugin/server/pi-worker.d.mts +7 -0
- package/plugin/server/pi-worker.mjs +45 -4
- package/plugin/server/port-attr.mjs +172 -0
- package/plugin/server/sysmon.mjs +212 -0
- package/plugin/server/wake-event.mjs +255 -0
- package/src/agent/index.ts +4 -2
- package/src/agent/qr.ts +70 -0
- package/src/cloud/gateway.ts +5 -1
- package/src/cloud/sshd.ts +5 -8
- package/src/host/main.ts +14 -1
- package/src/web/app.css +379 -0
- package/src/web/app.js +1557 -5
- package/src/web/e2e.js +29 -2
- package/src/web/index.html +1 -0
- package/windows/npm-update.mjs +261 -11
- package/windows/update-policy.mjs +98 -0
package/plugin/server/index.mjs
CHANGED
|
@@ -6,21 +6,33 @@
|
|
|
6
6
|
* permissions are checked before dispatching any interactive bridge commands.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { spawn } from "node:child_process";
|
|
9
|
+
import { execFile as execFileCb, spawn } from "node:child_process";
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { promisify } from "node:util";
|
|
11
12
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
|
|
12
13
|
import { join, dirname } from "node:path";
|
|
13
14
|
import { hostname, homedir } from "node:os";
|
|
14
15
|
import { fileURLToPath } from "node:url";
|
|
15
16
|
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
|
|
17
|
+
import { gitRead, diffRepoDir } from "./git-safe.mjs";
|
|
16
18
|
import { createSshBridge } from "./ssh.mjs";
|
|
17
19
|
import { findBody, findReceipt, journalBase as receiptJournalBase, publicReceipt, watchReceipts } from "./pi-receipts.mjs";
|
|
20
|
+
import { listAttachments, saveAttachment } from "./attachments.mjs";
|
|
21
|
+
import { searchReceipts, sessionRoots as piSessionRoots, findSessionFile } from "./pi-receipt-search.mjs";
|
|
22
|
+
import { usageRollup } from "./pi-usage.mjs";
|
|
23
|
+
import { readAllSpawns } from "./pi-wake.mjs";
|
|
24
|
+
import { sysSnapshot } from "./sysmon.mjs";
|
|
25
|
+
import { attributePorts } from "./port-attr.mjs";
|
|
26
|
+
import { parsePiTranscript } from "./pi-transcript.mjs";
|
|
18
27
|
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";
|
|
28
|
+
import { JOB_ID, MAX_PENDING, MAX_PROMPT, WORKSPACE_NAME, appendJob, jobsFile, publicJob, queueDepth, readHeartbeat, readJobs, workerBase } from "./pi-worker.mjs";
|
|
20
29
|
import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
|
|
21
30
|
import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
|
|
22
31
|
|
|
23
32
|
const D = dirs();
|
|
33
|
+
const execFile = promisify(execFileCb);
|
|
34
|
+
/** diff.get ships at most 128 KiB of `git show` output, marked truncated beyond. */
|
|
35
|
+
const MAX_DIFF_BYTES = 128 * 1024;
|
|
24
36
|
const NAME = process.env.HERDGATE_HOST_NAME || hostname();
|
|
25
37
|
const log = (line) => console.error(`herdgate: ${line}`);
|
|
26
38
|
/** The panel's settings file (app home herdgate dir) — the owner's switches live
|
|
@@ -116,6 +128,84 @@ function runningPid() {
|
|
|
116
128
|
}
|
|
117
129
|
}
|
|
118
130
|
|
|
131
|
+
/** --- Wave 2 observer wiring: sysmon / port-attr / pi-transcript behind ops --- */
|
|
132
|
+
|
|
133
|
+
/** Raw `herdr pane list` rows, every field kept. common.mjs's herdrPanes is the
|
|
134
|
+
* PWA picker view and drops fields on purpose; the observers need `pid`, which
|
|
135
|
+
* a Herdr build may or may not expose — "no pid column" must stay
|
|
136
|
+
* distinguishable from "no live children". Returns null when the CLI fails. */
|
|
137
|
+
async function paneRowsWithPids() {
|
|
138
|
+
try {
|
|
139
|
+
const { stdout } = await execFile(D.herdrBin, ["pane", "list"], { timeout: 8_000, maxBuffer: 8 << 20 });
|
|
140
|
+
const parsed = JSON.parse(stdout);
|
|
141
|
+
const panes = parsed?.result?.panes ?? parsed?.panes ?? [];
|
|
142
|
+
return Array.isArray(panes) ? panes.filter((p) => p && typeof p.pane_id === "string") : [];
|
|
143
|
+
} catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Every spawn-registry record across scopes; unreadable registry → [] (the
|
|
149
|
+
* observers fail closed, they never take the host down). */
|
|
150
|
+
function spawnRecords() {
|
|
151
|
+
try {
|
|
152
|
+
return readAllSpawns(receiptJournalBase());
|
|
153
|
+
} catch {
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Live spawn children joined with their pane rows: one row per live child,
|
|
159
|
+
* newest record per id. The registry stores pane ids, never pids — a pid
|
|
160
|
+
* exists only when this Herdr's pane list carries one. */
|
|
161
|
+
function liveSpawnChildren(panes) {
|
|
162
|
+
const byId = new Map();
|
|
163
|
+
for (const record of spawnRecords()) {
|
|
164
|
+
const prior = byId.get(record.id);
|
|
165
|
+
if (!prior || (record.ts ?? 0) >= (prior.ts ?? 0)) byId.set(record.id, record);
|
|
166
|
+
}
|
|
167
|
+
const byPane = new Map(panes.map((p) => [p.pane_id, p]));
|
|
168
|
+
const rows = [];
|
|
169
|
+
for (const record of byId.values()) {
|
|
170
|
+
const pane = record.paneId ? byPane.get(record.paneId) : undefined;
|
|
171
|
+
if (!pane) continue; // pane gone → child not live
|
|
172
|
+
const pid = Number(pane.pid);
|
|
173
|
+
rows.push({ key: record.name, paneId: record.paneId, pid: Number.isInteger(pid) && pid > 0 ? pid : null });
|
|
174
|
+
}
|
|
175
|
+
return rows;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The transcript behind one receipt: the spawn record's own sessionFile when
|
|
179
|
+
* it exists (records may predate the field), else Pi's standard session roots.
|
|
180
|
+
* Returns null when nothing is found — the caller answers a clear error op. */
|
|
181
|
+
function transcriptFor(entry) {
|
|
182
|
+
const record = spawnRecords()
|
|
183
|
+
.filter((s) => s.sessionId === entry.sessionId && typeof s.sessionFile === "string")
|
|
184
|
+
.sort((a, b) => (b.ts ?? 0) - (a.ts ?? 0))[0];
|
|
185
|
+
if (record && existsSync(record.sessionFile)) return record.sessionFile;
|
|
186
|
+
return findSessionFile(piSessionRoots(), entry.sessionId);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Which Herdr argv focuses a pane — probed once from --help (pane focus, else the
|
|
190
|
+
* tab equivalent), null when this Herdr supports neither. Never throws. */
|
|
191
|
+
let paneFocusArgv;
|
|
192
|
+
async function paneFocusArgvProbe() {
|
|
193
|
+
if (paneFocusArgv !== undefined) return paneFocusArgv;
|
|
194
|
+
const help = async (...args) => {
|
|
195
|
+
try {
|
|
196
|
+
const { stdout } = await execFile(D.herdrBin, args, { timeout: 5_000 });
|
|
197
|
+
return stdout;
|
|
198
|
+
} catch {
|
|
199
|
+
return "";
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
if (/\bfocus\b/.test(await help("pane", "--help"))) return (paneFocusArgv = ["pane", "focus"]);
|
|
203
|
+
const tabHelp = await help("tab", "--help");
|
|
204
|
+
if (/\bfocus\b/.test(tabHelp)) return (paneFocusArgv = ["tab", "focus"]);
|
|
205
|
+
if (/\bselect\b/.test(tabHelp)) return (paneFocusArgv = ["tab", "select"]);
|
|
206
|
+
return (paneFocusArgv = null);
|
|
207
|
+
}
|
|
208
|
+
|
|
119
209
|
/** --- serve: the startup hook. Start the publisher once, then exit (Herdr's hook is one-shot). --- */
|
|
120
210
|
async function serve() {
|
|
121
211
|
if (process.env.HERDGATE_PUBLISHER_CHILD === "1") return publisherLoop(); // the child
|
|
@@ -222,6 +312,8 @@ async function publisherLoop() {
|
|
|
222
312
|
if (payload && typeof payload === "object" && typeof payload.op === "string" && payload.op.startsWith("e2e")) log(`e2e: op ${payload.op} from ${device}`);
|
|
223
313
|
if (!payload || typeof payload !== "object") return null;
|
|
224
314
|
if (payload.op === "e2e.init") {
|
|
315
|
+
const prior = e2eSessions.get(device);
|
|
316
|
+
if (prior?.ready()) log(`e2e: rotating session with ${device} (lifetime bound reached on the device)`);
|
|
225
317
|
const ch = new HostChannel(await e2eSelfKey());
|
|
226
318
|
if (wsRef !== ws || ws.readyState !== 1 || !devices.some(d => d.id === device)) return { reply: null };
|
|
227
319
|
e2eSessions.set(device, ch);
|
|
@@ -336,6 +428,12 @@ async function publisherLoop() {
|
|
|
336
428
|
for (const sub of targets) {
|
|
337
429
|
store.markDelivered(sub.device, entry.id);
|
|
338
430
|
pushReceiptTo(sub.device, entry);
|
|
431
|
+
// A phone with the app closed misses the frame; the wake push brings it
|
|
432
|
+
// back so flushWatches can replay the settle (throttled per device).
|
|
433
|
+
const known = devices.find(d => d.id === sub.device);
|
|
434
|
+
if (known && known.connected !== false) continue;
|
|
435
|
+
log(`receipts: wake ${sub.device} (settle while offline)`);
|
|
436
|
+
wakeAway(true);
|
|
339
437
|
}
|
|
340
438
|
};
|
|
341
439
|
|
|
@@ -389,8 +487,16 @@ async function publisherLoop() {
|
|
|
389
487
|
lifecycle?.setConnected(true);
|
|
390
488
|
log(`connected to ${url}${loopbackPort ? ` via loopback 127.0.0.1:${loopbackPort}` : ""} (room ${m.roomId}, ${devices.length} device(s))`);
|
|
391
489
|
if (process.env.HERDGATE_PI_RECEIPTS === "1" && !receiptWatch) {
|
|
392
|
-
|
|
490
|
+
// Settles push to subscribed devices only. Parent wakes no longer ride
|
|
491
|
+
// this watcher — the child-cooperative design (arm/marker/observer)
|
|
492
|
+
// missed three times live. Herdr now reports through the [[events]]
|
|
493
|
+
// hooks (server/wake-event.mjs): wake survives a child that never
|
|
494
|
+
// arms, and a pane that dies before settling still reports.
|
|
495
|
+
receiptWatch = watchReceipts(receiptJournalBase(), (entry) => {
|
|
496
|
+
pushReceipt(entry);
|
|
497
|
+
});
|
|
393
498
|
log(`receipts: journal push enabled (${receiptJournalBase()})`);
|
|
499
|
+
log(`wake: herdr event hooks (pane.agent_status_changed/exited/closed)`);
|
|
394
500
|
}
|
|
395
501
|
for (const d of devices) flushWatches(d.id);
|
|
396
502
|
void publish(ws);
|
|
@@ -440,6 +546,118 @@ async function publisherLoop() {
|
|
|
440
546
|
return void replyTo({ op: "receipt.result", id: id || null,
|
|
441
547
|
...publicReceipt(entry), ...(enabled ? {} : { reason: "pi_receipts_disabled" }) });
|
|
442
548
|
}
|
|
549
|
+
if (op === "receipt.search") {
|
|
550
|
+
// Experimental (opt-in HERDGATE_PI_RECEIPTS=1): BM25 keyword search over
|
|
551
|
+
// the journal; bodies and transcripts score host-side only. Hits are
|
|
552
|
+
// publicReceipt-shaped (id, score, status, reason, usage) — no snippet,
|
|
553
|
+
// no sessionId, no session file, no timestamps. Search finds ids; the
|
|
554
|
+
// gated receipt.body op serves any text.
|
|
555
|
+
const enabled = process.env.HERDGATE_PI_RECEIPTS === "1";
|
|
556
|
+
const query = typeof payload.query === "string" ? payload.query.slice(0, 200) : "";
|
|
557
|
+
const limit = Number(payload.limit);
|
|
558
|
+
const hits = enabled && query.trim()
|
|
559
|
+
? searchReceipts({ base: receiptJournalBase(), sessionsRoot: piSessionRoots(), query,
|
|
560
|
+
limit: Number.isFinite(limit) ? limit : 10, all: payload.all === true })
|
|
561
|
+
: [];
|
|
562
|
+
log(`receipts: ${m.device} search ${JSON.stringify(query)} -> ${hits.length} hit(s)`);
|
|
563
|
+
return void replyTo({ op: "receipt.search.result",
|
|
564
|
+
...(enabled ? { hits } : { hits: [], reason: "pi_receipts_disabled" }) });
|
|
565
|
+
}
|
|
566
|
+
if (op === "usage.rollup") {
|
|
567
|
+
// The PWA's Timeline/Usage views: the receipt journal rolled into daily
|
|
568
|
+
// buckets and per-principal spend (the raw usageRollup shape). Aggregates
|
|
569
|
+
// only and usageRollup fails closed to a zeroed result, so read scope is
|
|
570
|
+
// enough and a missing journal answers zeros, never an error.
|
|
571
|
+
const n = Number(payload.days);
|
|
572
|
+
const days = Number.isFinite(n) ? Math.min(31, Math.max(1, Math.floor(n))) : 7;
|
|
573
|
+
const rollup = usageRollup({ base: receiptJournalBase(), days });
|
|
574
|
+
log(`usage: ${m.device} roll-up ${days}d -> ${rollup.total.requests} request(s), ${rollup.total.tokens} token(s)`);
|
|
575
|
+
return void replyTo({ op: "usage.rollup.result", ...rollup });
|
|
576
|
+
}
|
|
577
|
+
if (op === "sysmon.snapshot") {
|
|
578
|
+
// READ-ONLY machine observation (sysmon.mjs): CPU/RAM per live spawn
|
|
579
|
+
// child. Roots are the registry's live panes joined with pane rows —
|
|
580
|
+
// the registry stores no pids, so roots exist only when herdr's pane
|
|
581
|
+
// list carries a pid; without pids the answer is [] plus a note, never
|
|
582
|
+
// a guess. The sampler itself fails closed to []. Subprocess-backed
|
|
583
|
+
// (one pane list), so throttled like term.*.
|
|
584
|
+
const now = Date.now();
|
|
585
|
+
const last = termThrottle.get(`sysmon:${m.device}`) ?? 0;
|
|
586
|
+
if (now - last < 1_000) return void replyTo({ op: "error", code: "busy", message: "sysmon.snapshot is throttled (1/s)" });
|
|
587
|
+
termThrottle.set(`sysmon:${m.device}`, now);
|
|
588
|
+
const panes = await paneRowsWithPids();
|
|
589
|
+
let note = null;
|
|
590
|
+
let roots = [];
|
|
591
|
+
if (panes === null) {
|
|
592
|
+
note = "herdr pane list failed — no live child could be resolved";
|
|
593
|
+
} else {
|
|
594
|
+
const withPid = liveSpawnChildren(panes).filter((row) => row.pid);
|
|
595
|
+
if (withPid.length === 0) {
|
|
596
|
+
note = panes.some((p) => Number.isInteger(Number(p.pid)) && Number(p.pid) > 0)
|
|
597
|
+
? "no live spawn child exposes a pid — nothing to sample"
|
|
598
|
+
: "herdr pane list carries no pid field — CPU/RAM roots unavailable";
|
|
599
|
+
} else {
|
|
600
|
+
roots = withPid.map((row) => ({ pid: row.pid, key: row.key }));
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const agents = sysSnapshot(roots);
|
|
604
|
+
log(`sysmon: ${m.device} snapshot -> ${agents.length} agent row(s)${note ? ` (${note})` : ""}`);
|
|
605
|
+
return void replyTo({ op: "sysmon.snapshot.result", at: new Date().toISOString(), agents, ...(note ? { note } : {}) });
|
|
606
|
+
}
|
|
607
|
+
if (op === "ports.list") {
|
|
608
|
+
// READ-ONLY listener attribution (port-attr.mjs): every LISTEN socket,
|
|
609
|
+
// attributed to the live spawn child it descends from. Without shell
|
|
610
|
+
// pids nothing can be attributed — the module answers the unattributed
|
|
611
|
+
// list and a note says why; an owner is never invented. Throttled 1/s.
|
|
612
|
+
const now = Date.now();
|
|
613
|
+
const last = termThrottle.get(`ports:${m.device}`) ?? 0;
|
|
614
|
+
if (now - last < 1_000) return void replyTo({ op: "error", code: "busy", message: "ports.list is throttled (1/s)" });
|
|
615
|
+
termThrottle.set(`ports:${m.device}`, now);
|
|
616
|
+
const panes = await paneRowsWithPids();
|
|
617
|
+
let shellPids = [];
|
|
618
|
+
let note = null;
|
|
619
|
+
if (panes === null) {
|
|
620
|
+
note = "herdr pane list failed — every listener stays unattributed";
|
|
621
|
+
} else {
|
|
622
|
+
shellPids = liveSpawnChildren(panes).filter((row) => row.pid).map((row) => ({ pid: row.pid, key: row.key }));
|
|
623
|
+
if (shellPids.length === 0) {
|
|
624
|
+
note = panes.some((p) => Number.isInteger(Number(p.pid)) && Number(p.pid) > 0)
|
|
625
|
+
? "no live spawn child exposes a pid — every listener stays unattributed"
|
|
626
|
+
: "herdr pane list carries no pid field — every listener stays unattributed";
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const { attributed, unattributed } = attributePorts(shellPids);
|
|
630
|
+
log(`ports: ${m.device} list -> ${attributed.length} attributed, ${unattributed.length} unattributed${note ? ` (${note})` : ""}`);
|
|
631
|
+
return void replyTo({ op: "ports.list.result", attributed, unattributed, ...(note ? { note } : {}) });
|
|
632
|
+
}
|
|
633
|
+
if (op === "receipt.enrich") {
|
|
634
|
+
// Experimental (opt-in HERDGATE_PI_RECEIPTS=1): transcript facts for one
|
|
635
|
+
// receipt — model, context size, turns, usage totals, last activity —
|
|
636
|
+
// parsed from the session transcript of the spawn registry record
|
|
637
|
+
// matching the receipt's sessionId (Pi's session roots as fallback).
|
|
638
|
+
// Metadata only; a missing or unreadable transcript is a clear error
|
|
639
|
+
// op, never a throw and never a guessed number.
|
|
640
|
+
const id = typeof payload.id === "string" && JOB_ID.test(payload.id) ? payload.id : "";
|
|
641
|
+
if (!receiptsEnabled()) {
|
|
642
|
+
return void replyTo({ op: "receipt.enrich.result", id: id || null, reason: "pi_receipts_disabled" });
|
|
643
|
+
}
|
|
644
|
+
if (!id) return void replyTo({ op: "error", code: "receipt.enrich", message: "receipt.enrich needs a request id" });
|
|
645
|
+
const entry = findReceipt(receiptJournalBase(), id);
|
|
646
|
+
if (!entry) {
|
|
647
|
+
log(`receipts: ${m.device} enrich ${id} -> no receipt`);
|
|
648
|
+
return void replyTo({ op: "error", code: "receipt.enrich", message: `no receipt ${id} in the journal` });
|
|
649
|
+
}
|
|
650
|
+
const file = transcriptFor(entry);
|
|
651
|
+
const parsed = file ? parsePiTranscript(file) : null;
|
|
652
|
+
if (!parsed || parsed.error) {
|
|
653
|
+
log(`receipts: ${m.device} enrich ${id} -> no transcript (session ${entry.sessionId})`);
|
|
654
|
+
return void replyTo({ op: "error", code: "receipt.enrich", message: `no readable transcript for session ${entry.sessionId}` });
|
|
655
|
+
}
|
|
656
|
+
log(`receipts: ${m.device} enrich ${id} -> ${parsed.model ?? "?"}, ${parsed.turns} turn(s), ${parsed.usageTotal.totalTokens} token(s)`);
|
|
657
|
+
return void replyTo({ op: "receipt.enrich.result", id, sessionId: entry.sessionId,
|
|
658
|
+
model: parsed.model ?? null, contextTokens: parsed.contextTokens ?? null,
|
|
659
|
+
turns: parsed.turns, usageTotal: parsed.usageTotal, lastTs: parsed.lastTs });
|
|
660
|
+
}
|
|
443
661
|
if (op === "receipt.watch" || op === "receipt.ack") {
|
|
444
662
|
// Experimental (opt-in HERDGATE_PI_RECEIPTS=1): durable per-request push
|
|
445
663
|
// subscriptions. Registering targets receipt.push at this device only;
|
|
@@ -523,6 +741,12 @@ async function publisherLoop() {
|
|
|
523
741
|
if (!prompt.trim() || prompt.length > MAX_PROMPT) {
|
|
524
742
|
return void replyTo({ op: "error", code: "bad-prompt", message: `worker.submit needs a prompt of 1..${MAX_PROMPT} chars` });
|
|
525
743
|
}
|
|
744
|
+
// Optional routing key: a NAME from the host's workspaces.json allowlist —
|
|
745
|
+
// never a raw path. Unknown names fail closed on the worker side.
|
|
746
|
+
const workspaceName = payload.workspace;
|
|
747
|
+
if (workspaceName !== undefined && (typeof workspaceName !== "string" || !WORKSPACE_NAME.test(workspaceName))) {
|
|
748
|
+
return void replyTo({ op: "error", code: "bad-workspace", message: "worker.submit workspace must be a short lowercase name" });
|
|
749
|
+
}
|
|
526
750
|
let jobs;
|
|
527
751
|
try { jobs = readJobs(file); }
|
|
528
752
|
catch (e) {
|
|
@@ -540,13 +764,55 @@ async function publisherLoop() {
|
|
|
540
764
|
return void replyTo({ op: "error", code: "queue-full", message: `worker queue is full (${MAX_PENDING} pending)` });
|
|
541
765
|
}
|
|
542
766
|
const jobId = id || randomUUID();
|
|
543
|
-
try { appendJob(file, { v: 1, id: jobId, prompt, ts: Date.now(), state: "queued"
|
|
767
|
+
try { appendJob(file, { v: 1, id: jobId, prompt, ts: Date.now(), state: "queued", principal: `device:${m.device}`,
|
|
768
|
+
...(workspaceName !== undefined ? { workspace: workspaceName } : {}) }); }
|
|
544
769
|
catch (e) {
|
|
545
770
|
return void replyTo({ op: "error", code: "worker-queue", message: `queue append failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
546
771
|
}
|
|
547
|
-
log(`worker: ${m.device} submitted ${jobId} (${prompt.length} chars)`);
|
|
772
|
+
log(`worker: ${m.device} submitted ${jobId} (${prompt.length} chars${workspaceName ? `, ws ${workspaceName}` : ""})`);
|
|
548
773
|
return void replyTo({ op: "worker.submitted", id: jobId, state: "queued", duplicate: false });
|
|
549
774
|
}
|
|
775
|
+
if (op === "attachment.upload" || op === "attachment.list") {
|
|
776
|
+
// Wave C3 — photo/file attachments from the PWA composer (the herdcats
|
|
777
|
+
// lesson: the upload lands ON THE AGENT MACHINE under the plugin's
|
|
778
|
+
// private state dir; the reply carries a path hint, and the Pi agent
|
|
779
|
+
// opens the file with its own read tool — image bytes never ride the
|
|
780
|
+
// prompt). Client names are never trusted: saveAttachment stores
|
|
781
|
+
// <uuid>.<ext> with the ext sniffed from magic bytes, inside
|
|
782
|
+
// stateDir/attachments/<yyyy-mm>/ (0700 per level, file 0600).
|
|
783
|
+
if (!D.stateDir) {
|
|
784
|
+
return void replyTo({ op: "error", code: "attachment", message: "no plugin state dir — attachments unavailable" });
|
|
785
|
+
}
|
|
786
|
+
if (op === "attachment.list") {
|
|
787
|
+
const attachments = listAttachments(D.stateDir);
|
|
788
|
+
log(`attachment: ${m.device} list -> ${attachments.length} file(s)`);
|
|
789
|
+
return void replyTo({ op: "attachment.list.result", attachments });
|
|
790
|
+
}
|
|
791
|
+
const name = typeof payload.name === "string" ? payload.name.trim() : "";
|
|
792
|
+
const dataBase64 = typeof payload.dataBase64 === "string" ? payload.dataBase64 : "";
|
|
793
|
+
if (!name || name.length > 255 || !dataBase64) {
|
|
794
|
+
return void replyTo({ op: "error", code: "attachment", message: "attachment.upload needs a name and base64 data" });
|
|
795
|
+
}
|
|
796
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(dataBase64) || dataBase64.length % 4 !== 0) {
|
|
797
|
+
log(`attachment: ${m.device} upload refused: bad base64`);
|
|
798
|
+
return void replyTo({ op: "error", code: "attachment", message: "attachment.upload data is not valid base64" });
|
|
799
|
+
}
|
|
800
|
+
let bytes;
|
|
801
|
+
try { bytes = Buffer.from(dataBase64, "base64"); }
|
|
802
|
+
catch (e) {
|
|
803
|
+
return void replyTo({ op: "error", code: "attachment", message: `attachment.upload data is not valid base64 (${e.code ?? "decode"})` });
|
|
804
|
+
}
|
|
805
|
+
try {
|
|
806
|
+
const saved = saveAttachment(D.stateDir, { name, bytes });
|
|
807
|
+
log(`attachment: ${m.device} uploaded ${name} (${bytes.length}B) -> ${saved.id}`);
|
|
808
|
+
return void replyTo({ op: "attachment.uploaded", id: saved.id, path: saved.path,
|
|
809
|
+
hint: `Please open and inspect this image: ${saved.path}` });
|
|
810
|
+
} catch (e) {
|
|
811
|
+
const why = e instanceof Error ? e.message : String(e);
|
|
812
|
+
log(`attachment: ${m.device} upload refused: ${why}`);
|
|
813
|
+
return void replyTo({ op: "error", code: "attachment", message: `attachment.upload failed: ${why}` });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
550
816
|
if (op === "view") {
|
|
551
817
|
// Answer this device now, even if the view has not changed since the last push.
|
|
552
818
|
lastSig = "";
|
|
@@ -584,6 +850,52 @@ async function publisherLoop() {
|
|
|
584
850
|
return void replyTo({ op: "error", code: "herdr", message: `read failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
585
851
|
}
|
|
586
852
|
}
|
|
853
|
+
if (op === "diff.get") {
|
|
854
|
+
// READ-ONLY code archeology: one `git show --stat --patch` of a host-local
|
|
855
|
+
// ref (hash/branch/tag) in the plugin's repo dir (HERDGATE_DIFF_REPO_DIR
|
|
856
|
+
// lets a test point elsewhere). The ref is whitelisted hard and the git
|
|
857
|
+
// call itself goes through gitRead — scrubbed env, no ext-diff/textconv,
|
|
858
|
+
// fsmonitor/hooks neutralized, no payload-chosen cwd — so hostile repo
|
|
859
|
+
// config can never execute through this op.
|
|
860
|
+
const ref = typeof payload.ref === "string" ? payload.ref : "";
|
|
861
|
+
if (!/^[A-Za-z0-9._/~^-]{1,64}$/.test(ref)) {
|
|
862
|
+
return void replyTo({ op: "error", code: "bad-ref", message: "diff.get needs a git ref of [A-Za-z0-9._/-], 1..64 chars" });
|
|
863
|
+
}
|
|
864
|
+
const repoDir = diffRepoDir();
|
|
865
|
+
try {
|
|
866
|
+
const { stdout } = await gitRead(["show", "--no-color", "--stat", "--patch", ref], repoDir, 10_000);
|
|
867
|
+
const bytes = Buffer.byteLength(stdout, "utf8");
|
|
868
|
+
const truncated = bytes > MAX_DIFF_BYTES;
|
|
869
|
+
const text = truncated ? Buffer.from(stdout, "utf8").subarray(0, MAX_DIFF_BYTES).toString("utf8") : stdout;
|
|
870
|
+
log(`diff: ${m.device} show ${ref} -> ${bytes}B${truncated ? " (capped at 128KiB)" : ""}`);
|
|
871
|
+
return void replyTo({ op: "diff.result", ref, text, bytes, truncated });
|
|
872
|
+
} catch (e) {
|
|
873
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
874
|
+
const stderr = String(e?.stderr ?? "");
|
|
875
|
+
const noRepo = /not a git repository/i.test(`${err.message}\n${stderr}`);
|
|
876
|
+
log(`diff: ${m.device} show ${ref} refused: ${err.message}`);
|
|
877
|
+
return void replyTo({ op: "error", code: noRepo ? "diff.repo" : "diff.ref",
|
|
878
|
+
message: noRepo ? "the plugin directory is not a git repository"
|
|
879
|
+
: stderr.split("\n")[0] || err.message });
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
if (op === "pane.focus") {
|
|
883
|
+
// Focus a pane on the host's Herdr. Fire-and-forget spawn, never awaited:
|
|
884
|
+
// a phone must not hang on a TUI command. argv comes from the --help probe.
|
|
885
|
+
const paneId = typeof payload.paneId === "string" ? payload.paneId : "";
|
|
886
|
+
if (!/^w\d+:p\d+$/.test(paneId)) {
|
|
887
|
+
return void replyTo({ op: "error", code: "bad-pane", message: "pane.focus needs a pane id like w0:p1" });
|
|
888
|
+
}
|
|
889
|
+
const argv = await paneFocusArgvProbe();
|
|
890
|
+
if (!argv) {
|
|
891
|
+
return void replyTo({ op: "error", code: "pane.focus", message: "this Herdr has no pane focus command" });
|
|
892
|
+
}
|
|
893
|
+
const child = spawn(D.herdrBin, [...argv, paneId], { stdio: "ignore", detached: true });
|
|
894
|
+
child.on("error", (e) => log(`pane: focus spawn failed: ${e.message}`));
|
|
895
|
+
child.unref();
|
|
896
|
+
log(`pane: ${m.device} focus ${paneId} via \`${argv.join(" ")}\``);
|
|
897
|
+
return void replyTo({ op: "pane.focused", paneId, via: argv.join(" ") });
|
|
898
|
+
}
|
|
587
899
|
return void replyTo({ op: "error", code: "read-only", message: `dev.herdgate.host has no op ${String(op)}` });
|
|
588
900
|
}
|
|
589
901
|
if (m.t === "pair.request") {
|