@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,265 @@
1
+ import crypto from "node:crypto";
2
+ import { Type } from "typebox";
3
+ import { parseDuration } from "../util.js";
4
+ import { ask, askable, clip, guardFor, keepSince, sinceOf, whyFailed } from "../watching.js";
5
+ /**
6
+ * A calendar, read again and again: reports the entries that were added, changed or removed.
7
+ * For any calendar that has an address of its own in iCalendar format (.ics): a shared family
8
+ * calendar, a team's, a school's, the waste collection.
9
+ *
10
+ * options: { url, every?, ahead?, headers?, token?, tokenHeader?, local? }
11
+ * url https://... or webcal://... (which is read as https)
12
+ * every how often to read it ("15m" by default)
13
+ * ahead only entries that begin within this from now ("60d" by default)
14
+ *
15
+ * event "added": { calendar, uid, summary, start, end?, allDay?, zone?, location?, description?, repeats? }
16
+ * event "changed": the same, with was: { summary, start, end?, location? }
17
+ * event "removed": { calendar, uid, summary, start }
18
+ *
19
+ * It reports changes to the calendar and nothing else. It never fires because an entry is about
20
+ * to begin: what should happen at a time is a schedule. An entry that has simply passed is not
21
+ * "removed". A repeating entry is one entry with its rule in `repeats`; it is not unfolded.
22
+ */
23
+ const MIN = "1m";
24
+ /** A calendar carries its whole past. More than this is not read, and a look says so. */
25
+ const MAX_BODY = 8 * 1024 * 1024;
26
+ const AT_ONCE = 20;
27
+ const MOST = 5000;
28
+ /** "Never over": a repeating entry without an end. */
29
+ const NEVER = 8.64e15;
30
+ export const type = {
31
+ summary: "a calendar (an .ics address) read again and again: reports entries that are added, changed or removed. For shared, team, school and collection calendars",
32
+ options: Type.Object({
33
+ url: Type.String({ description: "the address of the calendar in iCalendar format, https://... or webcal://... (it usually ends in .ics; calendar services call it the iCal, ICS or subscription address)" }),
34
+ every: Type.Optional(Type.String({ description: 'how often to read it, e.g. "15m", "1h". Default "15m", at least "1m"' })),
35
+ ahead: Type.Optional(Type.String({ description: 'only entries that begin within this from now, e.g. "14d". Default "60d". What is added further away is not reported, also not later when it comes nearer' })),
36
+ headers: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "headers to send. Not for secrets" })),
37
+ token: Type.Optional(Type.String({ description: "an access token or key, if the calendar wants one. Sent as Authorization: Bearer <token>", secret: true })),
38
+ tokenHeader: Type.Optional(Type.String({ description: 'send the token as this header instead, as it is, e.g. "x-api-key"' })),
39
+ local: Type.Optional(Type.Boolean({ description: "true if the address is on your owner's own network under a name that does not say so. Not needed for an IP address, localhost or a .local name" })),
40
+ }, { additionalProperties: false }),
41
+ plan(o) {
42
+ // webcal:// is how calendar programs write "subscribe to this": the same address over https.
43
+ const { url, every, local } = askable({ ...o, url: String(o.url ?? "").trim().replace(/^webcals?:\/\//i, "https://") }, MIN, "15m");
44
+ const ahead = o.ahead ?? "60d";
45
+ if (parseDuration(ahead) < 3_600_000)
46
+ throw new Error('"ahead" must be at least "1h"');
47
+ return {
48
+ options: { ...o, url: url.href },
49
+ does: [`read the calendar at ${clip(url.href, 160)}${local ? " (an address on your own network or this computer)" : ""} every ${every} and report entries that are added, changed or removed, as far as they begin within ${ahead}`, ...(o.token ? [`with the token given, sent only to ${url.host}`] : [])],
50
+ opens: true,
51
+ tell: 'The entries that are in the calendar now are the starting point and are not reported; from then on each change is. It does not report that an entry is about to begin: for a reminder before one, add a schedule (add_schedule with "at").',
52
+ };
53
+ },
54
+ };
55
+ // ---- reading a calendar ---------------------------------------------------------------------------
56
+ /** One line of a calendar: the property's name, its parameters, its value. */
57
+ function content(line) {
58
+ let quoted = false;
59
+ let colon = -1;
60
+ const cuts = [];
61
+ for (let i = 0; i < line.length; i++) {
62
+ const c = line[i];
63
+ if (c === '"')
64
+ quoted = !quoted;
65
+ else if (!quoted && c === ";")
66
+ cuts.push(i);
67
+ else if (!quoted && c === ":") {
68
+ colon = i;
69
+ break;
70
+ }
71
+ }
72
+ if (colon < 1)
73
+ return undefined;
74
+ const ends = [...cuts, colon];
75
+ const name = line.slice(0, ends[0]).trim().toUpperCase();
76
+ const params = {};
77
+ for (let i = 1; i < ends.length; i++) {
78
+ const p = line.slice(ends[i - 1] + 1, ends[i]);
79
+ const eq = p.indexOf("=");
80
+ if (eq > 0)
81
+ params[p.slice(0, eq).toUpperCase()] = p.slice(eq + 1).replace(/^"|"$/g, "");
82
+ }
83
+ return { name, params, value: line.slice(colon + 1) };
84
+ }
85
+ /** A text value as it was typed: \n is a new line, \, a comma, \; a semicolon. */
86
+ const typed = (s) => s.replace(/\\([nN,;\\])/g, (_all, c) => (c === "n" || c === "N" ? "\n" : c)).trim();
87
+ /** How far a zone's clock is ahead of UTC at an instant, in milliseconds. Throws for a zone the system does not know. */
88
+ function ahead(ts, zone) {
89
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(ts);
90
+ const n = (t) => Number(parts.find((p) => p.type === t)?.value);
91
+ return Date.UTC(n("year"), n("month") - 1, n("day"), n("hour"), n("minute"), n("second")) - Math.floor(ts / 1000) * 1000;
92
+ }
93
+ /** A date or a date with a time as a calendar writes it: how an event says it, and the instant it means. */
94
+ function time(value, params) {
95
+ const m = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z?))?$/.exec(value.trim());
96
+ if (!m)
97
+ return undefined;
98
+ const [y, mo, d, h, mi, s] = m.slice(1, 7).map((x) => Number(x ?? 0));
99
+ const day = `${m[1]}-${m[2]}-${m[3]}`;
100
+ // A day as such: it begins when the day does where pine runs.
101
+ if (m[4] === undefined)
102
+ return { text: day, at: new Date(y, mo - 1, d).getTime(), allDay: true };
103
+ const clock = `${day}T${m[4]}:${m[5]}:${m[6]}`;
104
+ if (m[7])
105
+ return { text: `${clock}Z`, at: Date.UTC(y, mo - 1, d, h, mi, s) };
106
+ const zone = (params.TZID ?? "").replace(/^\//, "").trim() || undefined;
107
+ if (zone) {
108
+ try {
109
+ const wall = Date.UTC(y, mo - 1, d, h, mi, s);
110
+ const first = wall - ahead(wall, zone);
111
+ return { text: clock, zone: clip(zone, 80), at: wall - ahead(first, zone) };
112
+ }
113
+ catch {
114
+ // A zone under a name of the program that wrote the calendar: read as this computer's own.
115
+ }
116
+ }
117
+ return { text: clock, ...(zone ? { zone: clip(zone, 80) } : {}), at: new Date(y, mo - 1, d, h, mi, s).getTime() };
118
+ }
119
+ /** How long "P1DT2H30M" is, in milliseconds. */
120
+ function span(value) {
121
+ const m = /^[+-]?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/.exec(value.trim());
122
+ if (!m)
123
+ return 0;
124
+ const [w, d, h, mi, s] = m.slice(1).map((x) => Number(x ?? 0));
125
+ return ((((w * 7 + d) * 24 + h) * 60 + mi) * 60 + s) * 1000;
126
+ }
127
+ const dayBefore = (day) => {
128
+ const [y, m, d] = day.split("-").map(Number);
129
+ const t = new Date(Date.UTC(y, m - 1, d - 1));
130
+ return t.toISOString().slice(0, 10);
131
+ };
132
+ /** A calendar's name and its entries. Throws for a document that is no calendar. */
133
+ export function parseCalendar(body) {
134
+ const text = body.replace(/^/, "");
135
+ if (!/^\s*BEGIN:VCALENDAR/im.test(text))
136
+ throw new Error(/^\s*<(!doctype html|html)\b/i.test(text) ? "that address is a web page, not a calendar. The calendar itself has an address of its own, which usually ends in .ics: calendar services show it as the iCal or subscription address" : "what it answers is not a calendar (iCalendar, .ics)");
137
+ // A long line is continued on the next one, which then begins with a space.
138
+ const lines = text.replace(/\r\n?/g, "\n").replace(/\n[ \t]/g, "").split("\n");
139
+ const open = [];
140
+ const items = [];
141
+ let name = "";
142
+ let props = {};
143
+ for (const raw of lines) {
144
+ const c = content(raw);
145
+ if (!c)
146
+ continue;
147
+ if (c.name === "BEGIN") {
148
+ open.push(c.value.trim().toUpperCase());
149
+ if (open.at(-1) === "VEVENT")
150
+ props = {};
151
+ continue;
152
+ }
153
+ if (c.name === "END") {
154
+ const kind = open.pop();
155
+ if (kind !== "VEVENT")
156
+ continue;
157
+ const begins = props.DTSTART ? time(props.DTSTART.value, props.DTSTART.params) : undefined;
158
+ if (!begins || /^CANCELLED$/i.test(props.STATUS?.value.trim() ?? ""))
159
+ continue;
160
+ const ends = props.DTEND ? time(props.DTEND.value, props.DTEND.params) : undefined;
161
+ const summary = clip(typed(props.SUMMARY?.value ?? "").replace(/\s+/g, " "), 300);
162
+ const uid = clip((props.UID?.value ?? "").trim() || `#${crypto.createHash("sha256").update(`${summary}\n${begins.text}`).digest("hex").slice(0, 16)}`, 300);
163
+ const rule = props.RRULE?.value.trim();
164
+ const stops = rule ? /(?:^|;)UNTIL=([0-9TZ]+)/i.exec(rule)?.[1] : undefined;
165
+ const over = ends ? ends.at : begins.at + (props.DURATION ? span(props.DURATION.value) : begins.allDay ? 86_400_000 : 0);
166
+ // For a whole day the calendar names the day after as the end; a reader means the last day.
167
+ const last = ends && begins.allDay && ends.allDay ? dayBefore(ends.text) : ends?.text;
168
+ const location = clip(typed(props.LOCATION?.value ?? "").replace(/\s+/g, " "), 300);
169
+ const description = clip(typed(props.DESCRIPTION?.value ?? ""), 1000);
170
+ items.push({
171
+ // One occurrence of a repeating entry that was moved is an entry of its own, under the same uid.
172
+ key: props["RECURRENCE-ID"] ? `${uid}\n${props["RECURRENCE-ID"].value.trim()}` : uid,
173
+ uid,
174
+ summary,
175
+ start: begins.text,
176
+ ...(last && last !== begins.text ? { end: last } : {}),
177
+ ...(begins.allDay ? { allDay: true } : {}),
178
+ ...(begins.zone ? { zone: begins.zone } : {}),
179
+ ...(location ? { location } : {}),
180
+ ...(description ? { description } : {}),
181
+ ...(rule ? { repeats: clip(rule, 200) } : {}),
182
+ at: begins.at,
183
+ until: rule ? (stops ? (time(stops, {})?.at ?? NEVER) + 86_400_000 : NEVER) : over,
184
+ });
185
+ continue;
186
+ }
187
+ if (open.at(-1) === "VEVENT")
188
+ props[c.name] ??= { params: c.params, value: c.value };
189
+ else if (open.length === 1 && c.name === "X-WR-CALNAME")
190
+ name = clip(typed(c.value).replace(/\s+/g, " "), 120);
191
+ }
192
+ return { name, items };
193
+ }
194
+ export default function calendar(source) {
195
+ const o = source.options;
196
+ if (typeof o.url !== "string")
197
+ throw new Error(`needs "url": the address of the calendar`);
198
+ const url = new URL(o.url.replace(/^webcals?:\/\//i, "https://"));
199
+ if (!["http:", "https:"].includes(url.protocol))
200
+ throw new Error("the address must start with https://, http:// or webcal://");
201
+ const aheadMs = parseDuration(o.ahead ?? "60d");
202
+ source.secret(o.token);
203
+ const guard = guardFor(url, o.local);
204
+ if (guard)
205
+ source.onStop(() => guard.close());
206
+ const about = { url: url.href };
207
+ source.poll(o.every ?? "15m", async (signal) => {
208
+ let answer;
209
+ try {
210
+ answer = await ask(url, { headers: o.headers, token: o.token, tokenHeader: o.tokenHeader, accept: "text/calendar, */*;q=0.5" }, guard, signal, sinceOf(source, about), MAX_BODY);
211
+ }
212
+ catch (e) {
213
+ if (signal.aborted)
214
+ return;
215
+ throw new Error(whyFailed(e, url));
216
+ }
217
+ if (answer.unchanged)
218
+ return;
219
+ // Half a calendar would make every entry of the other half look removed.
220
+ if (answer.truncated)
221
+ throw new Error("the calendar is larger than 8 MB, which is more than is read of one");
222
+ const { name, items } = parseCalendar(answer.body);
223
+ const now = Date.now();
224
+ const near = (e) => e.r === 1 || e.at <= now + aheadMs;
225
+ // What is over is neither kept nor missed.
226
+ const current = new Map();
227
+ for (const item of items)
228
+ if (item.until >= now && current.size < MOST && !current.has(item.key))
229
+ current.set(item.key, item);
230
+ const keep = (i) => ({ s: i.summary, a: i.start, ...(i.end ? { e: i.end } : {}), ...(i.location ? { l: i.location } : {}), at: i.at, until: i.until, ...(i.repeats ? { r: 1 } : {}) });
231
+ const next = Object.fromEntries([...current].map(([key, item]) => [key, keep(item)]));
232
+ const before = source.kv.get("entries");
233
+ source.status(`now: ${Object.values(next).filter(near).length} entries ahead`);
234
+ if (!before || JSON.stringify(before) !== JSON.stringify(next))
235
+ source.kv.set("entries", next);
236
+ keepSince(source, about, answer);
237
+ // The first look is the starting point.
238
+ if (!before)
239
+ return;
240
+ const calendarName = name || url.host;
241
+ const full = (i) => {
242
+ const { key: _key, at: _at, until: _until, ...said } = i;
243
+ return { calendar: calendarName, ...said };
244
+ };
245
+ const events = [];
246
+ for (const [key, item] of current) {
247
+ const was = before[key];
248
+ const is = next[key];
249
+ if (!was) {
250
+ if (near(is))
251
+ events.push({ event: "added", at: item.at, payload: full(item) });
252
+ }
253
+ else if ((was.s !== is.s || was.a !== is.a || (was.e ?? "") !== (is.e ?? "") || (was.l ?? "") !== (is.l ?? "")) && (near(is) || near(was))) {
254
+ events.push({ event: "changed", at: item.at, payload: { ...full(item), was: { summary: was.s, start: was.a, ...(was.e ? { end: was.e } : {}), ...(was.l ? { location: was.l } : {}) } } });
255
+ }
256
+ }
257
+ for (const [key, was] of Object.entries(before)) {
258
+ if (!current.has(key) && was.until >= now && near(was))
259
+ events.push({ event: "removed", at: was.at, payload: { calendar: calendarName, uid: key.split("\n")[0], summary: was.s, start: was.a } });
260
+ }
261
+ events.sort((a, b) => a.at - b.at);
262
+ const told = events.slice(0, AT_ONCE);
263
+ told.forEach((e, i) => source.emit(e.event, { ...e.payload, ...(events.length > told.length && i === told.length - 1 ? { more: events.length - told.length } : {}) }));
264
+ });
265
+ }
@@ -1,6 +1,6 @@
1
1
  import { Type } from "typebox";
2
- import { parseDuration } from "../util.js";
3
- import { clip, found, harmless, lineDiff, pattern, shown } from "../watching.js";
2
+ import { errText, parseDuration } from "../util.js";
3
+ import { capped, clip, found, harmless, lineDiff, pattern, shown } from "../watching.js";
4
4
  /**
5
5
  * A command, run again and again: reports when what it prints or how it ends changes. For what
6
6
  * only a command can tell: free disk space, a build, a branch that moved, a log, whether a
@@ -15,10 +15,24 @@ import { clip, found, harmless, lineDiff, pattern, shown } from "../watching.js"
15
15
  * event "changed": { command, code, previousCode?, value, previous } with match
16
16
  * { command, code, previousCode?, added, removed, more? } without
17
17
  *
18
+ * With `follow` the command is started once and kept running, and every line it prints is an
19
+ * event as it comes: for what tells by itself when something happens (tail -F, log stream,
20
+ * docker events, kubectl get -w, a client of some broker).
21
+ *
22
+ * follow true: keep the command running and report its lines; `every` is not used
23
+ * perMinute with follow: at most this many lines a minute (30 by default); the rest are counted
24
+ *
25
+ * event "line": { command, line, value?, dropped? } value: what `match` found, or the line as JSON if it is JSON
26
+ * event "ended": { command, code, error?, ran } it ended and is started again; not repeated while it ends at once every time
27
+ *
18
28
  * The command runs in the sandbox of that agent's shell: it reaches what the agent reaches and
19
29
  * nothing else. The first run is the starting point and reports nothing.
20
30
  */
21
31
  const MIN = 5000;
32
+ /** A followed command that ended is started again after a pause that grows with each end in a row. */
33
+ const AGAIN = [250, 500, 1000, 2000, 5000, 15_000, 60_000, 300_000];
34
+ /** A run shorter than this that follows another such run is the same trouble, not news. */
35
+ const BRIEF = 5000;
22
36
  export const type = {
23
37
  summary: "a command run again and again: reports when what it prints, or how it ends (its exit code), changes. For what only a command can tell: free disk space, a build, a branch that moved, a log, whether a machine answers. It runs like a command in your own shell, with the same limits",
24
38
  options: Type.Object({
@@ -26,6 +40,8 @@ export const type = {
26
40
  every: Type.Optional(Type.String({ description: 'how often to run it, e.g. "1m", "1h". Default "1m", at least "5s"' })),
27
41
  match: Type.Optional(Type.String({ description: 'watch only what this regular expression finds in what it prints (its first group, if it has one), e.g. "([0-9]+)% used". Without it everything it prints counts' })),
28
42
  timeout: Type.Optional(Type.String({ description: 'how long one run may take before it is stopped. Default "30s"' })),
43
+ follow: Type.Optional(Type.Boolean({ description: 'true for a command that keeps running and prints a line whenever something happens ("tail -n0 -F app.log", "log stream --predicate ...", "docker events"): it is started once, and every line it prints is reported as it comes. "every" and "timeout" are not used then. Not on Linux' })),
44
+ perMinute: Type.Optional(Type.Number({ description: "with follow: report at most this many lines a minute, the rest are counted and left out. Default 30" })),
29
45
  }, { additionalProperties: false }),
30
46
  plan(o, setup) {
31
47
  const run = String(o.run ?? "").trim();
@@ -33,13 +49,30 @@ export const type = {
33
49
  throw new Error(`needs "run": the command line`);
34
50
  if (run.length > 2000)
35
51
  throw new Error("that command line is too long: put it into a script in your workspace and run that");
52
+ if (o.match)
53
+ pattern(o.match);
54
+ if (o.follow === true) {
55
+ if (o.every !== undefined || o.timeout !== undefined)
56
+ throw new Error('a command that is followed runs all the time: leave "every" and "timeout" out');
57
+ if (process.platform === "linux")
58
+ throw new Error('"follow" does not work on Linux: its sandbox cleans up after a command, and a followed command does not end. Leave "follow" out and give "every": the command is then run again and again');
59
+ const perMinute = o.perMinute ?? 30;
60
+ if (!(perMinute >= 1 && perMinute <= 600))
61
+ throw new Error('"perMinute" is a number from 1 to 600');
62
+ return {
63
+ options: { ...o, run },
64
+ does: [`start this command and keep it running, unattended, with the rights of ${setup.agent}'s shell (its sandbox): ${run}`, `report ${o.match ? `every line it prints in which /${o.match}/ finds something` : "every line it prints"}, at most ${perMinute} a minute`, "start it again whenever it ends"],
65
+ opens: true,
66
+ tell: "It runs from now on; what it prints from here on is reported, line by line. The sources tool shows whether it is running.",
67
+ };
68
+ }
69
+ if (o.perMinute !== undefined)
70
+ throw new Error('"perMinute" is for a command that is followed ("follow": true)');
36
71
  const every = o.every ?? "1m";
37
72
  if (parseDuration(every) < MIN)
38
73
  throw new Error('"every" must be at least "5s"');
39
74
  if (o.timeout && parseDuration(o.timeout) < 1000)
40
75
  throw new Error('"timeout" must be at least "1s"');
41
- if (o.match)
42
- pattern(o.match);
43
76
  return {
44
77
  options: { ...o, run },
45
78
  does: [`run this command every ${every}, unattended, with the rights of ${setup.agent}'s shell (its sandbox): ${run}`, `report when ${o.match ? `what /${o.match}/ finds in what it prints` : "what it prints"} or its exit code changes`],
@@ -54,6 +87,8 @@ export default function command(source) {
54
87
  if (!run)
55
88
  throw new Error(`needs "run": the command line`);
56
89
  const re = o.match ? pattern(String(o.match)) : undefined;
90
+ if (o.follow === true)
91
+ return void following(source, run, re);
57
92
  const timeoutMs = parseDuration(o.timeout ?? "30s");
58
93
  source.poll(o.every ?? "1m", async (signal) => {
59
94
  const { code, output } = await source.exec(run, { timeoutMs, signal });
@@ -75,3 +110,73 @@ export default function command(source) {
75
110
  source.emit("changed", { command: clip(run, 300), code, ...(was.previous.code !== code ? { previousCode: was.previous.code } : {}), ...diff });
76
111
  });
77
112
  }
113
+ const clock = () => new Date().toTimeString().slice(0, 8);
114
+ /** Wait, but not longer than the source lives. */
115
+ const pause = (ms, signal) => new Promise((resolve) => {
116
+ if (signal.aborted)
117
+ return resolve();
118
+ const done = () => {
119
+ clearTimeout(timer);
120
+ signal.removeEventListener("abort", done);
121
+ resolve();
122
+ };
123
+ const timer = setTimeout(done, ms);
124
+ signal.addEventListener("abort", done, { once: true });
125
+ });
126
+ /** Keep a command running and report what it prints. It is started again when it ends, a little later each time it ends at once. */
127
+ function following(source, run, re) {
128
+ const cap = capped(Number(source.options.perMinute ?? 30));
129
+ const stop = new AbortController();
130
+ source.onStop(() => stop.abort());
131
+ let lines = 0;
132
+ const line = (text) => {
133
+ // What a terminal would act on is not text.
134
+ const clean = text.replace(/\x1b\[[0-9;?]*[A-Za-z]|[\x00-\x08\x0b-\x1f\x7f]/g, "");
135
+ let value;
136
+ if (re) {
137
+ value = found(re, clean);
138
+ if (value === null)
139
+ return;
140
+ }
141
+ else if (/^\s*[[{]/.test(clean)) {
142
+ try {
143
+ value = JSON.parse(clean);
144
+ }
145
+ catch {
146
+ // a line that only looks like JSON
147
+ }
148
+ }
149
+ if (!cap.ok())
150
+ return;
151
+ lines++;
152
+ const dropped = cap.dropped();
153
+ source.emit("line", { command: clip(run, 300), line: clip(clean, 2000), ...(value !== undefined ? { value: shown(value) } : {}), ...(dropped ? { dropped } : {}) });
154
+ };
155
+ void (async () => {
156
+ let fails = 0;
157
+ let wasBrief = false;
158
+ while (!stop.signal.aborted) {
159
+ const from = Date.now();
160
+ source.status(`running since ${clock()}, ${lines} ${lines === 1 ? "line" : "lines"} reported`);
161
+ let code;
162
+ let error = "";
163
+ try {
164
+ ({ code, error } = await source.follow(run, line, { signal: stop.signal }));
165
+ }
166
+ catch (e) {
167
+ if (stop.signal.aborted)
168
+ return;
169
+ error = errText(e);
170
+ }
171
+ const ran = Date.now() - from;
172
+ const brief = ran < BRIEF;
173
+ // Said when it ends, but not again and again for a command that ends the moment it is started.
174
+ if (!(brief && wasBrief))
175
+ source.emit("ended", { command: clip(run, 300), ...(code !== undefined ? { code } : {}), ...(error ? { error: clip(error, 600) } : {}), ran: Math.round(ran / 1000) });
176
+ wasBrief = brief;
177
+ fails = brief ? fails + 1 : 0;
178
+ source.status(`ended at ${clock()}${code !== undefined ? ` with exit ${code}` : ""}, ${code === undefined ? "could not be started" : "starting it again"}`);
179
+ await pause(AGAIN[Math.min(fails, AGAIN.length - 1)], stop.signal);
180
+ }
181
+ })();
182
+ }
@@ -0,0 +1,4 @@
1
+ import type { SourceType } from "../source-types.ts";
2
+ import type { SourceApi } from "../sources.ts";
3
+ export declare const type: SourceType;
4
+ export default function discord(source: SourceApi): void;