@tidegap/core 0.21.0 → 0.23.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 (49) hide show
  1. package/dist/channels/digest.d.ts +4 -1
  2. package/dist/channels/digest.js +7 -3
  3. package/dist/channels/format.d.ts +61 -19
  4. package/dist/channels/format.js +181 -51
  5. package/dist/channels/index.d.ts +1 -0
  6. package/dist/channels/index.js +1 -0
  7. package/dist/channels/kinds/discord.js +2 -2
  8. package/dist/channels/kinds/email.js +2 -1
  9. package/dist/channels/kinds/ntfy.js +9 -1
  10. package/dist/channels/kinds/pushover.js +4 -3
  11. package/dist/channels/kinds/shared.d.ts +4 -1
  12. package/dist/channels/kinds/shared.js +6 -1
  13. package/dist/channels/kinds/slack.js +2 -2
  14. package/dist/channels/notice.d.ts +42 -0
  15. package/dist/channels/notice.js +142 -0
  16. package/dist/channels/payload.d.ts +3 -0
  17. package/dist/channels/payload.js +19 -6
  18. package/dist/channels/plan.js +3 -2
  19. package/dist/channels/telegram.d.ts +18 -0
  20. package/dist/channels/telegram.js +23 -9
  21. package/dist/channels/types.d.ts +17 -1
  22. package/dist/grid.d.ts +10 -2
  23. package/dist/grid.js +14 -5
  24. package/dist/handoff.d.ts +66 -3
  25. package/dist/handoff.js +108 -3
  26. package/dist/history.d.ts +105 -0
  27. package/dist/history.js +108 -1
  28. package/dist/index.d.ts +15 -11
  29. package/dist/index.js +10 -6
  30. package/dist/job-cadence.d.ts +10 -0
  31. package/dist/job-cadence.js +34 -0
  32. package/dist/job-wake.d.ts +55 -0
  33. package/dist/job-wake.js +91 -0
  34. package/dist/jobs.d.ts +54 -2
  35. package/dist/jobs.js +258 -14
  36. package/dist/notice-language.d.ts +37 -0
  37. package/dist/notice-language.js +67 -0
  38. package/dist/providers/base.d.ts +14 -0
  39. package/dist/schedule-job.d.ts +18 -2
  40. package/dist/schedule-job.js +22 -2
  41. package/dist/scheduler.d.ts +2 -0
  42. package/dist/scheduler.js +5 -1
  43. package/dist/storage/sqlite.d.ts +24 -3
  44. package/dist/storage/sqlite.js +135 -28
  45. package/dist/task-events.d.ts +1 -1
  46. package/dist/task-events.js +9 -0
  47. package/dist/tool-surface.js +25 -1
  48. package/dist/types.d.ts +41 -1
  49. package/package.json +2 -2
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { type ReadinessProblem } from "../readiness.js";
11
11
  import type { TaskRecord } from "../types.js";
12
+ import { type NoticeStatus } from "./notice.js";
12
13
  import type { ChannelEvent, CleanWindowEvent } from "./types.js";
13
14
  /**
14
15
  * Ledger meta key: ISO-8601 end of the last summary window. An empty day
@@ -69,6 +70,8 @@ export interface DigestInput {
69
70
  /** One job in the daily summary; the host builds it from the job and its finished runs in the window. */
70
71
  export interface JobDigestLine {
71
72
  title: string;
73
+ /** The newest finished run's notice status; the line starts with its emoji. */
74
+ status: NoticeStatus;
72
75
  /** Finished runs in the window. */
73
76
  runs: number;
74
77
  /** Failed runs among them. */
@@ -87,7 +90,7 @@ export interface JobDigestLine {
87
90
  /** The runs this line reports; their alerts fold into the summary only when the line is printed. */
88
91
  coveredTaskIds: readonly string[];
89
92
  }
90
- /** `Mail triage: ok 03:12, "3 messages need a reply..." - next Fri 02:00` (KTD11). */
93
+ /** `✅ Mail triage: ok 03:12, "3 messages need a reply..." - next Fri 02:00` (KTD11). */
91
94
  export declare function jobDigestText(job: JobDigestLine): string;
92
95
  /** The digest event, with what it covers so per-task alerts can fold into it. */
93
96
  export type DigestEvent = Extract<ChannelEvent, {
@@ -9,7 +9,8 @@
9
9
  */
10
10
  import { localTimeLabel, MORNING_START_H } from "../postpone.js";
11
11
  import { problemLine } from "../readiness.js";
12
- import { cutPreview, messageTitle } from "./format.js";
12
+ import { messageTitle } from "./format.js";
13
+ import { cutPreview, NOTICE_EMOJI } from "./notice.js";
13
14
  /**
14
15
  * Ledger meta key: ISO-8601 end of the last summary window. An empty day
15
16
  * moves it too, so it is not proof of a send; see {@link DIGEST_SENT_META_KEY}.
@@ -56,9 +57,12 @@ export function digestDue(now, lastIso, at = DEFAULT_DIGEST_AT) {
56
57
  return { due, since };
57
58
  }
58
59
  /** Most characters (code points, ellipsis included) of a run preview a job line quotes. */
59
- const JOB_PREVIEW_CHARS = 60;
60
- /** `Mail triage: ok 03:12, "3 messages need a reply..." - next Fri 02:00` (KTD11). */
60
+ const JOB_PREVIEW_CHARS = 100;
61
+ /** `✅ Mail triage: ok 03:12, "3 messages need a reply..." - next Fri 02:00` (KTD11). */
61
62
  export function jobDigestText(job) {
63
+ return `${NOTICE_EMOJI[job.status]} ${jobDigestBody(job)}`;
64
+ }
65
+ function jobDigestBody(job) {
62
66
  const { last } = job;
63
67
  const when = last.late ? `ran late at ${last.at}` : `${last.outcome} ${last.at}`;
64
68
  const preview = last.preview?.replace(/\s+/g, " ").trim();
@@ -18,23 +18,33 @@
18
18
  * | not ready | none |
19
19
  * | replies and `/result` | none |
20
20
  */
21
+ import { type TaskAttachment } from "../history.js";
21
22
  import { type PostponeOption, type PostponePreset } from "../postpone.js";
22
23
  import { type ReadinessProblem } from "../readiness.js";
23
24
  import type { JobRecord, TaskRecord } from "../types.js";
24
25
  import { type InlineKeyboard } from "./telegram.js";
25
- import type { ChannelEvent, CleanWindowEvent, JobPausedNotice } from "./types.js";
26
+ import { type NoticeStatus, type StructuredSummary } from "./notice.js";
27
+ import type { ChannelEvent, CleanWindowEvent, JobEndedNotice, JobPausedNotice } from "./types.js";
26
28
  /** Characters of result text a done message previews (Q4). */
27
29
  export declare const TELEGRAM_PREVIEW_CHARS = 600;
30
+ /** Longest `📎` line: with the title, the time and a full preview, a notice still fits the smallest body cap (Pushover, 1024). */
31
+ export declare const ATTACHMENT_LINE_CHARS = 300;
28
32
  /** Most messages one `/result` sends before pointing to `tidegap queue show`. */
29
33
  export declare const RESULT_MAX_PARTS = 4;
30
34
  /** Tasks one `/queue` lists. */
31
35
  export declare const QUEUE_LIST_MAX = 10;
32
36
  /** Jobs one `/jobs` lists; the same cap as the digest's lists. */
33
37
  export declare const JOBS_LIST_MAX = 10;
34
- /** A message a host sends: text and optional inline buttons. */
38
+ /** The stored files a host sends after a message's text (Telegram only), from {@link sendableAttachments}. */
39
+ export interface OutgoingFiles {
40
+ taskId: string;
41
+ attachments: readonly TaskAttachment[];
42
+ }
43
+ /** A message a host sends: text, optional inline buttons, and optional files to send after it. */
35
44
  export interface OutgoingMessage {
36
45
  text: string;
37
46
  buttons?: InlineKeyboard;
47
+ files?: OutgoingFiles;
38
48
  }
39
49
  /** Button actions in `callback_data` (KTD15). */
40
50
  export type CallbackActionName = "later" | "cancel" | "run" | "result";
@@ -49,38 +59,69 @@ export declare function callbackFits(taskId: string): boolean;
49
59
  /** The decoding tables, for `parseCallback`. */
50
60
  export declare const CALLBACK_ACTIONS: Readonly<Record<string, CallbackActionName>>;
51
61
  export declare const CALLBACK_PRESETS: Readonly<Record<string, PostponePreset>>;
52
- /** True when the task asked for receipt redaction (`redactInReceipt` with patterns): no result text leaves the machine. */
53
- export declare function isRedactedTask(record: TaskRecord<unknown>): boolean;
54
62
  /**
55
63
  * The one-line preview of a run, the same on the jobs page and in the
56
64
  * digest (KTD6): a failed task's first error line with visible text, a
57
- * completed task's result text unless it redacts its receipt, else
58
- * undefined. Default-redacted, control characters removed, whitespace runs
59
- * joined; a longer text is cut to `maxChars - 1` code points plus "…", so
60
- * the result never exceeds `maxChars`.
65
+ * completed task's summary, or its result text without one, unless it
66
+ * redacts its receipt, else undefined. Default-redacted, control characters
67
+ * removed, whitespace runs joined; a longer text is cut to `maxChars - 1`
68
+ * code points plus "…", so the result never exceeds `maxChars`.
61
69
  */
62
70
  export declare function runPreview(record: TaskRecord<unknown>, maxChars: number): string | undefined;
63
- /** `text` cut to `maxChars - 1` code points plus "…" when longer, so it never exceeds `maxChars` (KTD6). */
64
- export declare function cutPreview(text: string, maxChars: number): string;
71
+ /**
72
+ * A run's summary in the notice shape, or undefined when the run has no
73
+ * usable summary: it failed, it redacts its receipt, it has no summary, or
74
+ * the summary has no verdict. The summary is default-redacted first.
75
+ */
76
+ export declare function runSummary(record: TaskRecord<unknown>): StructuredSummary | undefined;
77
+ /**
78
+ * The status of a job run's notice: `failed` for a failed run; for a
79
+ * completed run, the status word of its usable summary, else `done`. A
80
+ * final notice is `ended`, which the caller sets.
81
+ */
82
+ export declare function noticeStatus(record: TaskRecord<unknown>): NoticeStatus;
83
+ /**
84
+ * A run's verdict, the one line a person reads first: for a completed run
85
+ * that does not redact its receipt, the verdict of its summary without the
86
+ * status word, else the first line of its result text; for a failed run,
87
+ * its first error line. Cut to `maxChars`; undefined when there is no such line.
88
+ */
89
+ export declare function runVerdict(record: TaskRecord<unknown>, maxChars?: number): string | undefined;
65
90
  /** The title a message shows: `displayTitle`, one line, at most 80 characters, else the task id. */
66
91
  export declare function messageTitle(record: TaskRecord<unknown>): string;
67
92
  /** The title a task event's message shows: the job's title for a job occurrence, else {@link messageTitle}. */
68
93
  export declare function eventTitle(record: TaskRecord<unknown>, jobTitle?: string): string;
69
94
  /**
70
- * Task done (R26): title, time, where it ran, the preview or the redaction
71
- * note, and a [Result] button. A job occurrence (`jobTitle`) leads with
72
- * `<job title>: <result>` (jobs R22).
95
+ * The line that names a run's attachments: `📎 funnel.png (48 KB), weekly.csv
96
+ * (2 KB), not attached: huge.png (over 10 MB)`. A redacted task names no
97
+ * file: `📎 2 files, not sent: this task redacts its receipt`. Undefined
98
+ * when the run has none.
99
+ */
100
+ export declare function attachmentLine(record: TaskRecord<unknown>): string | undefined;
101
+ /**
102
+ * Task done (R26): title, time, the attachments line, where it ran, the
103
+ * preview or the redaction note, and a [Result] button with the raw result;
104
+ * the run's sendable files go with it. A job occurrence
105
+ * (`jobTitle`) leads with `<status emoji> <job title> — <verdict>`, adds the job's next run
106
+ * (`jobNext`) to the time line, a `No summary` line when its summarize step
107
+ * failed, and shows its summary in place of the raw preview.
73
108
  */
74
- export declare function taskDoneMessage(record: TaskRecord<unknown>, now?: Date, jobTitle?: string): OutgoingMessage;
109
+ export declare function taskDoneMessage(record: TaskRecord<unknown>, now?: Date, jobTitle?: string, jobNext?: string): OutgoingMessage;
75
110
  /**
76
111
  * Task failed: title, time, the first error line, the show command. No
77
- * buttons. A job occurrence (`jobTitle`) leads with `<job title>: failed`.
112
+ * buttons. A job occurrence (`jobTitle`) leads with `❌ <job title>: failed`.
78
113
  */
79
114
  export declare function taskFailedMessage(record: TaskRecord<unknown>, now?: Date, jobTitle?: string): OutgoingMessage;
80
115
  /** The first line of an auto-pause notice (jobs KTD10): `job '<title>' paused after 3 failures: <reason>`. */
81
116
  export declare function jobPausedTitle(notice: JobPausedNotice): string;
82
- /** The auto-pause notice: the sentence, then how to resume. No buttons. */
117
+ /** The auto-pause notice: the failed emoji and the sentence, then how to resume. No buttons. */
83
118
  export declare function jobPausedMessage(notice: JobPausedNotice): OutgoingMessage;
119
+ /** The first line of a job's final notice: `Job ended: "<title>"`. */
120
+ export declare function jobEndedTitle(notice: JobEndedNotice): string;
121
+ /** The body of a job's final notice: why it ended, then its last run with its verdict, or its first error line. */
122
+ export declare function jobEndedBody(notice: JobEndedNotice, last: TaskRecord<unknown>): string;
123
+ /** A job's final notice: the ended emoji, the title line and the body. No buttons. */
124
+ export declare function jobEndedMessage(notice: JobEndedNotice, last: TaskRecord<unknown>): OutgoingMessage;
84
125
  /** A clean window starting. No buttons. */
85
126
  export declare function cleanWindowMessage(window: CleanWindowEvent, now?: Date): OutgoingMessage;
86
127
  /**
@@ -119,9 +160,10 @@ export declare function laterMenuMessage(record: TaskRecord<unknown>, options: r
119
160
  /** Split text into parts of at most `max` characters, preferring line breaks. */
120
161
  export declare function splitMessage(text: string, max?: number): string[];
121
162
  /**
122
- * `/result` and the Result button (R27): no result text for a redacted
123
- * task; otherwise the result in parts of 4096 characters, at most
124
- * {@link RESULT_MAX_PARTS}, then a pointer to `tidegap queue show`.
163
+ * `/result` and the Result button (R27): no result text and no file for a
164
+ * redacted task; otherwise the result in parts of 4096 characters, at most
165
+ * {@link RESULT_MAX_PARTS}, then a pointer to `tidegap queue show`; the
166
+ * run's sendable files go after the last part.
125
167
  */
126
168
  export declare function resultMessages(record: TaskRecord<unknown>): OutgoingMessage[];
127
169
  /** `/later` grammar (KTD15), quoted by `/help` and the reset-time reply. */
@@ -18,8 +18,8 @@
18
18
  * | not ready | none |
19
19
  * | replies and `/result` | none |
20
20
  */
21
- import { displayTitle, stripControlChars, taskActions, taskResultText } from "../history.js";
22
- import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason } from "../jobs.js";
21
+ import { displayTitle, formatBytes, isRedactedTask, sendableAttachments, stripControlChars, taskActions, taskAttachments, taskAttachmentsSkipped, taskResultText, taskSummaryError, taskSummaryText, } from "../history.js";
22
+ import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason, jobEndText } from "../jobs.js";
23
23
  import { clip, firstErrorLine, oneLine } from "../notify.js";
24
24
  import { localTimeLabel } from "../postpone.js";
25
25
  import { problemLine, TICKER_CODES } from "../readiness.js";
@@ -27,8 +27,13 @@ import { isValidTimeZone } from "../zone-time.js";
27
27
  import { redactPrompt } from "../redact.js";
28
28
  import { freshReasonText, shortSessionId } from "../run-session.js";
29
29
  import { TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX } from "./telegram.js";
30
+ import { cutPreview, NOTICE_EMOJI, NOTICE_VERDICT_CHARS, stripBidiControls, structureSummary } from "./notice.js";
30
31
  /** Characters of result text a done message previews (Q4). */
31
32
  export const TELEGRAM_PREVIEW_CHARS = 600;
33
+ /** Longest `📎` line: with the title, the time and a full preview, a notice still fits the smallest body cap (Pushover, 1024). */
34
+ export const ATTACHMENT_LINE_CHARS = 300;
35
+ /** Most characters of the verdict a job's notice leads with. */
36
+ const VERDICT_CHARS = NOTICE_VERDICT_CHARS;
32
37
  /** Most messages one `/result` sends before pointing to `tidegap queue show`. */
33
38
  export const RESULT_MAX_PARTS = 4;
34
39
  /** Tasks one `/queue` lists. */
@@ -52,45 +57,81 @@ export function callbackFits(taskId) {
52
57
  /** The decoding tables, for `parseCallback`. */
53
58
  export const CALLBACK_ACTIONS = Object.fromEntries(Object.entries(ACTION_CODE).map(([name, code]) => [code, name]));
54
59
  export const CALLBACK_PRESETS = Object.fromEntries(Object.entries(PRESET_CODE).map(([preset, code]) => [code, preset]));
55
- /** True when the task asked for receipt redaction (`redactInReceipt` with patterns): no result text leaves the machine. */
56
- export function isRedactedTask(record) {
57
- try {
58
- const spec = JSON.parse(record.bodyJson ?? "");
59
- return Array.isArray(spec.redactInReceipt) && spec.redactInReceipt.length > 0;
60
- }
61
- catch {
62
- return false;
63
- }
64
- }
65
60
  /**
66
61
  * The one-line preview of a run, the same on the jobs page and in the
67
62
  * digest (KTD6): a failed task's first error line with visible text, a
68
- * completed task's result text unless it redacts its receipt, else
69
- * undefined. Default-redacted, control characters removed, whitespace runs
70
- * joined; a longer text is cut to `maxChars - 1` code points plus "…", so
71
- * the result never exceeds `maxChars`.
63
+ * completed task's summary, or its result text without one, unless it
64
+ * redacts its receipt, else undefined. Default-redacted, control characters
65
+ * removed, whitespace runs joined; a longer text is cut to `maxChars - 1`
66
+ * code points plus "…", so the result never exceeds `maxChars`.
72
67
  */
73
68
  export function runPreview(record, maxChars) {
74
69
  let text;
75
70
  if (record.status === "failed")
76
71
  text = firstErrorLine(record.error, Infinity);
77
72
  else if (record.status === "completed" && !isRedactedTask(record))
78
- text = oneLine(taskResultText(record) ?? "");
73
+ text = oneLine(taskSummaryText(record) ?? taskResultText(record) ?? "");
79
74
  return text ? cutPreview(text, maxChars) : undefined;
80
75
  }
81
- /** `text` cut to `maxChars - 1` code points plus "…" when longer, so it never exceeds `maxChars` (KTD6). */
82
- export function cutPreview(text, maxChars) {
83
- const chars = Array.from(text);
84
- return chars.length > maxChars ? `${chars.slice(0, maxChars - 1).join("")}…` : text;
76
+ /**
77
+ * A run's summary in the notice shape, or undefined when the run has no
78
+ * usable summary: it failed, it redacts its receipt, it has no summary, or
79
+ * the summary has no verdict. The summary is default-redacted first.
80
+ */
81
+ export function runSummary(record) {
82
+ if (record.status !== "completed" || isRedactedTask(record))
83
+ return undefined;
84
+ const summary = taskSummaryText(record);
85
+ if (!summary)
86
+ return undefined;
87
+ const structured = structureSummary(redactPrompt(summary, undefined));
88
+ return structured.verdict ? structured : undefined;
89
+ }
90
+ /**
91
+ * The status of a job run's notice: `failed` for a failed run; for a
92
+ * completed run, the status word of its usable summary, else `done`. A
93
+ * final notice is `ended`, which the caller sets.
94
+ */
95
+ export function noticeStatus(record) {
96
+ if (record.status === "failed")
97
+ return "failed";
98
+ return runSummary(record)?.status ?? "done";
99
+ }
100
+ /** The first line of `text` with visible text, made one line (default-redacted, no bidirectional controls), or undefined. */
101
+ function firstVisibleLine(text) {
102
+ for (const line of (text ?? "").split(/\r?\n/)) {
103
+ const one = stripBidiControls(oneLine(line)).trim();
104
+ if (one)
105
+ return one;
106
+ }
107
+ return undefined;
108
+ }
109
+ /**
110
+ * A run's verdict, the one line a person reads first: for a completed run
111
+ * that does not redact its receipt, the verdict of its summary without the
112
+ * status word, else the first line of its result text; for a failed run,
113
+ * its first error line. Cut to `maxChars`; undefined when there is no such line.
114
+ */
115
+ export function runVerdict(record, maxChars = VERDICT_CHARS) {
116
+ let line;
117
+ if (record.status === "failed")
118
+ line = firstErrorLine(record.error, Infinity);
119
+ else if (record.status === "completed" && !isRedactedTask(record))
120
+ line = runSummary(record)?.verdict ?? firstVisibleLine(taskResultText(record));
121
+ return line ? cutPreview(line, maxChars) : undefined;
85
122
  }
86
123
  /** The title a message shows: `displayTitle`, one line, at most 80 characters, else the task id. */
87
124
  export function messageTitle(record) {
88
125
  const t = stripControlChars(displayTitle(record) ?? "").trim();
89
126
  return t ? clip(t, 80) : record.taskId;
90
127
  }
91
- /** Result text safe to send: default-redacted, control characters removed, newlines kept. */
128
+ /** Text safe to send: default-redacted, control characters removed, newlines kept. */
129
+ function safeText(text) {
130
+ return stripControlChars(redactPrompt(text ?? "", undefined), { multiline: true }).trim();
131
+ }
132
+ /** Result text safe to send. */
92
133
  function safeResult(record) {
93
- return stripControlChars(redactPrompt(taskResultText(record) ?? "", undefined), { multiline: true }).trim();
134
+ return safeText(taskResultText(record));
94
135
  }
95
136
  function showCommand(record) {
96
137
  return `tidegap queue show ${record.taskId}`;
@@ -116,9 +157,9 @@ function runSessionLine(record) {
116
157
  const where = dir ? ` (${stripControlChars(dir)})` : "";
117
158
  return origin ? `Ran in a copy of session ${shortSessionId(origin)}${where}` : `Ran in a copy of its session${where}`;
118
159
  }
119
- /** A job's title as a message shows it (one line, at most 80 characters), or undefined when blank. */
160
+ /** A job's title as a message shows it (one line, no bidirectional controls, at most 80 characters), or undefined when blank. */
120
161
  function cleanJobTitle(title) {
121
- const t = stripControlChars(title ?? "").trim();
162
+ const t = stripBidiControls(stripControlChars(title ?? "")).trim();
122
163
  return t ? clip(t, 80) : undefined;
123
164
  }
124
165
  /** The title a task event's message shows: the job's title for a job occurrence, else {@link messageTitle}. */
@@ -126,39 +167,106 @@ export function eventTitle(record, jobTitle) {
126
167
  return cleanJobTitle(jobTitle) ?? messageTitle(record);
127
168
  }
128
169
  /**
129
- * Task done (R26): title, time, where it ran, the preview or the redaction
130
- * note, and a [Result] button. A job occurrence (`jobTitle`) leads with
131
- * `<job title>: <result>` (jobs R22).
170
+ * The body of a job run's notice: with a usable summary, one `• ` line per
171
+ * bullet, cut to {@link TELEGRAM_PREVIEW_CHARS}; else the raw output after
172
+ * its first visible line (the whole raw preview when that line was cut),
173
+ * clipped to {@link TELEGRAM_PREVIEW_CHARS}; "" when there is nothing more.
174
+ */
175
+ function jobDoneBody(record) {
176
+ const summary = runSummary(record);
177
+ if (summary)
178
+ return cutPreview(summary.bullets.map((b) => `• ${b}`).join("\n"), TELEGRAM_PREVIEW_CHARS);
179
+ const result = safeResult(record);
180
+ const lines = result.split(/\r?\n/);
181
+ const first = lines.findIndex((line) => oneLine(line) !== "");
182
+ if (first < 0)
183
+ return "";
184
+ if (Array.from(oneLine(lines[first])).length > VERDICT_CHARS)
185
+ return clip(result, TELEGRAM_PREVIEW_CHARS);
186
+ return clip(lines.slice(first + 1).join("\n").trim(), TELEGRAM_PREVIEW_CHARS);
187
+ }
188
+ /**
189
+ * The line that names a run's attachments: `📎 funnel.png (48 KB), weekly.csv
190
+ * (2 KB), not attached: huge.png (over 10 MB)`. A redacted task names no
191
+ * file: `📎 2 files, not sent: this task redacts its receipt`. Undefined
192
+ * when the run has none.
193
+ */
194
+ export function attachmentLine(record) {
195
+ const stored = taskAttachments(record);
196
+ if (isRedactedTask(record)) {
197
+ const n = stored.length;
198
+ return n > 0 ? `📎 ${n} ${n === 1 ? "file" : "files"}, not sent: this task redacts its receipt` : undefined;
199
+ }
200
+ const skipped = taskAttachmentsSkipped(record);
201
+ const parts = stored.map((a) => `${a.name} (${formatBytes(a.bytes)})`);
202
+ if (skipped.length > 0)
203
+ parts.push(`not attached: ${skipped.map((s) => `${s.name} (${s.reason})`).join(", ")}`);
204
+ return parts.length > 0 ? cutPreview(`📎 ${parts.join(", ")}`, ATTACHMENT_LINE_CHARS) : undefined;
205
+ }
206
+ /** The files a message about `record` sends after its text, or undefined. */
207
+ function messageFiles(record) {
208
+ const attachments = sendableAttachments(record);
209
+ return attachments.length > 0 ? { files: { taskId: record.taskId, attachments } } : {};
210
+ }
211
+ /**
212
+ * Task done (R26): title, time, the attachments line, where it ran, the
213
+ * preview or the redaction note, and a [Result] button with the raw result;
214
+ * the run's sendable files go with it. A job occurrence
215
+ * (`jobTitle`) leads with `<status emoji> <job title> — <verdict>`, adds the job's next run
216
+ * (`jobNext`) to the time line, a `No summary` line when its summarize step
217
+ * failed, and shows its summary in place of the raw preview.
132
218
  */
133
- export function taskDoneMessage(record, now = new Date(), jobTitle) {
219
+ export function taskDoneMessage(record, now = new Date(), jobTitle, jobNext) {
134
220
  const job = cleanJobTitle(jobTitle);
135
221
  const redacted = isRedactedTask(record);
136
- const preview = redacted ? "" : clip(safeResult(record), TELEGRAM_PREVIEW_CHARS);
137
- const lines = [job ? `${job}: ${preview ? clip(preview.replace(/\s+/g, " "), 200) : "done"}` : `Done: ${messageTitle(record)}`];
138
222
  const at = when(record.completedAt, now);
139
- if (at)
140
- lines.push(`Finished ${at}`);
223
+ const lines = [];
224
+ let body = "";
225
+ if (job) {
226
+ lines.push(`${NOTICE_EMOJI[noticeStatus(record)]} ${job} — ${runVerdict(record) ?? "done"}`);
227
+ const next = jobNext && jobNext !== JOB_RUNNING_NOW ? `next ${jobNext}` : undefined;
228
+ const time = [at && `Finished ${at}`, next].filter(Boolean).join(" · ");
229
+ if (time)
230
+ lines.push(time);
231
+ }
232
+ else {
233
+ lines.push(`Done: ${messageTitle(record)}`);
234
+ if (at)
235
+ lines.push(`Finished ${at}`);
236
+ }
237
+ const files = attachmentLine(record);
238
+ if (files)
239
+ lines.push(files);
141
240
  const ran = runSessionLine(record);
142
241
  if (ran)
143
242
  lines.push(ran);
243
+ if (job && !redacted) {
244
+ const failed = firstErrorLine(taskSummaryError(record), Infinity);
245
+ if (failed)
246
+ lines.push(`No summary: ${cutPreview(failed, VERDICT_CHARS)}`);
247
+ body = jobDoneBody(record);
248
+ }
249
+ else if (!redacted) {
250
+ body = clip(safeResult(record), TELEGRAM_PREVIEW_CHARS);
251
+ }
144
252
  if (redacted) {
145
253
  lines.push("", `The result is not sent here: this task redacts its receipt. Run \`${showCommand(record)}\`.`);
146
254
  }
147
- else if (preview && (!job || preview.length > 200 || /\n/.test(preview))) {
148
- lines.push("", preview);
255
+ else if (body) {
256
+ lines.push("", body);
149
257
  }
150
258
  const buttons = callbackFits(record.taskId) ? [[{ text: "Result", data: encodeCallback("result", record.taskId) }]] : undefined;
151
- return { text: lines.join("\n"), ...(buttons ? { buttons } : {}) };
259
+ return { text: lines.join("\n"), ...(buttons ? { buttons } : {}), ...messageFiles(record) };
152
260
  }
153
261
  /** The first error line with visible text (notify's firstErrorLine), at most `max` characters, or "unknown error". */
154
262
  const errorLine = (error, max = 300) => firstErrorLine(error, max) ?? "unknown error";
155
263
  /**
156
264
  * Task failed: title, time, the first error line, the show command. No
157
- * buttons. A job occurrence (`jobTitle`) leads with `<job title>: failed`.
265
+ * buttons. A job occurrence (`jobTitle`) leads with `❌ <job title>: failed`.
158
266
  */
159
267
  export function taskFailedMessage(record, now = new Date(), jobTitle) {
160
268
  const job = cleanJobTitle(jobTitle);
161
- const lines = [job ? `${job}: failed` : `Failed: ${messageTitle(record)}`];
269
+ const lines = [job ? `${NOTICE_EMOJI.failed} ${job}: failed` : `Failed: ${messageTitle(record)}`];
162
270
  const at = when(record.completedAt, now);
163
271
  if (at)
164
272
  lines.push(`Failed ${at}`);
@@ -171,9 +279,23 @@ export function jobPausedTitle(notice) {
171
279
  const title = cleanJobTitle(notice.title) ?? notice.jobId;
172
280
  return `job '${title}' paused after ${JOB_AUTO_PAUSE_FAILURES} failures: ${errorLine(notice.reason, 200)}`;
173
281
  }
174
- /** The auto-pause notice: the sentence, then how to resume. No buttons. */
282
+ /** The auto-pause notice: the failed emoji and the sentence, then how to resume. No buttons. */
175
283
  export function jobPausedMessage(notice) {
176
- return { text: `${jobPausedTitle(notice)}\nResume it: tidegap jobs resume ${notice.jobId}` };
284
+ return { text: `${NOTICE_EMOJI.failed} ${jobPausedTitle(notice)}\nResume it: tidegap jobs resume ${notice.jobId}` };
285
+ }
286
+ /** The first line of a job's final notice: `Job ended: "<title>"`. */
287
+ export function jobEndedTitle(notice) {
288
+ return `Job ended: "${cleanJobTitle(notice.title) ?? notice.jobId}"`;
289
+ }
290
+ /** The body of a job's final notice: why it ended, then its last run with its verdict, or its first error line. */
291
+ export function jobEndedBody(notice, last) {
292
+ const title = cleanJobTitle(notice.title) ?? notice.jobId;
293
+ const verdict = runVerdict(last);
294
+ return `"${title}" ended: ${jobEndText(notice.reason, notice.until)}.\nLast run: ${last.taskId} ${notice.lastOutcome}${verdict ? `: ${verdict}` : "."}`;
295
+ }
296
+ /** A job's final notice: the ended emoji, the title line and the body. No buttons. */
297
+ export function jobEndedMessage(notice, last) {
298
+ return { text: `${NOTICE_EMOJI.ended} ${jobEndedTitle(notice)}\n${jobEndedBody(notice, last)}` };
177
299
  }
178
300
  /** A clean window starting. No buttons. */
179
301
  export function cleanWindowMessage(window, now = new Date()) {
@@ -199,8 +321,12 @@ export function notReadyMessage(problems, recovered = false) {
199
321
  export function eventMessage(event, now = new Date()) {
200
322
  switch (event.kind) {
201
323
  case "task_done":
202
- return taskDoneMessage(event.task, now, event.jobTitle);
324
+ if (event.jobEnded)
325
+ return jobEndedMessage(event.jobEnded, event.task);
326
+ return taskDoneMessage(event.task, now, event.jobTitle, event.jobNext);
203
327
  case "task_failed":
328
+ if (event.jobEnded)
329
+ return jobEndedMessage(event.jobEnded, event.task);
204
330
  return event.jobPaused ? jobPausedMessage(event.jobPaused) : taskFailedMessage(event.task, now, event.jobTitle);
205
331
  case "clean_window":
206
332
  return cleanWindowMessage(event.window, now);
@@ -367,9 +493,10 @@ export function splitMessage(text, max = TELEGRAM_MESSAGE_MAX) {
367
493
  return parts;
368
494
  }
369
495
  /**
370
- * `/result` and the Result button (R27): no result text for a redacted
371
- * task; otherwise the result in parts of 4096 characters, at most
372
- * {@link RESULT_MAX_PARTS}, then a pointer to `tidegap queue show`.
496
+ * `/result` and the Result button (R27): no result text and no file for a
497
+ * redacted task; otherwise the result in parts of 4096 characters, at most
498
+ * {@link RESULT_MAX_PARTS}, then a pointer to `tidegap queue show`; the
499
+ * run's sendable files go after the last part.
373
500
  */
374
501
  export function resultMessages(record) {
375
502
  const title = messageTitle(record);
@@ -380,14 +507,17 @@ export function resultMessages(record) {
380
507
  return [{ text: `${title} is ${record.status}; it has no result.` }];
381
508
  }
382
509
  const body = safeResult(record);
510
+ const out = [];
383
511
  if (!body)
384
- return [{ text: `${title}\nThe result is empty.` }];
385
- const max = TELEGRAM_MESSAGE_MAX - 100;
386
- const parts = splitMessage(body, max);
387
- const out = parts.slice(0, RESULT_MAX_PARTS).map((p) => ({ text: p }));
388
- out[0] = { text: `${title}\n\n${out[0].text}` };
389
- if (parts.length > RESULT_MAX_PARTS)
390
- out.push({ text: `The result is longer. Run \`${showCommand(record)}\` for the rest.` });
512
+ out.push({ text: `${title}\nThe result is empty.` });
513
+ else {
514
+ const parts = splitMessage(body, TELEGRAM_MESSAGE_MAX - 100);
515
+ out.push(...parts.slice(0, RESULT_MAX_PARTS).map((p) => ({ text: p })));
516
+ out[0] = { text: `${title}\n\n${out[0].text}` };
517
+ if (parts.length > RESULT_MAX_PARTS)
518
+ out.push({ text: `The result is longer. Run \`${showCommand(record)}\` for the rest.` });
519
+ }
520
+ out[out.length - 1] = { ...out[out.length - 1], ...messageFiles(record) };
391
521
  return out;
392
522
  }
393
523
  /** `/later` grammar (KTD15), quoted by `/help` and the reset-time reply. */
@@ -11,5 +11,6 @@ export { PUSHOVER_MESSAGES_PATH } from "./kinds/pushover.js";
11
11
  export { isLoopbackSmtpHost } from "./kinds/email.js";
12
12
  export * from "./telegram.js";
13
13
  export * from "./format.js";
14
+ export * from "./notice.js";
14
15
  export * from "./commands.js";
15
16
  //# sourceMappingURL=index.d.ts.map
@@ -11,5 +11,6 @@ export { PUSHOVER_MESSAGES_PATH } from "./kinds/pushover.js";
11
11
  export { isLoopbackSmtpHost } from "./kinds/email.js";
12
12
  export * from "./telegram.js";
13
13
  export * from "./format.js";
14
+ export * from "./notice.js";
14
15
  export * from "./commands.js";
15
16
  //# sourceMappingURL=index.js.map
@@ -4,7 +4,7 @@
4
4
  * neither link nor ping (KTD2). Sent with `?wait=true`, so Discord answers
5
5
  * only after it accepted the message.
6
6
  */
7
- import { clipEscaped, escapeChars, LEVEL_COLOR, LOOPBACK_URL } from "./shared.js";
7
+ import { clipEscaped, escapeChars, LEVEL_COLOR, LOOPBACK_URL, statusTitle } from "./shared.js";
8
8
  /** Discord's caps on an embed's title and description. */
9
9
  export const DISCORD_TITLE_MAX = 256;
10
10
  export const DISCORD_DESCRIPTION_MAX = 4096;
@@ -15,7 +15,7 @@ export function discordBody(payload) {
15
15
  username: "Tidegap",
16
16
  embeds: [
17
17
  {
18
- title: clipEscaped(escapeChars(payload.title, SPECIALS), DISCORD_TITLE_MAX),
18
+ title: clipEscaped(escapeChars(statusTitle(payload), SPECIALS), DISCORD_TITLE_MAX),
19
19
  description: clipEscaped(escapeChars(payload.text, SPECIALS), DISCORD_DESCRIPTION_MAX),
20
20
  color: LEVEL_COLOR[payload.level],
21
21
  timestamp: payload.at,
@@ -9,6 +9,7 @@
9
9
  * turned off password SMTP for them on 2024-09-16 and they need OAuth,
10
10
  * which would need a Tidegap-owned client id (R20).
11
11
  */
12
+ import { statusTitle } from "./shared.js";
12
13
  /** A plain `local@domain` address: no spaces, CR, LF, `<`, `>`, quotes, commas or semicolons. */
13
14
  export const EMAIL_ADDRESS = String.raw `[^\s<>@,;"]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+`;
14
15
  const WHOLE_ADDRESS = new RegExp(`^(?:${EMAIL_ADDRESS})$`);
@@ -154,7 +155,7 @@ export const email = {
154
155
  ...(password ? { user, password } : {}),
155
156
  from,
156
157
  to: String(values.to || from),
157
- subject: headerLine(`Tidegap: ${payload.title}`),
158
+ subject: headerLine(`Tidegap: ${statusTitle(payload)}`),
158
159
  text: payload.text,
159
160
  };
160
161
  },
@@ -14,6 +14,14 @@ export const NTFY_MAX_BODY_BYTES = 4000;
14
14
  const PRIORITY = { task_failed: 4, not_ready: 4, task_done: 3, test: 3, clean_window: 2, digest: 2 };
15
15
  /** ntfy emoji tags per level (`x` shows ❌). */
16
16
  const TAGS = { success: "white_check_mark", error: "x", warning: "warning", info: "information_source" };
17
+ /** ntfy emoji tags per job notice status, in place of the level's. */
18
+ const STATUS_TAGS = {
19
+ ok: "white_check_mark",
20
+ attention: "warning",
21
+ done: "ballot_box_with_check",
22
+ failed: "x",
23
+ ended: "checkered_flag",
24
+ };
17
25
  /** The header value of `text`: as is when printable ASCII, else an RFC 2047 base64 encoded word. */
18
26
  export function headerText(text) {
19
27
  if (/^[\x20-\x7e]*$/.test(text))
@@ -153,7 +161,7 @@ export const ntfy = {
153
161
  "Content-Type": "text/plain; charset=utf-8",
154
162
  Title: headerText(payload.title),
155
163
  Priority: String(ntfyPriority(payload, values.priority)),
156
- Tags: TAGS[payload.level],
164
+ Tags: payload.status ? STATUS_TAGS[payload.status] : TAGS[payload.level],
157
165
  ...(token ? { Authorization: `Bearer ${token}` } : {}),
158
166
  },
159
167
  body: clipBytes(payload.text, NTFY_MAX_BODY_BYTES),
@@ -5,6 +5,8 @@
5
5
  * loopback test server (`TIDEGAP_PUSHOVER_API_BASE`, KTD8), never anywhere
6
6
  * else. Pushover shows plain text, so nothing is escaped.
7
7
  */
8
+ import { cutPreview } from "../notice.js";
9
+ import { statusTitle } from "./shared.js";
8
10
  const PUSHOVER_API_BASE = "https://api.pushover.net";
9
11
  export const PUSHOVER_MESSAGES_PATH = "/1/messages.json";
10
12
  /** Pushover's limits: message 1,024 characters, title 250. */
@@ -12,7 +14,6 @@ const PUSHOVER_MAX_MESSAGE = 1024;
12
14
  const PUSHOVER_MAX_TITLE = 250;
13
15
  /** Priority per event: summaries and clean windows quiet (-1), the rest normal (0). */
14
16
  const PRIORITY = { task_failed: 0, not_ready: 0, task_done: 0, test: 0, clean_window: -1, digest: -1 };
15
- const clip = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
16
17
  /** Pushover user keys and application tokens: 30 letters and digits. */
17
18
  const KEY = "[A-Za-z0-9]{30}";
18
19
  export const pushover = {
@@ -60,8 +61,8 @@ export const pushover = {
60
61
  const body = new URLSearchParams({
61
62
  token: String(values.app_token),
62
63
  user: String(values.user_key),
63
- title: clip(payload.title, PUSHOVER_MAX_TITLE),
64
- message: clip(payload.text, PUSHOVER_MAX_MESSAGE),
64
+ title: cutPreview(statusTitle(payload), PUSHOVER_MAX_TITLE),
65
+ message: cutPreview(payload.text, PUSHOVER_MAX_MESSAGE),
65
66
  priority: String(PRIORITY[payload.event]),
66
67
  ...(Number.isFinite(at) ? { timestamp: String(at) } : {}),
67
68
  });
@@ -1,4 +1,7 @@
1
- /** Helpers the chat kinds share: the loopback URL the test sinks use, escaping of untrusted text (KTD2). */
1
+ /** Helpers the chat kinds share: the loopback URL the test sinks use, escaping of untrusted text (KTD2), the status title. */
2
+ import type { NotificationPayload } from "../payload.js";
3
+ /** The payload title with the notice status emoji before it, for a job's task events; the title as is otherwise. */
4
+ export declare function statusTitle(payload: Pick<NotificationPayload, "title" | "status">): string;
2
5
  /**
3
6
  * Pattern source of a loopback http(s) URL. Kinds with a fixed official host
4
7
  * (Slack, Discord) also accept it, so the fake sinks of the tests and the QA