@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.
- package/README.md +2 -1
- package/changes.json +265 -0
- package/docs/SKILL.md +31 -7
- package/docs/references/agents.md +245 -21
- package/docs/references/coding.md +1 -1
- package/docs/references/computer.md +1 -1
- package/docs/references/configuration.md +14 -5
- package/docs/references/mcp.md +9 -0
- package/docs/references/operations.md +20 -9
- package/docs/references/overview.md +3 -1
- package/docs/references/security.md +83 -24
- package/docs/references/setup.md +55 -9
- package/docs/references/source-types.md +1418 -0
- package/docs/references/sources.md +333 -19
- package/docs/references/stack.md +1 -0
- package/docs/references/tui.md +86 -12
- package/examples/home/AGENTS.md +4 -0
- package/examples/home/TOOLS.md +5 -0
- package/examples/home/agents/main/workspace/AGENTS.md +1 -1
- package/examples/home/agents/main/workspace/TOOLS.md +5 -0
- package/mcp/browser.d.ts +6 -0
- package/mcp/browser.js +19 -0
- package/mcp/render.d.ts +1 -0
- package/mcp/render.js +237 -0
- package/package.json +3 -1
- package/src/actions.d.ts +6 -1
- package/src/actions.js +17 -4
- package/src/admin.d.ts +4 -0
- package/src/admin.js +25 -6
- package/src/agents.d.ts +167 -2
- package/src/agents.js +912 -45
- package/src/catalogue.d.ts +60 -0
- package/src/catalogue.js +791 -0
- package/src/cli.js +10 -7
- package/src/config.d.ts +53 -4
- package/src/config.js +30 -5
- package/src/goals.d.ts +1 -1
- package/src/goals.js +14 -1
- package/src/manual.js +24 -2
- package/src/mime.d.ts +78 -0
- package/src/mime.js +342 -0
- package/src/net.d.ts +11 -0
- package/src/net.js +29 -2
- package/src/pine.js +10 -1
- package/src/router.js +3 -3
- package/src/sandbox-linux.d.ts +3 -1
- package/src/sandbox-linux.js +5 -0
- package/src/security.d.ts +22 -6
- package/src/security.js +44 -13
- package/src/slots.d.ts +106 -0
- package/src/slots.js +250 -0
- package/src/source-types.d.ts +20 -0
- package/src/sources/calendar.d.ts +24 -0
- package/src/sources/calendar.js +265 -0
- package/src/sources/command.js +109 -4
- package/src/sources/discord.d.ts +4 -0
- package/src/sources/discord.js +298 -0
- package/src/sources/feed.d.ts +19 -0
- package/src/sources/feed.js +257 -0
- package/src/sources/http.js +154 -103
- package/src/sources/mail.d.ts +51 -0
- package/src/sources/mail.js +1013 -0
- package/src/sources/matrix.d.ts +4 -0
- package/src/sources/matrix.js +232 -0
- package/src/sources/modbus.d.ts +15 -0
- package/src/sources/modbus.js +240 -0
- package/src/sources/onvif.d.ts +35 -0
- package/src/sources/onvif.js +326 -0
- package/src/sources/presence.d.ts +80 -0
- package/src/sources/presence.js +480 -0
- package/src/sources/serial.d.ts +21 -0
- package/src/sources/serial.js +220 -0
- package/src/sources/slack.d.ts +16 -0
- package/src/sources/slack.js +1062 -0
- package/src/sources/smtp.d.ts +4 -0
- package/src/sources/smtp.js +360 -0
- package/src/sources/stream.d.ts +68 -0
- package/src/sources/stream.js +534 -0
- package/src/sources/syslog.d.ts +32 -0
- package/src/sources/syslog.js +243 -0
- package/src/sources/system.d.ts +14 -0
- package/src/sources/system.js +236 -0
- package/src/sources/system.swift +102 -0
- package/src/sources/telegram.js +34 -1
- package/src/sources.d.ts +41 -1
- package/src/sources.js +147 -24
- package/src/tools.d.ts +1 -1
- package/src/tools.js +304 -23
- package/src/tui/app.d.ts +35 -2
- package/src/tui/app.js +306 -43
- package/src/tui/levels.d.ts +68 -0
- package/src/tui/levels.js +273 -0
- package/src/tui/picture.d.ts +17 -1
- package/src/tui/picture.js +72 -5
- package/src/types.d.ts +3 -0
- package/src/update.d.ts +9 -1
- package/src/update.js +75 -3
- package/src/watching.d.ts +156 -0
- package/src/watching.js +609 -4
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import dgram from "node:dgram";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { errText } from "../util.js";
|
|
5
|
+
import { capped, clip, pattern } from "../watching.js";
|
|
6
|
+
/**
|
|
7
|
+
* A syslog listener: takes the log lines that routers, firewalls, switches, access points and NAS
|
|
8
|
+
* boxes send when they are told a "remote log server", and reports the ones that matter.
|
|
9
|
+
*
|
|
10
|
+
* options: { port, host?, protocol?, allow?, match?, severity?, perMinute? }
|
|
11
|
+
* protocol "udp" (default), "tcp" or "both"
|
|
12
|
+
* allow only these sender addresses, as prefixes: ["192.168.1.1", "192.168.2."]
|
|
13
|
+
* match only lines in which this regular expression finds something
|
|
14
|
+
* severity the least severe level still reported (default "warning"): emerg, alert, crit,
|
|
15
|
+
* err, warning, notice, info, debug
|
|
16
|
+
* perMinute at most this many reports a minute (default 20); the rest is counted and dropped
|
|
17
|
+
*
|
|
18
|
+
* event "line": { host, app?, severity, facility, message, from, time?, dropped? }
|
|
19
|
+
*
|
|
20
|
+
* Syslog has no login: whoever can reach the port can write a line, under any host name. `from`
|
|
21
|
+
* is the address a line really came from; `host` is what the line says about itself.
|
|
22
|
+
*/
|
|
23
|
+
export const SEVERITIES = ["emerg", "alert", "crit", "err", "warning", "notice", "info", "debug"];
|
|
24
|
+
const FACILITIES = ["kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp", "cron", "authpriv", "ftp", "ntp", "audit", "alert", "clock", "local0", "local1", "local2", "local3", "local4", "local5", "local6", "local7"];
|
|
25
|
+
const ALIASES = { emergency: "emerg", panic: "emerg", critical: "crit", error: "err", warn: "warning", information: "info", informational: "info" };
|
|
26
|
+
const LINE_MAX = 8192;
|
|
27
|
+
/** A name a line gave (a host, a program): one word of sensible length, or nothing. */
|
|
28
|
+
const word = (s, max) => {
|
|
29
|
+
const w = (s ?? "").replace(/[\x00-\x20\x7f]+/g, "");
|
|
30
|
+
return w && w !== "-" ? w.slice(0, max) : undefined;
|
|
31
|
+
};
|
|
32
|
+
/** Read one syslog line: the newer format (RFC 5424), the older one (RFC 3164), or whatever else it is. */
|
|
33
|
+
export function parseLine(raw) {
|
|
34
|
+
const line = raw.replace(/[\r\n\x00]+$/g, "").slice(0, LINE_MAX);
|
|
35
|
+
const pri = /^<(\d{1,3})>/.exec(line);
|
|
36
|
+
if (!pri || Number(pri[1]) > 191)
|
|
37
|
+
return { severity: "notice", facility: "user", message: line.trim() };
|
|
38
|
+
const n = Number(pri[1]);
|
|
39
|
+
const base = { severity: SEVERITIES[n & 7], facility: FACILITIES[n >> 3] ?? "user" };
|
|
40
|
+
const rest = line.slice(pri[0].length);
|
|
41
|
+
// RFC 5424: version, time, host, program, process, message id, structured data, text.
|
|
42
|
+
const v1 = /^1 (\S+) (\S+) (\S+) (\S+) (\S+) /.exec(rest);
|
|
43
|
+
if (v1) {
|
|
44
|
+
let text = rest.slice(v1[0].length);
|
|
45
|
+
if (text.startsWith("[")) {
|
|
46
|
+
// Structured data: elements in brackets, a bracket inside a value written as \].
|
|
47
|
+
let i = 0;
|
|
48
|
+
while (text[i] === "[") {
|
|
49
|
+
i++;
|
|
50
|
+
while (i < text.length && text[i] !== "]")
|
|
51
|
+
i += text[i] === "\\" ? 2 : 1;
|
|
52
|
+
i++;
|
|
53
|
+
}
|
|
54
|
+
text = text.slice(i);
|
|
55
|
+
}
|
|
56
|
+
else if (text.startsWith("-"))
|
|
57
|
+
text = text.slice(1);
|
|
58
|
+
const when = v1[1] === "-" ? undefined : new Date(v1[1]);
|
|
59
|
+
return { ...base, host: word(v1[2], 100), app: word(v1[3], 64), message: text.replace(/^ /, "").replace(/^\ufeff|^\xef\xbb\xbf/, "").trim(), ...(when && Number.isFinite(when.getTime()) ? { time: when.toISOString() } : {}) };
|
|
60
|
+
}
|
|
61
|
+
// RFC 3164: "Oct 11 22:14:15 host program[123]: text". Many devices leave out the time, the host or both.
|
|
62
|
+
const stamped = /^([A-Z][a-z]{2} [ \d]\d \d\d:\d\d:\d\d) /.exec(rest);
|
|
63
|
+
let text = stamped ? rest.slice(stamped[0].length) : rest;
|
|
64
|
+
let host;
|
|
65
|
+
const tagged = (s) => /^([^\s:[\]]{1,48})(?:\[\d+\])?: ?/.exec(s);
|
|
66
|
+
if (stamped && !tagged(text)) {
|
|
67
|
+
const m = /^(\S+) /.exec(text);
|
|
68
|
+
if (m) {
|
|
69
|
+
host = word(m[1], 100);
|
|
70
|
+
text = text.slice(m[0].length);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const tag = tagged(text);
|
|
74
|
+
if (tag)
|
|
75
|
+
text = text.slice(tag[0].length);
|
|
76
|
+
return { ...base, ...(host ? { host } : {}), ...(tag ? { app: word(tag[1], 64) } : {}), message: text.trim() };
|
|
77
|
+
}
|
|
78
|
+
const level = (v) => {
|
|
79
|
+
const name = String(v ?? "warning").trim().toLowerCase();
|
|
80
|
+
return SEVERITIES.indexOf(ALIASES[name] ?? name);
|
|
81
|
+
};
|
|
82
|
+
export const type = {
|
|
83
|
+
summary: "a syslog listener: the log lines a router, firewall, switch, access point or NAS sends to a \"remote log server\"; reports those that are severe enough or match",
|
|
84
|
+
options: Type.Object({
|
|
85
|
+
port: Type.Number({ description: "port to listen on, e.g. 5514 (514 is the usual one, which on many systems only root may open)" }),
|
|
86
|
+
host: Type.Optional(Type.String({ description: 'address to listen on. Default "0.0.0.0", so that devices on the network reach it' })),
|
|
87
|
+
protocol: Type.Optional(Type.String({ description: '"udp" (default, what most devices send), "tcp" or "both"' })),
|
|
88
|
+
allow: Type.Optional(Type.Array(Type.String(), { description: 'only these sender addresses, as prefixes: ["192.168.1.1", "192.168.2."]. Give the device\'s address: syslog has no login' })),
|
|
89
|
+
match: Type.Optional(Type.String({ description: 'only lines in which this regular expression finds something, e.g. "link down|login failed"' })),
|
|
90
|
+
severity: Type.Optional(Type.String({ description: 'the least severe level still reported: emerg, alert, crit, err, warning, notice, info or debug. Default "warning"' })),
|
|
91
|
+
perMinute: Type.Optional(Type.Number({ description: "at most this many reports a minute; what comes on top is counted and dropped. Default 20" })),
|
|
92
|
+
}, { additionalProperties: false }),
|
|
93
|
+
plan(o) {
|
|
94
|
+
if (!Number.isInteger(o.port) || o.port < 1 || o.port > 65535)
|
|
95
|
+
throw new Error(`"port" must be a port number, for example 5514`);
|
|
96
|
+
const protocol = String(o.protocol ?? "udp").toLowerCase();
|
|
97
|
+
if (!["udp", "tcp", "both"].includes(protocol))
|
|
98
|
+
throw new Error('"protocol" is "udp", "tcp" or "both"');
|
|
99
|
+
const floor = level(o.severity);
|
|
100
|
+
if (floor < 0)
|
|
101
|
+
throw new Error(`"severity" is one of ${SEVERITIES.join(", ")}`);
|
|
102
|
+
if (o.match !== undefined)
|
|
103
|
+
pattern(String(o.match));
|
|
104
|
+
if (o.perMinute !== undefined && !(Number.isInteger(o.perMinute) && o.perMinute >= 1 && o.perMinute <= 600))
|
|
105
|
+
throw new Error('"perMinute" is a whole number from 1 to 600');
|
|
106
|
+
const allow = (Array.isArray(o.allow) ? o.allow : []).map((a) => String(a).trim()).filter(Boolean);
|
|
107
|
+
for (const a of allow)
|
|
108
|
+
if (!/^[0-9a-fA-F.:]+$/.test(a))
|
|
109
|
+
throw new Error(`"${a}" in "allow" is not an address or the beginning of one. It looks like "192.168.1.1" or "192.168.2."`);
|
|
110
|
+
const options = { ...o, protocol, severity: SEVERITIES[floor] };
|
|
111
|
+
if (allow.length)
|
|
112
|
+
options.allow = allow;
|
|
113
|
+
else
|
|
114
|
+
delete options.allow;
|
|
115
|
+
return {
|
|
116
|
+
options,
|
|
117
|
+
does: [
|
|
118
|
+
`listen on port ${o.port} (${protocol === "both" ? "UDP and TCP" : protocol.toUpperCase()}) of this computer for the log lines devices send (syslog)${allow.length ? `, from the addresses ${allow.join(", ")}` : ""}, and report those of severity "${SEVERITIES[floor]}" or worse${o.match ? ` in which /${o.match}/ finds something` : ""}`,
|
|
119
|
+
...(allow.length ? [] : ['take lines from ANYONE who can reach the port, under any name: syslog has no login. "allow" with the device\'s address narrows it']),
|
|
120
|
+
`report at most ${o.perMinute ?? 20} lines a minute; what comes on top is counted and dropped`,
|
|
121
|
+
],
|
|
122
|
+
opens: true,
|
|
123
|
+
tell: `In the device, enter this computer's address as the remote log (syslog) server, port ${o.port}, protocol ${protocol === "tcp" ? "TCP" : "UDP"}.`,
|
|
124
|
+
};
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
export default async function syslog(source) {
|
|
128
|
+
const o = source.options;
|
|
129
|
+
const port = Number(o.port);
|
|
130
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
131
|
+
throw new Error(`needs "port" (for example 5514)`);
|
|
132
|
+
const host = String(o.host ?? "0.0.0.0");
|
|
133
|
+
const protocol = String(o.protocol ?? "udp");
|
|
134
|
+
const allow = (Array.isArray(o.allow) ? o.allow : []).map(String);
|
|
135
|
+
const floor = Math.max(0, level(o.severity));
|
|
136
|
+
const re = o.match ? pattern(String(o.match)) : undefined;
|
|
137
|
+
const perMinute = Number(o.perMinute ?? 20);
|
|
138
|
+
const cap = capped(perMinute);
|
|
139
|
+
const plain = (addr) => (addr ?? "").replace(/^::ffff:/, "");
|
|
140
|
+
const allowed = (remote) => !allow.length || allow.some((a) => remote === a || (/[.:]$/.test(a) && remote.startsWith(a)));
|
|
141
|
+
let reported = 0;
|
|
142
|
+
let quiet = 0;
|
|
143
|
+
let over = 0;
|
|
144
|
+
let turned = 0;
|
|
145
|
+
const say = () => source.status(`listening on port ${port} (${protocol}). ${reported} reported, ${quiet} not severe enough or not matching${over ? `, ${over} over the limit of ${perMinute} a minute` : ""}${turned ? `, ${turned} from addresses not allowed` : ""}`);
|
|
146
|
+
source.status(`listening on port ${port} (${protocol})`);
|
|
147
|
+
const take = (raw, remote) => {
|
|
148
|
+
if (!raw.trim())
|
|
149
|
+
return;
|
|
150
|
+
const line = parseLine(raw);
|
|
151
|
+
if (SEVERITIES.indexOf(line.severity) > floor || (re && !re.test(line.message))) {
|
|
152
|
+
quiet++;
|
|
153
|
+
return say();
|
|
154
|
+
}
|
|
155
|
+
if (!cap.ok()) {
|
|
156
|
+
over++;
|
|
157
|
+
return say();
|
|
158
|
+
}
|
|
159
|
+
const dropped = cap.dropped();
|
|
160
|
+
reported++;
|
|
161
|
+
say();
|
|
162
|
+
try {
|
|
163
|
+
source.emit("line", { host: line.host ?? remote, ...(line.app ? { app: line.app } : {}), severity: line.severity, facility: line.facility, message: clip(line.message, 2000), from: remote, ...(line.time ? { time: line.time } : {}), ...(dropped ? { dropped } : {}) });
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
source.log.warn("could not report a line", errText(e));
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
const hint = (e) => new Error(`could not listen on port ${port}: ${errText(e)}${port < 1024 ? ". Ports below 1024 often need root: use 5514 and enter that port in the device" : ""}`);
|
|
170
|
+
if (protocol === "udp" || protocol === "both") {
|
|
171
|
+
const socket = dgram.createSocket({ type: net.isIPv6(host) ? "udp6" : "udp4", reuseAddr: false });
|
|
172
|
+
socket.on("message", (msg, info) => {
|
|
173
|
+
const remote = plain(info.address);
|
|
174
|
+
if (!allowed(remote))
|
|
175
|
+
return void (turned++, say());
|
|
176
|
+
// One line a packet is the rule; a device that puts several into one is read all the same.
|
|
177
|
+
for (const raw of msg.subarray(0, LINE_MAX * 4).toString("utf8").split("\n").slice(0, 20))
|
|
178
|
+
take(raw, remote);
|
|
179
|
+
});
|
|
180
|
+
await new Promise((resolve, reject) => {
|
|
181
|
+
socket.once("error", (e) => reject(hint(e)));
|
|
182
|
+
socket.bind(port, host, () => {
|
|
183
|
+
socket.removeAllListeners("error");
|
|
184
|
+
socket.on("error", (e) => source.log.warn("syslog socket error", errText(e)));
|
|
185
|
+
resolve();
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
source.onStop(() => new Promise((resolve) => socket.close(() => resolve())));
|
|
189
|
+
}
|
|
190
|
+
if (protocol === "tcp" || protocol === "both") {
|
|
191
|
+
const open = new Set();
|
|
192
|
+
const server = net.createServer((sock) => {
|
|
193
|
+
const remote = plain(sock.remoteAddress);
|
|
194
|
+
if (open.size >= 20 || !allowed(remote)) {
|
|
195
|
+
turned++;
|
|
196
|
+
say();
|
|
197
|
+
return void sock.destroy();
|
|
198
|
+
}
|
|
199
|
+
open.add(sock);
|
|
200
|
+
// A device keeps its connection open and may have nothing to say for a long time.
|
|
201
|
+
sock.setTimeout(3_600_000, () => sock.destroy());
|
|
202
|
+
sock.setKeepAlive(true, 60_000);
|
|
203
|
+
sock.on("close", () => open.delete(sock));
|
|
204
|
+
sock.on("error", () => { });
|
|
205
|
+
let buffer = Buffer.alloc(0);
|
|
206
|
+
sock.on("data", (chunk) => {
|
|
207
|
+
buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk;
|
|
208
|
+
for (;;) {
|
|
209
|
+
// Either a line ends with a line break, or its length stands in front of it ("83 <34>1 ...").
|
|
210
|
+
const counted = /^(\d{1,5}) (?=<)/.exec(buffer.subarray(0, 8).toString("latin1"));
|
|
211
|
+
if (counted) {
|
|
212
|
+
const n = Number(counted[1]);
|
|
213
|
+
if (n > LINE_MAX * 4)
|
|
214
|
+
return void sock.destroy();
|
|
215
|
+
if (buffer.length < counted[0].length + n)
|
|
216
|
+
return;
|
|
217
|
+
take(buffer.subarray(counted[0].length, counted[0].length + n).toString("utf8"), remote);
|
|
218
|
+
buffer = buffer.subarray(counted[0].length + n);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const i = buffer.indexOf("\n");
|
|
222
|
+
if (i < 0) {
|
|
223
|
+
if (buffer.length > LINE_MAX * 4)
|
|
224
|
+
sock.destroy();
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
take(buffer.subarray(0, i).toString("utf8"), remote);
|
|
228
|
+
buffer = buffer.subarray(i + 1);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
await new Promise((resolve, reject) => {
|
|
233
|
+
server.once("error", (e) => reject(hint(e)));
|
|
234
|
+
server.listen(port, host, () => (server.removeAllListeners("error"), resolve()));
|
|
235
|
+
});
|
|
236
|
+
source.onStop(() => new Promise((resolve) => {
|
|
237
|
+
for (const s of open)
|
|
238
|
+
s.destroy();
|
|
239
|
+
server.close(() => resolve());
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
source.log.info(`listening for syslog on ${host}:${port} (${protocol})`);
|
|
243
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SourceType } from "../source-types.ts";
|
|
2
|
+
import type { SourceApi } from "../sources.ts";
|
|
3
|
+
/**
|
|
4
|
+
* For tests: a program that writes the helper's lines, in place of the one built from
|
|
5
|
+
* system.swift, so that the type can be tried on any system. Not an option of the source: a
|
|
6
|
+
* source's options are what an agent may set, and which program the daemon runs is not among them.
|
|
7
|
+
*/
|
|
8
|
+
export declare const standIn: {
|
|
9
|
+
program?: string[];
|
|
10
|
+
};
|
|
11
|
+
export declare const type: SourceType;
|
|
12
|
+
/** The helper as a program: built from its source the first time, then found again by the source's hash. */
|
|
13
|
+
export declare function buildHelper(dir: string, source?: string): Promise<string>;
|
|
14
|
+
export default function system(source: SourceApi): Promise<void>;
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import { errText } from "../util.js";
|
|
7
|
+
import { clip } from "../watching.js";
|
|
8
|
+
/**
|
|
9
|
+
* This computer: reports when it goes to sleep and wakes, when its screen is locked and unlocked,
|
|
10
|
+
* when it changes between mains and battery, when its network comes and goes, when a disk is
|
|
11
|
+
* plugged in or taken out, and when an app the owner named starts or quits.
|
|
12
|
+
*
|
|
13
|
+
* options: { watch?, apps?, battery? }
|
|
14
|
+
* watch what to report: "sleep", "lock", "power", "network", "volumes" (all five by default)
|
|
15
|
+
* apps apps whose start and end are reported, by name or bundle id: ["Xcode", "us.zoom.xos"]
|
|
16
|
+
* battery report "battery-low" once when the charge falls to this many percent on battery (20)
|
|
17
|
+
*
|
|
18
|
+
* events: "sleeping", "woke", "display-off", "display-on", "locked", "unlocked" {}
|
|
19
|
+
* "power" { on: "ac" | "battery" | "ups", percent? } when the supply changes
|
|
20
|
+
* "battery-low" { percent }
|
|
21
|
+
* "network" { online, via? } when it changes
|
|
22
|
+
* "mounted", "unmounted" { name, path? }
|
|
23
|
+
* "app-started", "app-quit" { app, bundle? }
|
|
24
|
+
*
|
|
25
|
+
* macOS only so far. The system tells a small helper (system.swift), which pine builds with
|
|
26
|
+
* swiftc the first time and keeps in the source's own folder, where no agent can write. The
|
|
27
|
+
* helper only repeats what the system says; what becomes an event is decided here.
|
|
28
|
+
*/
|
|
29
|
+
const KINDS = ["sleep", "lock", "power", "network", "volumes"];
|
|
30
|
+
const SWIFT = path.join(import.meta.dirname, "system.swift");
|
|
31
|
+
/** After the helper ended, the pause before it is started again; longer with each end in a row. */
|
|
32
|
+
const AGAIN = [500, 2000, 10_000, 60_000, 300_000];
|
|
33
|
+
/**
|
|
34
|
+
* For tests: a program that writes the helper's lines, in place of the one built from
|
|
35
|
+
* system.swift, so that the type can be tried on any system. Not an option of the source: a
|
|
36
|
+
* source's options are what an agent may set, and which program the daemon runs is not among them.
|
|
37
|
+
*/
|
|
38
|
+
export const standIn = {};
|
|
39
|
+
const NOT_HERE = "the system source works on a Mac only so far: it listens to what macOS says about sleep, the lock, power, the network and disks";
|
|
40
|
+
const NO_COMPILER = "it needs Apple's command line developer tools, once, to build its helper, and they are not installed on this Mac. Your owner installs them by typing this into a terminal: xcode-select --install. Then subscribe again";
|
|
41
|
+
const here = () => process.platform === "darwin" || Boolean(standIn.program);
|
|
42
|
+
export const type = {
|
|
43
|
+
summary: "this computer (a Mac): reports sleep and wake, the screen lock, mains or battery, the network coming and going, disks plugged in, and apps you name starting or quitting",
|
|
44
|
+
options: Type.Object({
|
|
45
|
+
watch: Type.Optional(Type.Array(Type.String(), { description: 'what to report, any of "sleep" (sleeping, woke, display-off, display-on), "lock" (locked, unlocked), "power" (power, battery-low), "network", "volumes" (mounted, unmounted). Default: all five' })),
|
|
46
|
+
apps: Type.Optional(Type.Array(Type.String(), { description: 'apps whose start and end are reported (app-started, app-quit), by name or bundle id, e.g. ["Xcode", "us.zoom.xos"]. Without it no app is reported' })),
|
|
47
|
+
battery: Type.Optional(Type.Number({ description: 'report "battery-low" once when the charge falls to this many percent while on battery. Default 20' })),
|
|
48
|
+
}, { additionalProperties: false }),
|
|
49
|
+
plan(o) {
|
|
50
|
+
if (!here())
|
|
51
|
+
throw new Error(NOT_HERE);
|
|
52
|
+
const watch = [...new Set((o.watch ?? KINDS).map((k) => String(k).trim().toLowerCase()))];
|
|
53
|
+
const unknown = watch.filter((k) => !KINDS.includes(k));
|
|
54
|
+
if (unknown.length)
|
|
55
|
+
throw new Error(`"watch" takes ${KINDS.join(", ")}, not ${unknown.join(", ")}. Apps go into "apps", by name`);
|
|
56
|
+
const apps = (o.apps ?? []).map((a) => String(a).trim()).filter(Boolean);
|
|
57
|
+
if (apps.length > 30 || apps.some((a) => a.length > 100))
|
|
58
|
+
throw new Error('"apps" is a list of at most 30 names');
|
|
59
|
+
if (!watch.length && !apps.length)
|
|
60
|
+
throw new Error(`there is nothing to report: name something in "watch" (${KINDS.join(", ")}) or in "apps"`);
|
|
61
|
+
if (o.battery !== undefined && !(o.battery >= 1 && o.battery <= 99))
|
|
62
|
+
throw new Error('"battery" is a percentage from 1 to 99');
|
|
63
|
+
const says = { sleep: "goes to sleep and wakes", lock: "is locked and unlocked", power: "changes between mains and battery, or runs low", network: "loses or gets its network", volumes: "gets a disk plugged in or taken out" };
|
|
64
|
+
return {
|
|
65
|
+
options: { ...(o.watch ? { watch } : {}), ...(apps.length ? { apps } : {}), ...(o.battery !== undefined ? { battery: o.battery } : {}) },
|
|
66
|
+
does: [`report when this computer ${watch.map((k) => says[k]).join(", ") || "starts or quits one of the apps below"}`, ...(apps.length ? [`report when ${apps.join(", ")} ${apps.length === 1 ? "starts or quits" : "start or quit"}`] : []), "build a small helper program the first time, which listens to the system and nothing else"],
|
|
67
|
+
opens: true,
|
|
68
|
+
tell: "It reports from now on. How things are right now (on mains or battery, online or not) is the starting point and is not reported.",
|
|
69
|
+
};
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
const run = (file, args, ms) => new Promise((resolve) => {
|
|
73
|
+
execFile(file, args, { timeout: ms, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => resolve({ code: err ? (typeof err.code === "number" ? err.code : 1) : 0, stdout: String(stdout), stderr: String(stderr) }));
|
|
74
|
+
});
|
|
75
|
+
/** The helper as a program: built from its source the first time, then found again by the source's hash. */
|
|
76
|
+
export async function buildHelper(dir, source = SWIFT) {
|
|
77
|
+
const file = path.join(dir, `pine-system-${createHash("sha256").update(fs.readFileSync(source)).digest("hex").slice(0, 12)}`);
|
|
78
|
+
if (fs.existsSync(file))
|
|
79
|
+
return file;
|
|
80
|
+
// /usr/bin/swiftc exists on every Mac, but without the tools it only opens a window that offers to install them.
|
|
81
|
+
const tools = await run("/usr/bin/xcode-select", ["-p"], 10_000);
|
|
82
|
+
if (tools.code !== 0 || !fs.existsSync(tools.stdout.trim()))
|
|
83
|
+
throw new Error(NO_COMPILER);
|
|
84
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
85
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
86
|
+
const built = await run("/usr/bin/swiftc", ["-swift-version", "5", "-O", "-o", tmp, source], 300_000);
|
|
87
|
+
if (built.code !== 0 || !fs.existsSync(tmp)) {
|
|
88
|
+
fs.rmSync(tmp, { force: true });
|
|
89
|
+
const why = built.stderr.split("\n").filter((l) => /error/i.test(l)).slice(0, 3).join(" | ") || built.stderr.trim().split("\n").slice(-2).join(" | ");
|
|
90
|
+
throw new Error(`its helper could not be built (${why.slice(0, 400) || "the compiler gave no reason"}). Apple's command line developer tools may need an update: xcode-select --install, or Software Update`);
|
|
91
|
+
}
|
|
92
|
+
fs.renameSync(tmp, file);
|
|
93
|
+
for (const old of fs.readdirSync(dir))
|
|
94
|
+
if (old.startsWith("pine-system-") && path.join(dir, old) !== file && !old.includes(".tmp"))
|
|
95
|
+
fs.rmSync(path.join(dir, old), { force: true });
|
|
96
|
+
return file;
|
|
97
|
+
}
|
|
98
|
+
/** A name the system gave (a disk, an app) as an event carries it: one line, no control characters, not long. */
|
|
99
|
+
const name = (v) => clip(String(v ?? "").replace(/[\x00-\x1f\x7f]+/g, " ").trim(), 120);
|
|
100
|
+
const clock = () => new Date().toTimeString().slice(0, 8);
|
|
101
|
+
export default async function system(source) {
|
|
102
|
+
if (!here())
|
|
103
|
+
throw new Error(NOT_HERE);
|
|
104
|
+
const o = source.options;
|
|
105
|
+
const watch = (Array.isArray(o.watch) ? o.watch : KINDS).map(String).filter((k) => KINDS.includes(k));
|
|
106
|
+
const apps = (Array.isArray(o.apps) ? o.apps : []).map((a) => String(a).trim().toLowerCase()).filter(Boolean);
|
|
107
|
+
const low = Number(o.battery ?? 20);
|
|
108
|
+
const kinds = [...watch, ...(apps.length ? ["apps"] : [])];
|
|
109
|
+
if (!kinds.length)
|
|
110
|
+
throw new Error('there is nothing to report: name something in "watch" or in "apps"');
|
|
111
|
+
// A wrong set-up (no compiler) is found out here, and shows as the reason the source is not running.
|
|
112
|
+
const program = standIn.program ?? [await buildHelper(path.join(source.dataDir, "helper"))];
|
|
113
|
+
const stop = new AbortController();
|
|
114
|
+
let supply = "";
|
|
115
|
+
const said = () => source.status(`listening since ${since}${supply ? `, on ${supply}` : ""}`);
|
|
116
|
+
let since = clock();
|
|
117
|
+
const line = (text) => {
|
|
118
|
+
let m;
|
|
119
|
+
try {
|
|
120
|
+
m = JSON.parse(text);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (!m || typeof m !== "object" || typeof m.event !== "string")
|
|
126
|
+
return;
|
|
127
|
+
switch (m.event) {
|
|
128
|
+
case "sleeping":
|
|
129
|
+
case "woke":
|
|
130
|
+
case "display-off":
|
|
131
|
+
case "display-on":
|
|
132
|
+
if (watch.includes("sleep"))
|
|
133
|
+
source.emit(m.event);
|
|
134
|
+
return;
|
|
135
|
+
case "locked":
|
|
136
|
+
case "unlocked":
|
|
137
|
+
if (watch.includes("lock"))
|
|
138
|
+
source.emit(m.event);
|
|
139
|
+
return;
|
|
140
|
+
case "power": {
|
|
141
|
+
if (!watch.includes("power"))
|
|
142
|
+
return;
|
|
143
|
+
const on = ["ac", "battery", "ups"].includes(m.on) ? String(m.on) : "ac";
|
|
144
|
+
const percent = Number.isFinite(m.percent) ? Math.max(0, Math.min(100, Math.round(m.percent))) : undefined;
|
|
145
|
+
supply = on === "ac" ? "mains" : on;
|
|
146
|
+
said();
|
|
147
|
+
// The supply is what counts as a change: the charge moves all day.
|
|
148
|
+
if (source.changed(on, "power"))
|
|
149
|
+
source.emit("power", { on, ...(percent !== undefined ? { percent } : {}) });
|
|
150
|
+
// Low once per discharge: said again only after it was charged or well above the mark.
|
|
151
|
+
if (percent === undefined)
|
|
152
|
+
return;
|
|
153
|
+
const warned = source.kv.get("low") === true;
|
|
154
|
+
if (on === "battery" && percent <= low && !warned) {
|
|
155
|
+
source.kv.set("low", true);
|
|
156
|
+
source.emit("battery-low", { percent });
|
|
157
|
+
}
|
|
158
|
+
else if (warned && (on !== "battery" || percent > low + 5))
|
|
159
|
+
source.kv.set("low", false);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
case "network": {
|
|
163
|
+
if (!watch.includes("network"))
|
|
164
|
+
return;
|
|
165
|
+
const now = m.online === true ? { online: true, via: ["wifi", "ethernet", "cellular"].includes(m.via) ? String(m.via) : "other" } : { online: false };
|
|
166
|
+
if (source.changed(now, "network"))
|
|
167
|
+
source.emit("network", now);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
case "mounted":
|
|
171
|
+
case "unmounted":
|
|
172
|
+
if (watch.includes("volumes") && m.name)
|
|
173
|
+
source.emit(m.event, { name: name(m.name), ...(m.path ? { path: name(m.path) } : {}) });
|
|
174
|
+
return;
|
|
175
|
+
case "app-started":
|
|
176
|
+
case "app-quit": {
|
|
177
|
+
const app = name(m.app);
|
|
178
|
+
const bundle = name(m.bundle);
|
|
179
|
+
if (apps.includes(app.toLowerCase()) || (bundle && apps.includes(bundle.toLowerCase())))
|
|
180
|
+
source.emit(m.event, { app, ...(bundle ? { bundle } : {}) });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
const once = () => new Promise((resolve) => {
|
|
186
|
+
// Without the daemon's environment: the helper needs none of it.
|
|
187
|
+
const child = spawn(program[0], [...program.slice(1), ...kinds], { stdio: ["pipe", "pipe", "ignore"], env: {} });
|
|
188
|
+
const end = () => {
|
|
189
|
+
child.stdin.end();
|
|
190
|
+
child.kill();
|
|
191
|
+
};
|
|
192
|
+
stop.signal.addEventListener("abort", end, { once: true });
|
|
193
|
+
let rest = "";
|
|
194
|
+
child.stdout.on("data", (d) => {
|
|
195
|
+
rest += d.toString("utf8");
|
|
196
|
+
for (let at = rest.indexOf("\n"); at >= 0; at = rest.indexOf("\n")) {
|
|
197
|
+
const text = rest.slice(0, at);
|
|
198
|
+
rest = rest.slice(at + 1);
|
|
199
|
+
try {
|
|
200
|
+
line(text);
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
source.log.warn("could not take a line of the helper", errText(e));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (rest.length > 64 * 1024)
|
|
207
|
+
rest = "";
|
|
208
|
+
});
|
|
209
|
+
child.stdin.on("error", () => { });
|
|
210
|
+
child.on("error", (e) => source.log.warn("the helper could not be started", errText(e)));
|
|
211
|
+
child.on("close", () => {
|
|
212
|
+
stop.signal.removeEventListener("abort", end);
|
|
213
|
+
resolve();
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
source.onStop(() => stop.abort());
|
|
217
|
+
said();
|
|
218
|
+
void (async () => {
|
|
219
|
+
let fails = 0;
|
|
220
|
+
while (!stop.signal.aborted) {
|
|
221
|
+
const from = Date.now();
|
|
222
|
+
since = clock();
|
|
223
|
+
said();
|
|
224
|
+
await once();
|
|
225
|
+
if (stop.signal.aborted)
|
|
226
|
+
return;
|
|
227
|
+
fails = Date.now() - from < 10_000 ? fails + 1 : 0;
|
|
228
|
+
source.status(`its helper ended at ${clock()}, starting it again`);
|
|
229
|
+
await new Promise((r) => {
|
|
230
|
+
const done = () => (clearTimeout(t), stop.signal.removeEventListener("abort", done), r());
|
|
231
|
+
const t = setTimeout(done, AGAIN[Math.min(fails, AGAIN.length - 1)]);
|
|
232
|
+
stop.signal.addEventListener("abort", done, { once: true });
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
})();
|
|
236
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// pine's helper for the "system" event source: it says what this Mac does (sleep and wake, the
|
|
2
|
+
// screen lock, power, the network, disks, apps), one JSON object per line on standard output.
|
|
3
|
+
// It decides nothing: which of these become events, and for whom, is system.ts's business.
|
|
4
|
+
// Its arguments name what to listen for; it ends when its input is closed.
|
|
5
|
+
//
|
|
6
|
+
// Built by pine with swiftc on first use (src/sources/system.ts), like the other helpers.
|
|
7
|
+
import AppKit
|
|
8
|
+
import Foundation
|
|
9
|
+
import IOKit.ps
|
|
10
|
+
import Network
|
|
11
|
+
|
|
12
|
+
func say(_ event: String, _ fields: [String: Any] = [:]) {
|
|
13
|
+
var object = fields
|
|
14
|
+
object["event"] = event
|
|
15
|
+
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), let line = String(data: data, encoding: .utf8) else { return }
|
|
16
|
+
print(line)
|
|
17
|
+
fflush(stdout)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/// Where the power comes from and how full the battery is. A Mac without a battery says only "ac".
|
|
21
|
+
func power() -> [String: Any] {
|
|
22
|
+
let info = IOPSCopyPowerSourcesInfo().takeRetainedValue()
|
|
23
|
+
let providing = IOPSGetProvidingPowerSourceType(info).takeUnretainedValue() as String
|
|
24
|
+
var out: [String: Any] = ["on": providing == kIOPMACPowerKey ? "ac" : (providing == kIOPMBatteryPowerKey ? "battery" : "ups")]
|
|
25
|
+
for source in IOPSCopyPowerSourcesList(info).takeRetainedValue() as [CFTypeRef] {
|
|
26
|
+
guard let about = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any] else { continue }
|
|
27
|
+
guard let now = about[kIOPSCurrentCapacityKey] as? Int, let full = about[kIOPSMaxCapacityKey] as? Int, full > 0 else { continue }
|
|
28
|
+
out["percent"] = now * 100 / full
|
|
29
|
+
if let charging = about[kIOPSIsChargingKey] as? Bool { out["charging"] = charging }
|
|
30
|
+
break
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let wanted = Set(CommandLine.arguments.dropFirst())
|
|
36
|
+
func on(_ kind: String) -> Bool { wanted.isEmpty || wanted.contains(kind) }
|
|
37
|
+
|
|
38
|
+
let workspace = NSWorkspace.shared.notificationCenter
|
|
39
|
+
let main = OperationQueue.main
|
|
40
|
+
var kept: [Any] = []
|
|
41
|
+
|
|
42
|
+
if on("sleep") {
|
|
43
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.willSleepNotification, object: nil, queue: main) { _ in say("sleeping") })
|
|
44
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: main) { _ in say("woke") })
|
|
45
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: main) { _ in say("display-off") })
|
|
46
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.screensDidWakeNotification, object: nil, queue: main) { _ in say("display-on") })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if on("lock") {
|
|
50
|
+
let all = DistributedNotificationCenter.default()
|
|
51
|
+
kept.append(all.addObserver(forName: Notification.Name("com.apple.screenIsLocked"), object: nil, queue: main) { _ in say("locked") })
|
|
52
|
+
kept.append(all.addObserver(forName: Notification.Name("com.apple.screenIsUnlocked"), object: nil, queue: main) { _ in say("unlocked") })
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if on("volumes") {
|
|
56
|
+
func volume(_ note: Notification) -> [String: Any] {
|
|
57
|
+
var out: [String: Any] = [:]
|
|
58
|
+
if let name = note.userInfo?[NSWorkspace.localizedVolumeNameUserInfoKey] as? String { out["name"] = name }
|
|
59
|
+
if let url = note.userInfo?[NSWorkspace.volumeURLUserInfoKey] as? URL { out["path"] = url.path }
|
|
60
|
+
return out
|
|
61
|
+
}
|
|
62
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.didMountNotification, object: nil, queue: main) { note in say("mounted", volume(note)) })
|
|
63
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.didUnmountNotification, object: nil, queue: main) { note in say("unmounted", volume(note)) })
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if on("apps") {
|
|
67
|
+
func app(_ note: Notification) -> [String: Any] {
|
|
68
|
+
guard let running = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication else { return [:] }
|
|
69
|
+
var out: [String: Any] = [:]
|
|
70
|
+
if let name = running.localizedName { out["app"] = name }
|
|
71
|
+
if let bundle = running.bundleIdentifier { out["bundle"] = bundle }
|
|
72
|
+
return out
|
|
73
|
+
}
|
|
74
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.didLaunchApplicationNotification, object: nil, queue: main) { note in say("app-started", app(note)) })
|
|
75
|
+
kept.append(workspace.addObserver(forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: main) { note in say("app-quit", app(note)) })
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if on("power") {
|
|
79
|
+
// Said once at the start, so that whoever listens knows what a later line differs from.
|
|
80
|
+
say("power", power())
|
|
81
|
+
let source = IOPSNotificationCreateRunLoopSource({ _ in say("power", power()) }, nil).takeRetainedValue()
|
|
82
|
+
CFRunLoopAddSource(CFRunLoopGetMain(), source, .defaultMode)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let monitor = NWPathMonitor()
|
|
86
|
+
if on("network") {
|
|
87
|
+
// Called once right away with how things are, then at every change.
|
|
88
|
+
monitor.pathUpdateHandler = { path in
|
|
89
|
+
let via = path.usesInterfaceType(.wifi) ? "wifi" : path.usesInterfaceType(.wiredEthernet) ? "ethernet" : path.usesInterfaceType(.cellular) ? "cellular" : "other"
|
|
90
|
+
say("network", path.status == .satisfied ? ["online": true, "via": via] : ["online": false])
|
|
91
|
+
}
|
|
92
|
+
monitor.start(queue: DispatchQueue.main)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// pine closes the input when the source stops, and when pine itself is gone the input is closed too.
|
|
96
|
+
Thread.detachNewThread {
|
|
97
|
+
while FileHandle.standardInput.availableData.count > 0 {}
|
|
98
|
+
exit(0)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
say("ready")
|
|
102
|
+
RunLoop.main.run()
|
package/src/sources/telegram.js
CHANGED
|
@@ -24,7 +24,10 @@ import { errText, sleep, truncate } from "../util.js";
|
|
|
24
24
|
export const type = {
|
|
25
25
|
summary: "a Telegram bot: your owner writes to it from anywhere and you answer there; you can also message them through it. Needs the bot's token from @BotFather",
|
|
26
26
|
talks: true,
|
|
27
|
-
sends: 'a Telegram message to your owner: {"text": "..."}',
|
|
27
|
+
sends: 'a Telegram message to your owner: {"text": "..."}, and with "file" a picture, a video or a sound file from your workspace to go with it',
|
|
28
|
+
files: true,
|
|
29
|
+
// send() refuses every chat but the owner's (`heard`), whatever the message names.
|
|
30
|
+
toOwner: true,
|
|
28
31
|
options: Type.Object({
|
|
29
32
|
token: Type.String({ description: "the bot's token, which @BotFather gives when a bot is made with /newbot (123456789:AA...)", secret: true }),
|
|
30
33
|
allow: Type.Optional(Type.Array(Type.Number(), { description: "Telegram user ids that may talk to the bot. Leave out unless your owner gave you their id: the bot is then paired, which means it sends a code to the account that writes to it and your owner types that code into pine" })),
|
|
@@ -63,6 +66,10 @@ export const type = {
|
|
|
63
66
|
},
|
|
64
67
|
};
|
|
65
68
|
const MAX_PHOTO = 10 * 1024 * 1024;
|
|
69
|
+
/** What a bot may upload in one file. */
|
|
70
|
+
const MAX_UPLOAD = 50 * 1024 * 1024;
|
|
71
|
+
/** How long a caption under a picture or a video may be. */
|
|
72
|
+
const MAX_CAPTION = 1024;
|
|
66
73
|
export default async function telegram(source) {
|
|
67
74
|
const o = source.options;
|
|
68
75
|
const token = String(o.token ?? "");
|
|
@@ -107,10 +114,36 @@ export default async function telegram(source) {
|
|
|
107
114
|
return last;
|
|
108
115
|
};
|
|
109
116
|
// ---- out: answers, and what an agent sends on its own -------------------------------------------
|
|
117
|
+
/** A picture, a video or a sound file to the owner's chat, with the message as its caption where it fits under one. */
|
|
118
|
+
const sendFile = async (chatId, file, text) => {
|
|
119
|
+
if (!heard(chatId))
|
|
120
|
+
throw new Error("that chat is not your owner's");
|
|
121
|
+
if (file.bytes.length > MAX_UPLOAD)
|
|
122
|
+
throw new Error(`${file.name} is ${Math.round(file.bytes.length / 1024 / 1024)} MB, and Telegram takes files up to 50 MB from a bot. Send a smaller one: a single picture, or the video scaled down with ffmpeg`);
|
|
123
|
+
const [method, field] = file.mime.startsWith("image/") && file.bytes.length <= MAX_PHOTO ? ["sendPhoto", "photo"] : file.mime.startsWith("video/") ? ["sendVideo", "video"] : file.mime.startsWith("audio/") ? ["sendAudio", "audio"] : ["sendDocument", "document"];
|
|
124
|
+
// A message too long for a caption goes first, by itself, so that nothing of it is cut.
|
|
125
|
+
const caption = text.trim();
|
|
126
|
+
if (caption.length > MAX_CAPTION)
|
|
127
|
+
await send(chatId, caption);
|
|
128
|
+
const form = new FormData();
|
|
129
|
+
form.set("chat_id", String(chatId));
|
|
130
|
+
if (caption && caption.length <= MAX_CAPTION)
|
|
131
|
+
form.set("caption", caption);
|
|
132
|
+
form.set(field, new Blob([new Uint8Array(file.bytes)], { type: file.mime }), file.name);
|
|
133
|
+
const res = await fetch(`${base}/bot${token}/${method}`, { method: "POST", body: form, signal: AbortSignal.any([stop.signal, AbortSignal.timeout(180_000)]) });
|
|
134
|
+
const json = await res.json().catch(() => ({}));
|
|
135
|
+
if (!json.ok)
|
|
136
|
+
throw new Error(`Telegram refused ${method}: ${json.description ?? res.status}`);
|
|
137
|
+
};
|
|
110
138
|
source.onSend(async (message) => {
|
|
111
139
|
const chatId = Number(message.chatId ?? ownerChat());
|
|
112
140
|
if (!Number.isFinite(chatId))
|
|
113
141
|
throw new Error("nobody is connected yet: your owner has to write to the bot once, and confirm it in pine");
|
|
142
|
+
const file = message.file;
|
|
143
|
+
if (file && Buffer.isBuffer(file.bytes)) {
|
|
144
|
+
await sendFile(chatId, file, String(message.text ?? ""));
|
|
145
|
+
return `sent to your owner on Telegram, with ${file.name}`;
|
|
146
|
+
}
|
|
114
147
|
await send(chatId, String(message.text ?? ""));
|
|
115
148
|
return "sent to your owner on Telegram";
|
|
116
149
|
});
|