@pmndre/pine 0.22.0 → 0.33.0

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.
Files changed (99) hide show
  1. package/README.md +2 -1
  2. package/changes.json +265 -0
  3. package/docs/SKILL.md +31 -7
  4. package/docs/references/agents.md +245 -21
  5. package/docs/references/coding.md +1 -1
  6. package/docs/references/computer.md +1 -1
  7. package/docs/references/configuration.md +14 -5
  8. package/docs/references/mcp.md +9 -0
  9. package/docs/references/operations.md +20 -9
  10. package/docs/references/overview.md +3 -1
  11. package/docs/references/security.md +83 -24
  12. package/docs/references/setup.md +55 -9
  13. package/docs/references/source-types.md +1418 -0
  14. package/docs/references/sources.md +333 -19
  15. package/docs/references/stack.md +1 -0
  16. package/docs/references/tui.md +86 -12
  17. package/examples/home/AGENTS.md +4 -0
  18. package/examples/home/TOOLS.md +5 -0
  19. package/examples/home/agents/main/workspace/AGENTS.md +1 -1
  20. package/examples/home/agents/main/workspace/TOOLS.md +5 -0
  21. package/mcp/browser.d.ts +6 -0
  22. package/mcp/browser.js +19 -0
  23. package/mcp/render.d.ts +1 -0
  24. package/mcp/render.js +237 -0
  25. package/package.json +3 -1
  26. package/src/actions.d.ts +6 -1
  27. package/src/actions.js +17 -4
  28. package/src/admin.d.ts +4 -0
  29. package/src/admin.js +25 -6
  30. package/src/agents.d.ts +167 -2
  31. package/src/agents.js +912 -45
  32. package/src/catalogue.d.ts +60 -0
  33. package/src/catalogue.js +791 -0
  34. package/src/cli.js +10 -7
  35. package/src/config.d.ts +53 -4
  36. package/src/config.js +30 -5
  37. package/src/goals.d.ts +1 -1
  38. package/src/goals.js +14 -1
  39. package/src/manual.js +24 -2
  40. package/src/mime.d.ts +78 -0
  41. package/src/mime.js +342 -0
  42. package/src/net.d.ts +11 -0
  43. package/src/net.js +29 -2
  44. package/src/pine.js +10 -1
  45. package/src/router.js +3 -3
  46. package/src/sandbox-linux.d.ts +3 -1
  47. package/src/sandbox-linux.js +5 -0
  48. package/src/security.d.ts +22 -6
  49. package/src/security.js +44 -13
  50. package/src/slots.d.ts +106 -0
  51. package/src/slots.js +250 -0
  52. package/src/source-types.d.ts +20 -0
  53. package/src/sources/calendar.d.ts +24 -0
  54. package/src/sources/calendar.js +265 -0
  55. package/src/sources/command.js +109 -4
  56. package/src/sources/discord.d.ts +4 -0
  57. package/src/sources/discord.js +298 -0
  58. package/src/sources/feed.d.ts +19 -0
  59. package/src/sources/feed.js +257 -0
  60. package/src/sources/http.js +154 -103
  61. package/src/sources/mail.d.ts +51 -0
  62. package/src/sources/mail.js +1013 -0
  63. package/src/sources/matrix.d.ts +4 -0
  64. package/src/sources/matrix.js +232 -0
  65. package/src/sources/modbus.d.ts +15 -0
  66. package/src/sources/modbus.js +240 -0
  67. package/src/sources/onvif.d.ts +35 -0
  68. package/src/sources/onvif.js +326 -0
  69. package/src/sources/presence.d.ts +80 -0
  70. package/src/sources/presence.js +480 -0
  71. package/src/sources/serial.d.ts +21 -0
  72. package/src/sources/serial.js +220 -0
  73. package/src/sources/slack.d.ts +16 -0
  74. package/src/sources/slack.js +1062 -0
  75. package/src/sources/smtp.d.ts +4 -0
  76. package/src/sources/smtp.js +360 -0
  77. package/src/sources/stream.d.ts +68 -0
  78. package/src/sources/stream.js +534 -0
  79. package/src/sources/syslog.d.ts +32 -0
  80. package/src/sources/syslog.js +243 -0
  81. package/src/sources/system.d.ts +14 -0
  82. package/src/sources/system.js +236 -0
  83. package/src/sources/system.swift +102 -0
  84. package/src/sources/telegram.js +34 -1
  85. package/src/sources.d.ts +41 -1
  86. package/src/sources.js +147 -24
  87. package/src/tools.d.ts +1 -1
  88. package/src/tools.js +304 -23
  89. package/src/tui/app.d.ts +35 -2
  90. package/src/tui/app.js +306 -43
  91. package/src/tui/levels.d.ts +68 -0
  92. package/src/tui/levels.js +273 -0
  93. package/src/tui/picture.d.ts +17 -1
  94. package/src/tui/picture.js +72 -5
  95. package/src/types.d.ts +3 -0
  96. package/src/update.d.ts +9 -1
  97. package/src/update.js +75 -3
  98. package/src/watching.d.ts +156 -0
  99. package/src/watching.js +609 -4
@@ -0,0 +1,480 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import dgram from "node:dgram";
3
+ import dns from "node:dns";
4
+ import fs from "node:fs";
5
+ import net from "node:net";
6
+ import os from "node:os";
7
+ import { Type } from "typebox";
8
+ import { isPrivateAddress } from "../net.js";
9
+ import { parseDuration } from "../util.js";
10
+ import { clip } from "../watching.js";
11
+ /**
12
+ * Who is on the owner's own network: reports when a device joins it and when it has left.
13
+ * For "is my phone home", a TV or a console that was switched on, a printer that came online.
14
+ *
15
+ * options: { hosts?, services?, every?, away? }
16
+ * hosts the devices to look for, name → address: { "phone": "192.168.1.23", "tv": "tv.local" }
17
+ * services kinds of device that announce themselves on the network (mDNS, also called Bonjour),
18
+ * by their service type: ["_airplay._tcp", "_ipp._tcp"]. Every device of that kind counts
19
+ * every how often to look ("30s" by default)
20
+ * away how long a device must have been silent before it counts as gone ("10m" by default)
21
+ *
22
+ * event "arrived": { name, address?, service?, awayFor? } awayFor: seconds it was gone
23
+ * event "left": { name, address?, service?, lastSeen } lastSeen: when it last answered
24
+ *
25
+ * A host is there when it answers a ping, or answers a connection at all, even by refusing it.
26
+ * Only addresses on one's own network are looked for. Nothing is sent to a device beyond that
27
+ * one packet and a question to the network at large about who offers a service. The first look
28
+ * is the starting point and reports nothing.
29
+ */
30
+ const MIN = 10_000;
31
+ const GROUP = "224.0.0.251";
32
+ const MDNS = 5353;
33
+ /** Ports tried when a device does not answer a ping: one nearly nothing listens on, the web, and the one an iPhone keeps open. */
34
+ const PORTS = [7, 80, 62078];
35
+ /** The system's own Bonjour browser on a Mac. It knows what the system knows, and needs no permission of its own to listen on the network. */
36
+ const DNSSD = "/usr/bin/dns-sd";
37
+ /** How long one device is given to answer, and how long answers to a question about services are waited for. A test shortens them. */
38
+ export const timing = { probeMs: 1500, listenMs: 1200 };
39
+ /** A question "who has a PTR record for these names". `unicast` asks for the answer to be sent back to the asker alone. */
40
+ export function dnsQuery(names, unicast = false) {
41
+ const head = Buffer.alloc(12);
42
+ head.writeUInt16BE(names.length, 4);
43
+ const parts = names.map((name) => {
44
+ const labels = name.split(".").filter(Boolean).map((l) => Buffer.from(l, "utf8").subarray(0, 63));
45
+ const tail = Buffer.alloc(5);
46
+ tail.writeUInt16BE(12, 1);
47
+ tail.writeUInt16BE(unicast ? 0x8001 : 1, 3);
48
+ return Buffer.concat([...labels.flatMap((l) => [Buffer.from([l.length]), l]), tail]);
49
+ });
50
+ return Buffer.concat([head, ...parts]);
51
+ }
52
+ /**
53
+ * The records of a DNS message: answers, authority and additional ones alike. Anybody on the
54
+ * network can send one, so nothing in it is believed to be well formed: a name that points in
55
+ * circles, a length that leads out of the message or a record of an odd size ends the reading,
56
+ * and what was read until then is what comes back.
57
+ */
58
+ export function dnsRead(buf) {
59
+ const records = [];
60
+ if (buf.length < 12)
61
+ return { response: false, records };
62
+ const response = (buf[2] & 0x80) !== 0;
63
+ const name = (start) => {
64
+ const labels = [];
65
+ let at = start;
66
+ let end = -1;
67
+ let jumps = 0;
68
+ for (;;) {
69
+ if (at >= buf.length)
70
+ throw new Error("short");
71
+ const len = buf[at];
72
+ if (len === 0)
73
+ return [labels, end < 0 ? at + 1 : end];
74
+ if ((len & 0xc0) === 0xc0) {
75
+ if (at + 1 >= buf.length || ++jumps > 20)
76
+ throw new Error("loop");
77
+ if (end < 0)
78
+ end = at + 2;
79
+ at = ((len & 0x3f) << 8) | buf[at + 1];
80
+ continue;
81
+ }
82
+ if (len > 63 || at + 1 + len > buf.length || labels.length >= 20)
83
+ throw new Error("label");
84
+ labels.push(buf.toString("utf8", at + 1, at + 1 + len));
85
+ at += 1 + len;
86
+ }
87
+ };
88
+ try {
89
+ let at = 12;
90
+ for (let i = buf.readUInt16BE(4); i > 0; i--)
91
+ at = name(at)[1] + 4;
92
+ const count = Math.min(buf.readUInt16BE(6) + buf.readUInt16BE(8) + buf.readUInt16BE(10), 100);
93
+ for (let i = 0; i < count; i++) {
94
+ const [owner, next] = name(at);
95
+ if (next + 10 > buf.length)
96
+ break;
97
+ const type = buf.readUInt16BE(next);
98
+ const ttl = buf.readUInt32BE(next + 4);
99
+ const len = buf.readUInt16BE(next + 8);
100
+ const data = next + 10;
101
+ if (data + len > buf.length)
102
+ break;
103
+ const rec = { name: owner, type, ttl };
104
+ if (type === 12)
105
+ rec.ptr = name(data)[0];
106
+ else if (type === 33 && len >= 7)
107
+ rec.srv = { port: buf.readUInt16BE(data + 4), target: name(data + 6)[0] };
108
+ else if (type === 1 && len === 4)
109
+ rec.address = [...buf.subarray(data, data + 4)].join(".");
110
+ else if (type === 28 && len === 16)
111
+ rec.address = Array.from({ length: 8 }, (_, k) => buf.readUInt16BE(data + k * 2).toString(16)).join(":");
112
+ records.push(rec);
113
+ at = data + len;
114
+ }
115
+ }
116
+ catch {
117
+ // what was read until here
118
+ }
119
+ return { response, records };
120
+ }
121
+ /** A line of the system's Bonjour browser (`dns-sd -B`): a device of a kind appeared ("Add") or is gone ("Rmv"), on one network interface. */
122
+ export function browseLine(line) {
123
+ // Timestamp, A/R, Flags, if, Domain, Service Type, Instance Name (which may have spaces in it)
124
+ const m = /^\s*\d+:\d+:\d+\.\d+\s+(Add|Rmv)\s+\S+\s+(\S+)\s+\S+\s+(_\S+?)\.?\s+(.+?)\s*$/.exec(line);
125
+ return m ? { add: m[1] === "Add", iface: m[2], service: m[3].toLowerCase(), name: m[4] } : undefined;
126
+ }
127
+ /**
128
+ * Turns "it answered" and "it did not" into arrivals and departures. A device that answered is
129
+ * there. One that does not is still there until it has been silent for `awayMs`: a phone that
130
+ * sleeps answers only now and then. `quiet` is for the look that is the starting point: what is
131
+ * found is noted and nothing is reported.
132
+ */
133
+ export function tracker(awayMs, state = {}) {
134
+ const about = (k) => ({ name: k.name, ...(k.address ? { address: k.address } : {}), ...(k.service ? { service: k.service } : {}) });
135
+ return {
136
+ state,
137
+ sight(key, seen, now, quiet, info) {
138
+ const k = state[key];
139
+ if (!k) {
140
+ if (!seen && !quiet)
141
+ return undefined;
142
+ state[key] = { ...info, there: seen, ...(seen ? { last: now } : {}) };
143
+ return seen && !quiet ? { event: "arrived", payload: about(state[key]) } : undefined;
144
+ }
145
+ if (seen) {
146
+ Object.assign(k, { ...info, last: now });
147
+ if (k.there)
148
+ return undefined;
149
+ k.there = true;
150
+ const awayFor = k.left !== undefined ? Math.max(0, Math.round((now - k.left) / 1000)) : undefined;
151
+ delete k.left;
152
+ return { event: "arrived", payload: { ...about(k), ...(awayFor !== undefined ? { awayFor } : {}) } };
153
+ }
154
+ if (!k.there || now - (k.last ?? 0) < awayMs)
155
+ return undefined;
156
+ return this.gone(key);
157
+ },
158
+ /** It said goodbye, or was silent for long enough. */
159
+ gone(key) {
160
+ const k = state[key];
161
+ if (!k?.there)
162
+ return undefined;
163
+ k.there = false;
164
+ k.left = k.last;
165
+ return { event: "left", payload: { ...about(k), lastSeen: new Date(k.last ?? Date.now()).toISOString() } };
166
+ },
167
+ };
168
+ }
169
+ const first = (...files) => files.find((f) => fs.existsSync(f));
170
+ /** Whether this computer is on a local network at all. When it is not, nobody answering says nothing about who is at home. */
171
+ const onNetwork = () => Object.values(os.networkInterfaces()).some((list) => (list ?? []).some((a) => !a.internal && a.family === "IPv4" && /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(a.address)));
172
+ /** Whether anything is at this address right now: it answers a ping, or it answers a connection, be it with a no. */
173
+ export function answers(ip) {
174
+ // Never anything but an address goes to a program or a socket.
175
+ if (!net.isIP(ip))
176
+ return Promise.resolve(false);
177
+ return new Promise((resolve) => {
178
+ let open = PORTS.length + 1;
179
+ let done = false;
180
+ const socks = [];
181
+ const say = (yes) => {
182
+ if (done || (!yes && --open > 0))
183
+ return;
184
+ done = true;
185
+ clearTimeout(timer);
186
+ for (const s of socks)
187
+ s.destroy();
188
+ child?.kill("SIGKILL");
189
+ resolve(yes);
190
+ };
191
+ const timer = setTimeout(() => {
192
+ open = 1;
193
+ say(false);
194
+ }, timing.probeMs);
195
+ const v6 = net.isIPv6(ip);
196
+ const ping = v6 && process.platform === "darwin" ? first("/sbin/ping6") : first("/sbin/ping", "/bin/ping", "/usr/bin/ping", "/usr/sbin/ping");
197
+ const child = ping ? execFile(ping, ["-c", "1", "-n", ip], { timeout: timing.probeMs + 200 }, (err) => say(!err)) : undefined;
198
+ if (!child)
199
+ say(false);
200
+ for (const port of PORTS) {
201
+ const s = net.connect({ host: ip, port });
202
+ socks.push(s);
203
+ s.once("connect", () => say(true));
204
+ s.once("error", (e) => say(e.code === "ECONNREFUSED"));
205
+ }
206
+ });
207
+ }
208
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
209
+ const LOCAL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*\.local$/i;
210
+ const SERVICE = /^_[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?\._(tcp|udp)$/;
211
+ /** An address of one's own network: a private one of a single device, or a .local name. */
212
+ const own = (address) => {
213
+ if (net.isIPv4(address))
214
+ return isPrivateAddress(address) && !/^(0|22[4-9]|2[3-5]\d)\./.test(address) && !address.endsWith(".255");
215
+ if (net.isIPv6(address))
216
+ return isPrivateAddress(address) && !/^ff/i.test(address) && address !== "::";
217
+ return LOCAL.test(address);
218
+ };
219
+ function hostsOf(raw) {
220
+ if (raw === undefined || raw === null)
221
+ return [];
222
+ if (typeof raw !== "object" || Array.isArray(raw))
223
+ throw new Error('"hosts" is an object of name and address: {"phone": "192.168.1.23"}');
224
+ const list = Object.entries(raw).map(([name, a]) => ({ name, address: String(a ?? "").trim().toLowerCase() }));
225
+ if (list.length > 32)
226
+ throw new Error('"hosts" takes 32 devices at most');
227
+ for (const h of list) {
228
+ if (!NAME.test(h.name))
229
+ throw new Error(`"${h.name}" is not a usable name for a device: letters, digits, - and _`);
230
+ if (!own(h.address))
231
+ throw new Error(`${h.name}: "${h.address}" is not an address on your owner's own network. Give the device's IP address there (192.168.1.23) or its .local name; this is not for addresses on the internet (the http type looks whether one of those answers)`);
232
+ }
233
+ return list;
234
+ }
235
+ function servicesOf(raw) {
236
+ const list = (Array.isArray(raw) ? raw : raw === undefined || raw === null || raw === "" ? [] : String(raw).split(",")).map((s) => String(s).trim().toLowerCase().replace(/\.local\.?$/, "").replace(/\.$/, "")).filter(Boolean);
237
+ if (list.length > 16)
238
+ throw new Error('"services" takes 16 service types at most');
239
+ for (const s of list)
240
+ if (!SERVICE.test(s))
241
+ throw new Error(`"${s}" is not a service type. One looks like _airplay._tcp, _ipp._tcp (printers), _googlecast._tcp, _hap._tcp (HomeKit), _smb._tcp`);
242
+ return [...new Set(list)];
243
+ }
244
+ export const type = {
245
+ summary: "who is on your owner's own network: reports when a device joins it and when it has left. For a phone coming home, a TV or printer switched on",
246
+ options: Type.Object({
247
+ hosts: Type.Optional(Type.Record(Type.String(), Type.String(), { description: 'the devices to look for, as name and address on the network: {"phone": "192.168.1.23", "tv": "tv.local"}. An IP address the router always gives that device, or its .local name' })),
248
+ services: Type.Optional(Type.Array(Type.String(), { description: 'kinds of device that announce themselves on the network (Bonjour), by service type: ["_airplay._tcp", "_ipp._tcp", "_googlecast._tcp"]. Every device of that kind is reported by its own name' })),
249
+ every: Type.Optional(Type.String({ description: 'how often to look, e.g. "30s", "2m". Default "30s", at least "10s"' })),
250
+ away: Type.Optional(Type.String({ description: 'how long a device must have been silent before it counts as gone. Default "10m": a phone that sleeps answers only now and then' })),
251
+ }, { additionalProperties: false }),
252
+ plan(o) {
253
+ const hosts = hostsOf(o.hosts);
254
+ const services = servicesOf(o.services);
255
+ if (!hosts.length && !services.length)
256
+ throw new Error('needs "hosts" (devices by address: {"phone": "192.168.1.23"}) or "services" (kinds of device: ["_airplay._tcp"]), or both');
257
+ const every = o.every ?? "30s";
258
+ if (parseDuration(every) < MIN)
259
+ throw new Error('"every" must be at least "10s"');
260
+ const away = o.away ?? "10m";
261
+ if (parseDuration(away) < parseDuration(every))
262
+ throw new Error('"away" must not be shorter than "every": a device is gone when it was silent for that long');
263
+ return {
264
+ options: { ...(hosts.length ? { hosts: Object.fromEntries(hosts.map((h) => [h.name, h.address])) } : {}), ...(services.length ? { services } : {}), ...(o.every ? { every: o.every } : {}), ...(o.away ? { away: o.away } : {}) },
265
+ does: [
266
+ ...(hosts.length ? [`look every ${every} whether ${hosts.map((h) => `${h.name} (${h.address})`).join(", ")} ${hosts.length === 1 ? "is" : "are"} on your network, with one ping each`] : []),
267
+ ...(services.length ? [`ask your network every ${every} which devices offer ${services.join(", ")}`] : []),
268
+ `report a device when it joins, and when it has not answered for ${away}`,
269
+ ],
270
+ opens: true,
271
+ tell: "Who is there now is the starting point and is not reported; from then on an arrival and a departure are. The sources tool shows how many are there.",
272
+ };
273
+ },
274
+ };
275
+ export default async function presence(source) {
276
+ const o = source.options;
277
+ const hosts = hostsOf(o.hosts);
278
+ const services = servicesOf(o.services);
279
+ if (!hosts.length && !services.length)
280
+ throw new Error('needs "hosts" or "services"');
281
+ const awayMs = parseDuration(o.away ?? "10m");
282
+ const track = tracker(awayMs, source.kv.get("state") ?? {});
283
+ const text = (s, n) => clip(s.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim(), n);
284
+ const report = (c) => c && source.emit(c.event, c.payload);
285
+ // ---- devices that announce themselves --------------------------------------------------------
286
+ /** What was heard since the last look: by its full name, when, and what it is. */
287
+ const heard = new Map();
288
+ /** What the system's browser says is there right now, with the network interfaces it is seen on. */
289
+ const held = new Map();
290
+ let sock;
291
+ /** On the port every device talks on, where all of it is heard; or, if that port cannot be shared, on one of its own, with answers asked for by name. */
292
+ let shared = false;
293
+ /** The system refused to send the question to the network. */
294
+ let blocked = false;
295
+ const browsing = services.length > 0 && process.platform === "darwin" && fs.existsSync(DNSSD);
296
+ const hear = (msg, from) => {
297
+ // These announcements do not cross a router: one from elsewhere is not one.
298
+ if (!isPrivateAddress(from.address))
299
+ return;
300
+ const { response, records } = dnsRead(msg);
301
+ if (!response)
302
+ return;
303
+ for (const r of records) {
304
+ if (r.type !== 12 || !r.ptr?.length)
305
+ continue;
306
+ const service = services.find((s) => r.name.join(".").toLowerCase() === `${s}.local`);
307
+ if (!service)
308
+ continue;
309
+ const key = `service:${r.ptr.join(".").toLowerCase().slice(0, 300)}`;
310
+ if (r.ttl === 0) {
311
+ heard.delete(key);
312
+ report(track.gone(key));
313
+ continue;
314
+ }
315
+ if (heard.size >= 500 && !heard.has(key))
316
+ continue;
317
+ const srv = records.find((x) => x.srv && x.name.join(".").toLowerCase() === r.ptr.join(".").toLowerCase())?.srv;
318
+ const address = (srv && records.find((x) => x.address && net.isIPv4(x.address) && x.name.join(".").toLowerCase() === srv.target.join(".").toLowerCase())?.address) || from.address;
319
+ heard.set(key, { at: Date.now(), name: text(r.ptr[0], 100), service, address });
320
+ }
321
+ };
322
+ if (browsing) {
323
+ // One browser per kind, each started by its path with the service type (checked to be one) as its argument.
324
+ let stopped = false;
325
+ const children = new Set();
326
+ const timers = new Set();
327
+ const browse = (service, wait) => {
328
+ if (stopped)
329
+ return;
330
+ const child = spawn(DNSSD, ["-B", service, "local."], { stdio: ["ignore", "pipe", "ignore"] });
331
+ children.add(child);
332
+ let rest = "";
333
+ child.stdout.on("data", (d) => {
334
+ rest += d.toString("utf8");
335
+ const all = rest.split("\n");
336
+ rest = (all.pop() ?? "").slice(-2000);
337
+ for (const line of all) {
338
+ const b = browseLine(line);
339
+ if (!b || b.service !== service)
340
+ continue;
341
+ const key = `service:${`${b.name}.${service}.local`.toLowerCase().slice(0, 300)}`;
342
+ const h = held.get(key);
343
+ if (b.add) {
344
+ if (h)
345
+ h.ifaces.add(b.iface);
346
+ else if (held.size < 500)
347
+ held.set(key, { name: text(b.name, 100), service, ifaces: new Set([b.iface]) });
348
+ }
349
+ else if (h) {
350
+ h.ifaces.delete(b.iface);
351
+ if (h.ifaces.size)
352
+ continue;
353
+ // Gone from every interface it was seen on: the system knows it left.
354
+ held.delete(key);
355
+ report(track.gone(key));
356
+ }
357
+ }
358
+ });
359
+ child.on("error", () => { });
360
+ child.on("close", () => {
361
+ children.delete(child);
362
+ for (const [key, h] of held)
363
+ if (h.service === service)
364
+ held.delete(key);
365
+ if (stopped)
366
+ return;
367
+ const t = setTimeout(() => (timers.delete(t), browse(service, Math.min(wait * 2, 60_000))), wait);
368
+ t.unref?.();
369
+ timers.add(t);
370
+ });
371
+ };
372
+ for (const s of services)
373
+ browse(s, 2000);
374
+ source.onStop(() => {
375
+ stopped = true;
376
+ for (const t of timers)
377
+ clearTimeout(t);
378
+ for (const c of children)
379
+ c.kill("SIGKILL");
380
+ });
381
+ }
382
+ else if (services.length) {
383
+ sock = await new Promise((resolve) => {
384
+ const own = () => {
385
+ const s = dgram.createSocket("udp4");
386
+ s.bind(0, () => resolve(s));
387
+ };
388
+ const s = dgram.createSocket({ type: "udp4", reuseAddr: true });
389
+ s.once("error", () => {
390
+ s.close();
391
+ own();
392
+ });
393
+ s.bind(MDNS, () => {
394
+ try {
395
+ s.addMembership(GROUP);
396
+ s.removeAllListeners("error");
397
+ shared = true;
398
+ resolve(s);
399
+ }
400
+ catch {
401
+ s.close();
402
+ own();
403
+ }
404
+ });
405
+ });
406
+ sock.on("error", (e) => void (blocked ||= ["EHOSTUNREACH", "ENETUNREACH", "EPERM", "EACCES"].includes(e.code ?? "")));
407
+ sock.on("message", hear);
408
+ sock.unref();
409
+ source.onStop(() => void sock?.close());
410
+ }
411
+ let before = Date.now();
412
+ source.poll(o.every ?? "30s", async (signal) => {
413
+ const began = Date.now();
414
+ // The first look of all is where things stand.
415
+ const quiet = !source.kv.get("began");
416
+ const found = await Promise.all(hosts.map(async (h) => {
417
+ let ip = h.address;
418
+ if (!net.isIP(ip)) {
419
+ try {
420
+ ip = (await dns.promises.lookup(ip, { family: 4 })).address;
421
+ }
422
+ catch {
423
+ // A device that is off has no name on the network.
424
+ return { h, ip: undefined, there: false };
425
+ }
426
+ if (!isPrivateAddress(ip))
427
+ throw new Error(`${h.name}: its name leads to an address that is not on your own network`);
428
+ }
429
+ return { h, ip, there: await answers(ip) };
430
+ }));
431
+ if (sock) {
432
+ blocked = false;
433
+ const ask = dnsQuery(services.map((s) => `${s}.local`), !shared);
434
+ await new Promise((resolve) => sock.send(ask, MDNS, GROUP, (e) => (e && (blocked = true), resolve())));
435
+ }
436
+ // The system's browser says what there is as soon as it runs; the first look gives it a moment to.
437
+ if (sock || (browsing && quiet)) {
438
+ await new Promise((resolve) => {
439
+ const t = setTimeout(resolve, timing.listenMs);
440
+ signal.addEventListener("abort", () => (clearTimeout(t), resolve()), { once: true });
441
+ });
442
+ }
443
+ if (signal.aborted)
444
+ return;
445
+ // Nobody answers and this computer has no network: that says nothing about who is at home.
446
+ if (hosts.length && !found.some((f) => f.there) && !onNetwork())
447
+ throw new Error("this computer is not on a local network right now");
448
+ const now = Date.now();
449
+ for (const f of found)
450
+ report(track.sight(`host:${f.h.name}`, f.there, now, quiet || !track.state[`host:${f.h.name}`], { name: f.h.name, address: f.ip ?? (net.isIP(f.h.address) ? f.h.address : undefined) }));
451
+ // Asked, and the question never left this computer: who is there is not known, which is not the same as nobody.
452
+ const deaf = Boolean(sock) && blocked && ![...heard.values()].some((h) => h.at >= began);
453
+ if (services.length && !deaf) {
454
+ for (const key of new Set([...held.keys(), ...heard.keys(), ...Object.keys(track.state).filter((k) => k.startsWith("service:"))])) {
455
+ const h = heard.get(key);
456
+ const b = held.get(key);
457
+ const k = track.state[key];
458
+ // Held by the system's browser, or heard since the look before this one began: an announcement between two looks counts.
459
+ report(track.sight(key, Boolean(b || (h && h.at >= before)), now, quiet, b ? { name: b.name, service: b.service } : h ? { name: h.name, service: h.service, address: h.address } : { name: k.name, service: k.service, address: k.address }));
460
+ }
461
+ for (const [key, h] of heard)
462
+ if (h.at < began)
463
+ heard.delete(key);
464
+ // Devices of a kind come and go; the ones that left long ago are forgotten, the oldest first.
465
+ const gone = Object.entries(track.state).filter(([k, v]) => k.startsWith("service:") && !v.there).sort((a, b) => (a[1].last ?? 0) - (b[1].last ?? 0));
466
+ for (const [k] of gone.slice(0, Math.max(0, Object.keys(track.state).length - 200)))
467
+ delete track.state[k];
468
+ }
469
+ before = began;
470
+ source.kv.set("state", track.state);
471
+ // Where things stand is only known once the network could be asked.
472
+ if (quiet && !deaf)
473
+ source.kv.set("began", true);
474
+ const there = hosts.filter((h) => track.state[`host:${h.name}`]?.there).length;
475
+ const offered = Object.entries(track.state).filter(([k, v]) => k.startsWith("service:") && v.there).length;
476
+ source.status([hosts.length ? `${there} of ${hosts.length} there` : "", services.length ? `${offered} announced on the network` : ""].filter(Boolean).join(", "));
477
+ if (deaf)
478
+ throw new Error("the question who offers a service could not be sent to the network: this computer does not let pine onto it");
479
+ });
480
+ }
@@ -0,0 +1,21 @@
1
+ import type { SourceType } from "../source-types.ts";
2
+ import type { SourceApi } from "../sources.ts";
3
+ /** How long to wait before looking for a device again, at the start and at most. A test shortens them. */
4
+ export declare const timing: {
5
+ retryMs: number;
6
+ retryMaxMs: number;
7
+ };
8
+ /** The device a `port` option means: resolved, under /dev, there, and a serial port. Throws a sentence otherwise. */
9
+ export declare function portOf(raw: unknown): string;
10
+ export declare const type: SourceType;
11
+ /** Lines out of bytes as they arrive: split at any line end, without control characters, none longer than a line can be. */
12
+ export declare function lines(onLine: (line: string) => void): (chunk: Buffer) => void;
13
+ /**
14
+ * Listen to a serial device until `stop` is called. The device is held open by a reader that
15
+ * does nothing else (`cat`, started by its path with the device as its one argument), and its
16
+ * speed is set while it is open, since a Mac forgets the setting when the last holder lets go.
17
+ * `state` says how it stands: "listening", "waiting" (the device is not there), "unset" (the
18
+ * speed could not be set).
19
+ */
20
+ export declare function listen(file: string, baud: number, onLine: (line: string) => void, state: (now: "listening" | "waiting" | "unset") => void): () => void;
21
+ export default function serial(source: SourceApi): void;