@tidegap/core 0.22.0 → 0.24.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 (40) hide show
  1. package/dist/channels/commands.js +3 -2
  2. package/dist/channels/digest.d.ts +4 -1
  3. package/dist/channels/digest.js +6 -2
  4. package/dist/channels/format.d.ts +44 -19
  5. package/dist/channels/format.js +113 -77
  6. package/dist/channels/index.d.ts +1 -0
  7. package/dist/channels/index.js +1 -0
  8. package/dist/channels/kinds/discord.js +2 -2
  9. package/dist/channels/kinds/email.js +2 -1
  10. package/dist/channels/kinds/ntfy.js +9 -1
  11. package/dist/channels/kinds/pushover.js +4 -3
  12. package/dist/channels/kinds/shared.d.ts +4 -1
  13. package/dist/channels/kinds/shared.js +6 -1
  14. package/dist/channels/kinds/slack.js +2 -2
  15. package/dist/channels/notice.d.ts +42 -0
  16. package/dist/channels/notice.js +142 -0
  17. package/dist/channels/payload.d.ts +3 -0
  18. package/dist/channels/payload.js +16 -5
  19. package/dist/channels/telegram.d.ts +31 -1
  20. package/dist/channels/telegram.js +34 -12
  21. package/dist/history.d.ts +101 -0
  22. package/dist/history.js +95 -0
  23. package/dist/index.d.ts +8 -6
  24. package/dist/index.js +6 -4
  25. package/dist/jobs.d.ts +53 -5
  26. package/dist/jobs.js +279 -42
  27. package/dist/notice-language.d.ts +37 -0
  28. package/dist/notice-language.js +67 -0
  29. package/dist/providers/base.d.ts +7 -0
  30. package/dist/redact.d.ts +3 -2
  31. package/dist/redact.js +8 -2
  32. package/dist/schedule-job.d.ts +3 -2
  33. package/dist/schedule-job.js +6 -5
  34. package/dist/scheduler.d.ts +9 -1
  35. package/dist/scheduler.js +13 -5
  36. package/dist/storage/sqlite.js +7 -3
  37. package/dist/types.d.ts +14 -1
  38. package/dist/zone-time.d.ts +2 -0
  39. package/dist/zone-time.js +11 -0
  40. package/package.json +2 -2
@@ -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
@@ -1,4 +1,9 @@
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 { NOTICE_EMOJI } from "../notice.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 function statusTitle(payload) {
5
+ return payload.status ? `${NOTICE_EMOJI[payload.status]} ${payload.title}` : payload.title;
6
+ }
2
7
  /**
3
8
  * Pattern source of a loopback http(s) URL. Kinds with a fixed official host
4
9
  * (Slack, Discord) also accept it, so the fake sinks of the tests and the QA
@@ -1,9 +1,9 @@
1
1
  /** Slack (R12): an Incoming Webhook of a Slack app. `text` plus one mrkdwn section block; `&<>` escaped (KTD2). */
2
- import { clipEscaped, escapeAngle, LOOPBACK_URL } from "./shared.js";
2
+ import { clipEscaped, escapeAngle, LOOPBACK_URL, statusTitle } from "./shared.js";
3
3
  /** Slack's cap on a section block's text. */
4
4
  export const SLACK_SECTION_MAX = 3000;
5
5
  export function slackBody(payload) {
6
- const title = escapeAngle(payload.title);
6
+ const title = escapeAngle(statusTitle(payload));
7
7
  const text = escapeAngle(payload.text);
8
8
  return JSON.stringify({
9
9
  text,
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The status of a job notice and the shape of its summary. The status
3
+ * emoji comes from one fixed map, never from model output: a summary's
4
+ * status is a word from a closed set, and pictographs a model writes at the
5
+ * start of a line are removed. `structureSummary` takes whatever the model
6
+ * returned (a paragraph, markdown, a numbered list, the requested shape) and
7
+ * gives one shape: a verdict and at most four short lines. Pure: the
8
+ * run-level helpers (`runSummary`, `noticeStatus`) live in `format.ts`.
9
+ */
10
+ /** The status a job notice shows: judged fine, judged to need a look, completed without a judgment, failed, or ended. */
11
+ export type NoticeStatus = "ok" | "attention" | "done" | "failed" | "ended";
12
+ /** The emoji line 1 of a job notice starts with, per status. */
13
+ export declare const NOTICE_EMOJI: Readonly<Record<NoticeStatus, string>>;
14
+ /** Most characters (code points) of a summary's verdict. */
15
+ export declare const NOTICE_VERDICT_CHARS = 120;
16
+ /** Most lines below the verdict. */
17
+ export declare const NOTICE_BULLETS_MAX = 4;
18
+ /** Most characters (code points) of one line below the verdict. */
19
+ export declare const NOTICE_BULLET_CHARS = 200;
20
+ /** A summary in the notice shape. `status` only when the reply led with a status word. */
21
+ export interface StructuredSummary {
22
+ status?: "ok" | "attention";
23
+ /** "" when the reply had no usable text: the notice then shows the raw output. */
24
+ verdict: string;
25
+ bullets: string[];
26
+ }
27
+ /** `text` cut to `maxChars - 1` code points plus "…" when longer, so it never exceeds `maxChars` (KTD6). */
28
+ export declare function cutPreview(text: string, maxChars: number): string;
29
+ /** `text` without bidirectional controls, for a line shown beside the status emoji. */
30
+ export declare function stripBidiControls(text: string): string;
31
+ /**
32
+ * A summary in the notice shape. Never fails and never trusts the shape:
33
+ * the first line with text is the verdict, a leading `OK` or `ATTENTION`
34
+ * is its status word, later marked lines are bullets (an unmarked line
35
+ * joins the bullet before it), and a paragraph without marks gives one
36
+ * bullet per sentence. The verdict is cut at {@link NOTICE_VERDICT_CHARS}
37
+ * and the rest of its line becomes the first bullet; bullets are cut at
38
+ * {@link NOTICE_BULLET_CHARS}, and past {@link NOTICE_BULLETS_MAX} the last
39
+ * line kept is `…`.
40
+ */
41
+ export declare function structureSummary(text: string): StructuredSummary;
42
+ //# sourceMappingURL=notice.d.ts.map
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The status of a job notice and the shape of its summary. The status
3
+ * emoji comes from one fixed map, never from model output: a summary's
4
+ * status is a word from a closed set, and pictographs a model writes at the
5
+ * start of a line are removed. `structureSummary` takes whatever the model
6
+ * returned (a paragraph, markdown, a numbered list, the requested shape) and
7
+ * gives one shape: a verdict and at most four short lines. Pure: the
8
+ * run-level helpers (`runSummary`, `noticeStatus`) live in `format.ts`.
9
+ */
10
+ /** The emoji line 1 of a job notice starts with, per status. */
11
+ export const NOTICE_EMOJI = {
12
+ ok: "✅",
13
+ attention: "⚠️",
14
+ done: "☑️",
15
+ failed: "❌",
16
+ ended: "🏁",
17
+ };
18
+ /** Most characters (code points) of a summary's verdict. */
19
+ export const NOTICE_VERDICT_CHARS = 120;
20
+ /** Most lines below the verdict. */
21
+ export const NOTICE_BULLETS_MAX = 4;
22
+ /** Most characters (code points) of one line below the verdict. */
23
+ export const NOTICE_BULLET_CHARS = 200;
24
+ /** `text` cut to `maxChars - 1` code points plus "…" when longer, so it never exceeds `maxChars` (KTD6). */
25
+ export function cutPreview(text, maxChars) {
26
+ const chars = Array.from(text);
27
+ return chars.length > maxChars ? `${chars.slice(0, maxChars - 1).join("")}…` : text;
28
+ }
29
+ /** Most characters (code points) of a reply `structureSummary` reads, and of one line of it: the caps need far less, and the regexes stay linear in practice. */
30
+ const SUMMARY_INPUT_CHARS = 8000;
31
+ const SUMMARY_LINE_CHARS = 2000;
32
+ /** Bidirectional controls: they can reorder the rest of a line on screen. */
33
+ const BIDI_CONTROLS = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
34
+ /** Whitespace that is a control character: a space, so words stay apart. */
35
+ const CONTROL_SPACE = /[\t\v\f\r\u0085]/g;
36
+ /** Control and format characters, and the blank fillers (Hangul, braille) that look like nothing. */
37
+ const INVISIBLE = /[\p{Cc}\p{Cf}\u115F\u1160\u2800\u3164\uFFA0]/gu;
38
+ const LEADING_PICTOGRAPHS = /^(?:[\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}⃣︎️]|\s)+/u;
39
+ const FENCE = /^\s*(```|~~~)/;
40
+ const RULE = /^\s*([-*_]\s*){3,}$/;
41
+ const TABLE_RULE = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/;
42
+ const HEADING = /^\s*#{1,6}(\s+|$)/;
43
+ const LIST_MARK = /^\s*(?:[-*•–]|\d{1,3}[.)])(?:\s+|$)/;
44
+ // A hyphen or a period after the word needs a space after it: `OK-ish` and `Attention-grabbing` are words, not a status.
45
+ const STATUS_WORD = /^\[?(ok|attention)\]?(?:\s*[:—–]|\s*[-.](?=\s|$)|\s*$)\s*/i;
46
+ const SENTENCE_END = /(?<=[.!?…])\s+|(?<=[。!?])/;
47
+ /** `text` without bidirectional controls, for a line shown beside the status emoji. */
48
+ export function stripBidiControls(text) {
49
+ return text.replace(BIDI_CONTROLS, "");
50
+ }
51
+ /** The first `max` code points of `text`, without an ellipsis. */
52
+ function headChars(text, max) {
53
+ return text.length <= max ? text : Array.from(text.slice(0, max * 2)).slice(0, max).join("");
54
+ }
55
+ /** One line without control and format characters, markdown emphasis, quote marks or leading pictographs; links as `text (url)`. */
56
+ function cleanLine(line) {
57
+ return line
58
+ .replace(CONTROL_SPACE, " ")
59
+ .replace(INVISIBLE, "")
60
+ .replace(/\*\*|__|`/g, "")
61
+ .replace(/^\s*(>\s*)+/, "")
62
+ .replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, "$1 ($2)")
63
+ .replace(LEADING_PICTOGRAPHS, "")
64
+ .replace(/\s+/g, " ")
65
+ .trim();
66
+ }
67
+ /**
68
+ * A summary in the notice shape. Never fails and never trusts the shape:
69
+ * the first line with text is the verdict, a leading `OK` or `ATTENTION`
70
+ * is its status word, later marked lines are bullets (an unmarked line
71
+ * joins the bullet before it), and a paragraph without marks gives one
72
+ * bullet per sentence. The verdict is cut at {@link NOTICE_VERDICT_CHARS}
73
+ * and the rest of its line becomes the first bullet; bullets are cut at
74
+ * {@link NOTICE_BULLET_CHARS}, and past {@link NOTICE_BULLETS_MAX} the last
75
+ * line kept is `…`.
76
+ */
77
+ export function structureSummary(text) {
78
+ let status;
79
+ let verdictLine;
80
+ let statusSeen = false;
81
+ const parts = [];
82
+ let open;
83
+ for (const full of headChars(text, SUMMARY_INPUT_CHARS).split(/\r?\n/)) {
84
+ const raw = headChars(full, SUMMARY_LINE_CHARS);
85
+ if (FENCE.test(raw) || TABLE_RULE.test(raw) || RULE.test(raw))
86
+ continue;
87
+ const heading = HEADING.test(raw);
88
+ if (heading && verdictLine !== undefined)
89
+ continue;
90
+ let line = cleanLine(raw.replace(HEADING, ""));
91
+ if (!line) {
92
+ open = undefined;
93
+ continue;
94
+ }
95
+ const marked = LIST_MARK.test(line);
96
+ if (marked)
97
+ line = cleanLine(line.replace(LIST_MARK, ""));
98
+ if (!line)
99
+ continue;
100
+ if (verdictLine === undefined) {
101
+ const word = statusSeen ? null : STATUS_WORD.exec(line);
102
+ if (word) {
103
+ statusSeen = true;
104
+ status = word[1].toLowerCase();
105
+ line = cleanLine(line.slice(word[0].length));
106
+ if (!line)
107
+ continue;
108
+ }
109
+ verdictLine = line;
110
+ continue;
111
+ }
112
+ if (marked || !open) {
113
+ open = { text: line, marked };
114
+ parts.push(open);
115
+ }
116
+ else {
117
+ open.text = `${open.text} ${line}`;
118
+ }
119
+ }
120
+ if (verdictLine === undefined)
121
+ return { verdict: "", bullets: [] };
122
+ const verdictChars = Array.from(verdictLine);
123
+ const verdict = cutPreview(verdictLine, NOTICE_VERDICT_CHARS);
124
+ const lines = [];
125
+ if (verdictChars.length > NOTICE_VERDICT_CHARS)
126
+ lines.push(verdictChars.slice(NOTICE_VERDICT_CHARS - 1).join("").trim());
127
+ for (const part of parts) {
128
+ if (lines.length > NOTICE_BULLETS_MAX)
129
+ break;
130
+ if (part.marked)
131
+ lines.push(part.text);
132
+ else
133
+ for (const sentence of part.text.split(SENTENCE_END))
134
+ if (sentence.trim())
135
+ lines.push(sentence.trim());
136
+ }
137
+ const bullets = lines.map((l) => cutPreview(l, NOTICE_BULLET_CHARS));
138
+ if (bullets.length > NOTICE_BULLETS_MAX)
139
+ bullets.splice(NOTICE_BULLETS_MAX - 1, Infinity, "…");
140
+ return { ...(status ? { status } : {}), verdict, bullets };
141
+ }
142
+ //# sourceMappingURL=notice.js.map
@@ -5,6 +5,7 @@
5
5
  * plain text: a `format` for a receiver that renders markup escapes them.
6
6
  */
7
7
  import type { TaskStatus } from "../types.js";
8
+ import type { NoticeStatus } from "./notice.js";
8
9
  import type { ChannelEvent, EventKind } from "./types.js";
9
10
  export type NotificationLevel = "info" | "success" | "warning" | "error";
10
11
  /** A payload's event: an {@link EventKind}, or `test` for the message a Connect or Send test sends. */
@@ -24,6 +25,8 @@ export interface NotificationPayload {
24
25
  status: TaskStatus;
25
26
  grams?: number;
26
27
  };
28
+ /** On a job's task events only: the notice status; a kind shows its emoji beside the title. */
29
+ status?: NoticeStatus;
27
30
  /** On `not_ready` only: the tick daemon runs again after a sent alert ("running again"). */
28
31
  recovered?: true;
29
32
  }
@@ -4,7 +4,14 @@
4
4
  * redaction and the 600-character preview. Title and text are untrusted
5
5
  * plain text: a `format` for a receiver that renders markup escapes them.
6
6
  */
7
- import { eventMessage, eventTitle, jobEndedTitle, jobPausedTitle } from "./format.js";
7
+ import { eventMessage, eventTitle, jobEndedTitle, jobPausedTitle, noticeStatus } from "./format.js";
8
+ /** The word a job run's payload title ends with, per status. */
9
+ const STATUS_WORD = {
10
+ ok: "ok",
11
+ attention: "needs a look",
12
+ done: "done",
13
+ failed: "failed",
14
+ };
8
15
  const LEVEL = {
9
16
  task_done: "success",
10
17
  task_failed: "error",
@@ -38,16 +45,20 @@ export function payloadFor(event, now = new Date()) {
38
45
  const title = eventTitle(record, event.jobTitle);
39
46
  const grams = record.receipt?.actualCarbonGCo2 ?? record.receipt?.estimatedCarbonGCo2;
40
47
  const done = event.kind === "task_done";
48
+ const paused = event.kind === "task_failed" ? event.jobPaused : undefined;
49
+ const job = event.jobEnded !== undefined || paused !== undefined || event.jobTitle !== undefined;
50
+ const status = event.jobEnded ? "ended" : paused ? "failed" : job ? noticeStatus(record) : undefined;
41
51
  const head = event.jobEnded
42
52
  ? jobEndedTitle(event.jobEnded)
43
- : event.kind === "task_failed" && event.jobPaused
44
- ? jobPausedTitle(event.jobPaused)
45
- : event.jobTitle
46
- ? `${title}: ${done ? "done" : "failed"}`
53
+ : paused
54
+ ? jobPausedTitle(paused)
55
+ : status && status !== "ended"
56
+ ? `${title}: ${STATUS_WORD[status]}`
47
57
  : `${done ? "Done" : "Failed"}: ${title}`;
48
58
  return {
49
59
  ...base,
50
60
  title: head,
61
+ ...(status ? { status } : {}),
51
62
  at: validIso(record.completedAt) ?? now.toISOString(),
52
63
  task: { id: record.taskId, title, status: record.status, ...(typeof grams === "number" && Number.isFinite(grams) ? { grams } : {}) },
53
64
  };
@@ -13,6 +13,8 @@ export declare const TELEGRAM_API_BASE = "https://api.telegram.org";
13
13
  export declare const TELEGRAM_MESSAGE_MAX = 4096;
14
14
  /** Longest wait for one Bot API call beyond its long-poll `timeout`, in ms. */
15
15
  export declare const TELEGRAM_CALL_TIMEOUT_MS = 30000;
16
+ /** Longest one file upload may take: a 10 MB file on a slow link needs more than a call. */
17
+ export declare const TELEGRAM_UPLOAD_TIMEOUT_MS = 120000;
16
18
  /** Telegram's cap on a button's `callback_data`, in bytes. */
17
19
  export declare const TELEGRAM_CALLBACK_MAX_BYTES = 64;
18
20
  export interface TelegramChat {
@@ -60,10 +62,30 @@ export declare class TelegramError extends Error {
60
62
  readonly status?: number | undefined;
61
63
  /** Seconds Telegram asked to wait (429). */
62
64
  readonly retryAfterS?: number | undefined;
65
+ /**
66
+ * Telegram may have done the call: the time limit ended it (the
67
+ * request may have reached Telegram), or Telegram answered 2xx with a
68
+ * body that is not `ok`. A message sent this way may have arrived.
69
+ */
70
+ readonly maybeDelivered: boolean;
63
71
  name: string;
64
72
  constructor(message: string, kind: TelegramErrorKind, method: string, status?: number | undefined,
65
73
  /** Seconds Telegram asked to wait (429). */
66
- retryAfterS?: number | undefined);
74
+ retryAfterS?: number | undefined,
75
+ /**
76
+ * Telegram may have done the call: the time limit ended it (the
77
+ * request may have reached Telegram), or Telegram answered 2xx with a
78
+ * body that is not `ok`. A message sent this way may have arrived.
79
+ */
80
+ maybeDelivered?: boolean);
81
+ }
82
+ /** The Bot API methods that upload a file. */
83
+ export type TelegramFileMethod = "sendPhoto" | "sendDocument";
84
+ /** A file to upload: its bytes, its type, and the file name Telegram shows. */
85
+ export interface TelegramUpload {
86
+ bytes: Uint8Array;
87
+ type: string;
88
+ filename: string;
67
89
  }
68
90
  export interface TelegramClientOptions {
69
91
  token: string;
@@ -86,6 +108,8 @@ export declare class TelegramClient {
86
108
  * the tick or the listener.
87
109
  */
88
110
  call<T>(method: string, body?: Record<string, unknown>, signal?: AbortSignal): Promise<T>;
111
+ /** One POST to a Bot API method, with the timeout, abort and error mapping every call shares. */
112
+ private post;
89
113
  getMe(): Promise<TelegramUser>;
90
114
  getWebhookInfo(): Promise<{
91
115
  url: string;
@@ -100,6 +124,12 @@ export declare class TelegramClient {
100
124
  sendMessage(chatId: number | string, text: string, opts?: {
101
125
  buttons?: InlineKeyboard;
102
126
  }): Promise<TelegramMessage>;
127
+ /**
128
+ * Upload one file as a photo (`sendPhoto`) or a document (`sendDocument`),
129
+ * multipart, with a plain caption (no `parse_mode`). The same host and
130
+ * errors as {@link call}; the time limit is {@link TELEGRAM_UPLOAD_TIMEOUT_MS}.
131
+ */
132
+ sendFile(method: TelegramFileMethod, chatId: number | string, file: TelegramUpload, caption: string): Promise<TelegramMessage>;
103
133
  answerCallbackQuery(id: string, opts?: {
104
134
  text?: string;
105
135
  showAlert?: boolean;
@@ -13,6 +13,8 @@ export const TELEGRAM_API_BASE = "https://api.telegram.org";
13
13
  export const TELEGRAM_MESSAGE_MAX = 4096;
14
14
  /** Longest wait for one Bot API call beyond its long-poll `timeout`, in ms. */
15
15
  export const TELEGRAM_CALL_TIMEOUT_MS = 30_000;
16
+ /** Longest one file upload may take: a 10 MB file on a slow link needs more than a call. */
17
+ export const TELEGRAM_UPLOAD_TIMEOUT_MS = 120_000;
16
18
  /** Telegram's cap on a button's `callback_data`, in bytes. */
17
19
  export const TELEGRAM_CALLBACK_MAX_BYTES = 64;
18
20
  export class TelegramError extends Error {
@@ -20,15 +22,23 @@ export class TelegramError extends Error {
20
22
  method;
21
23
  status;
22
24
  retryAfterS;
25
+ maybeDelivered;
23
26
  name = "TelegramError";
24
27
  constructor(message, kind, method, status,
25
28
  /** Seconds Telegram asked to wait (429). */
26
- retryAfterS) {
29
+ retryAfterS,
30
+ /**
31
+ * Telegram may have done the call: the time limit ended it (the
32
+ * request may have reached Telegram), or Telegram answered 2xx with a
33
+ * body that is not `ok`. A message sent this way may have arrived.
34
+ */
35
+ maybeDelivered = false) {
27
36
  super(message);
28
37
  this.kind = kind;
29
38
  this.method = method;
30
39
  this.status = status;
31
40
  this.retryAfterS = retryAfterS;
41
+ this.maybeDelivered = maybeDelivered;
32
42
  }
33
43
  }
34
44
  /** True for an `http://127.0.0.1[:port]` or `http://localhost[:port]` base (KTD13: tests and QA only). */
@@ -65,15 +75,19 @@ export class TelegramClient {
65
75
  * {@link TELEGRAM_CALL_TIMEOUT_MS}, so a stalled connection cannot hold
66
76
  * the tick or the listener.
67
77
  */
68
- async call(method, body = {}, signal) {
69
- const f = this.fetchFn ?? globalThis.fetch;
78
+ call(method, body = {}, signal) {
70
79
  const pollS = typeof body.timeout === "number" ? body.timeout : 0;
80
+ return this.post(method, { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }, pollS * 1000 + TELEGRAM_CALL_TIMEOUT_MS, signal);
81
+ }
82
+ /** One POST to a Bot API method, with the timeout, abort and error mapping every call shares. */
83
+ async post(method, init, timeoutMs, signal) {
84
+ const f = this.fetchFn ?? globalThis.fetch;
71
85
  const controller = new AbortController();
72
86
  let timedOut = false;
73
87
  const timer = setTimeout(() => {
74
88
  timedOut = true;
75
89
  controller.abort();
76
- }, pollS * 1000 + TELEGRAM_CALL_TIMEOUT_MS);
90
+ }, timeoutMs);
77
91
  const forward = () => controller.abort();
78
92
  if (signal?.aborted)
79
93
  controller.abort();
@@ -83,18 +97,13 @@ export class TelegramClient {
83
97
  let env = {};
84
98
  try {
85
99
  try {
86
- res = await f(`${this.base}/bot${this.token}/${method}`, {
87
- method: "POST",
88
- headers: { "content-type": "application/json" },
89
- body: JSON.stringify(body),
90
- signal: controller.signal,
91
- });
100
+ res = await f(`${this.base}/bot${this.token}/${method}`, { method: "POST", ...init, signal: controller.signal });
92
101
  }
93
102
  catch (err) {
94
103
  const code = err?.cause?.code;
95
104
  const why = typeof code === "string" && /^[A-Z_]+$/.test(code) ? ` (${code})` : "";
96
105
  if (timedOut)
97
- throw new TelegramError(`Telegram ${method}: timed out`, "network", method);
106
+ throw new TelegramError(`Telegram ${method}: timed out`, "network", method, undefined, undefined, true);
98
107
  if (err?.name === "AbortError") {
99
108
  throw new TelegramError(`Telegram ${method}: aborted`, "network", method);
100
109
  }
@@ -121,7 +130,7 @@ export class TelegramClient {
121
130
  throw new TelegramError(msg, "conflict", method, status);
122
131
  if (status === 429)
123
132
  throw new TelegramError(msg, "rate_limited", method, status, env.parameters?.retry_after);
124
- throw new TelegramError(msg, res.ok ? "api" : "http", method, status);
133
+ throw new TelegramError(msg, res.ok ? "api" : "http", method, status, undefined, res.ok);
125
134
  }
126
135
  return env.result;
127
136
  }
@@ -145,6 +154,19 @@ export class TelegramClient {
145
154
  body.reply_markup = keyboardMarkup(opts.buttons);
146
155
  return this.call("sendMessage", body);
147
156
  }
157
+ /**
158
+ * Upload one file as a photo (`sendPhoto`) or a document (`sendDocument`),
159
+ * multipart, with a plain caption (no `parse_mode`). The same host and
160
+ * errors as {@link call}; the time limit is {@link TELEGRAM_UPLOAD_TIMEOUT_MS}.
161
+ */
162
+ sendFile(method, chatId, file, caption) {
163
+ const form = new FormData();
164
+ form.append("chat_id", String(chatId));
165
+ form.append("caption", caption);
166
+ const field = method === "sendPhoto" ? "photo" : "document";
167
+ form.append(field, new Blob([file.bytes], { type: file.type }), file.filename);
168
+ return this.post(method, { body: form }, TELEGRAM_UPLOAD_TIMEOUT_MS);
169
+ }
148
170
  answerCallbackQuery(id, opts = {}) {
149
171
  const body = { callback_query_id: id };
150
172
  if (opts.text)
package/dist/history.d.ts CHANGED
@@ -116,4 +116,105 @@ export declare function shellQuote(word: string): string;
116
116
  * session id is valid.
117
117
  */
118
118
  export declare function resumeCommand(record: Pick<TaskRecord<unknown>, "originCwd" | "originSessionId">): string | undefined;
119
+ /** True when the task asked for receipt redaction (`redactInReceipt` with patterns): no result text and no attachment leaves the machine. */
120
+ export declare function isRedactedTask(record: TaskRecord<unknown>): boolean;
121
+ /**
122
+ * The file types a command run can attach: the stored extension, a label for
123
+ * people, whether Telegram takes it as a photo, and whether the page shows
124
+ * it inline (an SVG can hold script, so it is a download).
125
+ */
126
+ export declare const ATTACHMENT_TYPES: {
127
+ readonly "image/png": {
128
+ readonly ext: "png";
129
+ readonly label: "PNG image";
130
+ readonly photo: true;
131
+ readonly inline: true;
132
+ };
133
+ readonly "image/jpeg": {
134
+ readonly ext: "jpg";
135
+ readonly label: "JPEG image";
136
+ readonly photo: true;
137
+ readonly inline: true;
138
+ };
139
+ readonly "image/webp": {
140
+ readonly ext: "webp";
141
+ readonly label: "WebP image";
142
+ readonly photo: true;
143
+ readonly inline: true;
144
+ };
145
+ readonly "image/gif": {
146
+ readonly ext: "gif";
147
+ readonly label: "GIF image";
148
+ readonly photo: false;
149
+ readonly inline: true;
150
+ };
151
+ readonly "application/pdf": {
152
+ readonly ext: "pdf";
153
+ readonly label: "PDF";
154
+ readonly photo: false;
155
+ readonly inline: false;
156
+ };
157
+ readonly "text/csv": {
158
+ readonly ext: "csv";
159
+ readonly label: "CSV";
160
+ readonly photo: false;
161
+ readonly inline: false;
162
+ };
163
+ readonly "text/plain": {
164
+ readonly ext: "txt";
165
+ readonly label: "text";
166
+ readonly photo: false;
167
+ readonly inline: false;
168
+ };
169
+ readonly "application/json": {
170
+ readonly ext: "json";
171
+ readonly label: "JSON";
172
+ readonly photo: false;
173
+ readonly inline: false;
174
+ };
175
+ readonly "image/svg+xml": {
176
+ readonly ext: "svg";
177
+ readonly label: "SVG image";
178
+ readonly photo: false;
179
+ readonly inline: false;
180
+ };
181
+ };
182
+ export type AttachmentType = keyof typeof ATTACHMENT_TYPES;
183
+ /** One stored attachment of a run, as the result JSON holds it: `file` is `<n>.<ext>` in the task's attachment folder. */
184
+ export interface StoredAttachment {
185
+ name: string;
186
+ type: AttachmentType;
187
+ bytes: number;
188
+ file: string;
189
+ }
190
+ /** A file the command wrote that was not attached, and why. */
191
+ export interface SkippedAttachment {
192
+ name: string;
193
+ reason: string;
194
+ }
195
+ /** A stored attachment as a reader sees it: its 1-based index, and `expired` when its file is gone. */
196
+ export interface TaskAttachment extends StoredAttachment {
197
+ index: number;
198
+ expired?: boolean;
199
+ }
200
+ /** A file name for people: one line, no control, bidirectional or zero-width characters, whitespace runs joined, at most 80 characters; "" when nothing is left. */
201
+ export declare function attachmentDisplayName(name: string): string;
202
+ /**
203
+ * The stored attachments of a completed run, in order. An entry whose shape
204
+ * is wrong is left out; its `file` must be `<index>.<ext>` of its type, so
205
+ * a reader never builds a path from anything else. With `exists` (whether
206
+ * a `file` is still in the task's attachment folder), a file that is gone is
207
+ * marked `expired`.
208
+ */
209
+ export declare function taskAttachments(record: TaskRecord<unknown>, exists?: (file: string) => boolean): TaskAttachment[];
210
+ /** The files a completed run wrote that were not attached, with the reason. */
211
+ export declare function taskAttachmentsSkipped(record: TaskRecord<unknown>): SkippedAttachment[];
212
+ /**
213
+ * The attachments a channel may send: none for a task that redacts its
214
+ * receipt, else the stored ones whose file is still there (with `exists`).
215
+ * Every path that sends a file takes its list from here.
216
+ */
217
+ export declare function sendableAttachments(record: TaskRecord<unknown>, exists?: (file: string) => boolean): TaskAttachment[];
218
+ /** A size for people: `512 B`, `48 KB`, `14 MB`, `1.5 MB`. */
219
+ export declare function formatBytes(bytes: number): string;
119
220
  //# sourceMappingURL=history.d.ts.map
package/dist/history.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * Task-visibility helpers (v0.17): title derivation, message history and
3
3
  * display text. Pure functions; no I/O.
4
4
  */
5
+ import { cutPreview, stripBidiControls } from "./channels/notice.js";
5
6
  import { redactPrompt } from "./redact.js";
6
7
  /** Maximum stored title length, in characters. */
7
8
  export const TITLE_MAX_CHARS = 80;
@@ -215,4 +216,98 @@ export function resumeCommand(record) {
215
216
  const cwd = stripControlChars(record.originCwd);
216
217
  return `cd ${shellQuote(cwd)} && claude --resume ${record.originSessionId}`;
217
218
  }
219
+ /** True when the task asked for receipt redaction (`redactInReceipt` with patterns): no result text and no attachment leaves the machine. */
220
+ export function isRedactedTask(record) {
221
+ const spec = parseSpec(record.bodyJson);
222
+ return Array.isArray(spec?.redactInReceipt) && spec.redactInReceipt.length > 0;
223
+ }
224
+ /**
225
+ * The file types a command run can attach: the stored extension, a label for
226
+ * people, whether Telegram takes it as a photo, and whether the page shows
227
+ * it inline (an SVG can hold script, so it is a download).
228
+ */
229
+ export const ATTACHMENT_TYPES = {
230
+ "image/png": { ext: "png", label: "PNG image", photo: true, inline: true },
231
+ "image/jpeg": { ext: "jpg", label: "JPEG image", photo: true, inline: true },
232
+ "image/webp": { ext: "webp", label: "WebP image", photo: true, inline: true },
233
+ "image/gif": { ext: "gif", label: "GIF image", photo: false, inline: true },
234
+ "application/pdf": { ext: "pdf", label: "PDF", photo: false, inline: false },
235
+ "text/csv": { ext: "csv", label: "CSV", photo: false, inline: false },
236
+ "text/plain": { ext: "txt", label: "text", photo: false, inline: false },
237
+ "application/json": { ext: "json", label: "JSON", photo: false, inline: false },
238
+ "image/svg+xml": { ext: "svg", label: "SVG image", photo: false, inline: false },
239
+ };
240
+ /** Zero-width characters: a name that holds them can pass for another. */
241
+ const ZERO_WIDTH = /[\u200B-\u200D\u2060\uFEFF]/g;
242
+ /** A file name for people: one line, no control, bidirectional or zero-width characters, whitespace runs joined, at most 80 characters; "" when nothing is left. */
243
+ export function attachmentDisplayName(name) {
244
+ return cutPreview(stripBidiControls(stripControlChars(name)).replace(ZERO_WIDTH, "").replace(/\s+/g, " ").trim(), TITLE_MAX_CHARS);
245
+ }
246
+ function attachmentName(value) {
247
+ return typeof value === "string" ? attachmentDisplayName(value) || undefined : undefined;
248
+ }
249
+ function resultList(record, key) {
250
+ const r = record.result;
251
+ const v = r && typeof r === "object" ? r[key] : undefined;
252
+ return Array.isArray(v) ? v : [];
253
+ }
254
+ /**
255
+ * The stored attachments of a completed run, in order. An entry whose shape
256
+ * is wrong is left out; its `file` must be `<index>.<ext>` of its type, so
257
+ * a reader never builds a path from anything else. With `exists` (whether
258
+ * a `file` is still in the task's attachment folder), a file that is gone is
259
+ * marked `expired`.
260
+ */
261
+ export function taskAttachments(record, exists) {
262
+ if (record.status !== "completed")
263
+ return [];
264
+ const out = [];
265
+ resultList(record, "attachments").forEach((raw, i) => {
266
+ const a = raw;
267
+ const name = attachmentName(a?.name);
268
+ const type = a?.type;
269
+ if (!a || !name || typeof type !== "string" || !Object.hasOwn(ATTACHMENT_TYPES, type))
270
+ return;
271
+ const index = i + 1;
272
+ const file = `${index}.${ATTACHMENT_TYPES[type].ext}`;
273
+ if (a.file !== file || typeof a.bytes !== "number" || !Number.isSafeInteger(a.bytes) || a.bytes < 0)
274
+ return;
275
+ const expired = exists !== undefined && !exists(file);
276
+ out.push({ name, type: type, bytes: a.bytes, file, index, ...(expired ? { expired: true } : {}) });
277
+ });
278
+ return out;
279
+ }
280
+ /** The files a completed run wrote that were not attached, with the reason. */
281
+ export function taskAttachmentsSkipped(record) {
282
+ if (record.status !== "completed")
283
+ return [];
284
+ const out = [];
285
+ for (const raw of resultList(record, "attachmentsSkipped")) {
286
+ const s = raw;
287
+ const name = attachmentName(s?.name);
288
+ const reason = attachmentName(s?.reason);
289
+ if (name && reason)
290
+ out.push({ name, reason });
291
+ }
292
+ return out;
293
+ }
294
+ /**
295
+ * The attachments a channel may send: none for a task that redacts its
296
+ * receipt, else the stored ones whose file is still there (with `exists`).
297
+ * Every path that sends a file takes its list from here.
298
+ */
299
+ export function sendableAttachments(record, exists) {
300
+ if (isRedactedTask(record))
301
+ return [];
302
+ return taskAttachments(record, exists).filter((a) => !a.expired);
303
+ }
304
+ /** A size for people: `512 B`, `48 KB`, `14 MB`, `1.5 MB`. */
305
+ export function formatBytes(bytes) {
306
+ if (bytes < 1024)
307
+ return `${bytes} B`;
308
+ // Below 1 MB but rounding to 1024 KB reads as `1 MB`.
309
+ if (Math.round(bytes / 1024) < 1024)
310
+ return `${Math.round(bytes / 1024)} KB`;
311
+ return `${(Math.round((bytes / (1024 * 1024)) * 10) / 10).toString()} MB`;
312
+ }
218
313
  //# sourceMappingURL=history.js.map