@tidegap/core 0.19.0 → 0.20.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 (167) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +127 -0
  11. package/dist/channels/format.js +407 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +77 -0
  51. package/dist/energy.js +131 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +152 -0
  55. package/dist/handoff.js +430 -0
  56. package/dist/history.d.ts +2 -0
  57. package/dist/history.js +3 -1
  58. package/dist/index.d.ts +43 -13
  59. package/dist/index.js +32 -6
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +173 -0
  63. package/dist/jobs.js +794 -0
  64. package/dist/notify.d.ts +2 -0
  65. package/dist/notify.js +2 -1
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +7 -3
  69. package/dist/providers/base.d.ts +113 -1
  70. package/dist/providers/base.js +15 -0
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +1 -0
  77. package/dist/providers/gemini.js +27 -20
  78. package/dist/providers/index.d.ts +2 -2
  79. package/dist/providers/index.js +1 -1
  80. package/dist/providers/ollama.d.ts +1 -0
  81. package/dist/providers/ollama.js +26 -22
  82. package/dist/providers/openai.js +5 -5
  83. package/dist/providers/timeout.d.ts +18 -0
  84. package/dist/providers/timeout.js +33 -0
  85. package/dist/quota.d.ts +7 -2
  86. package/dist/quota.js +12 -27
  87. package/dist/readiness.d.ts +169 -0
  88. package/dist/readiness.js +254 -0
  89. package/dist/redact.d.ts +42 -0
  90. package/dist/redact.js +110 -0
  91. package/dist/region-host.d.ts +30 -0
  92. package/dist/region-host.js +69 -0
  93. package/dist/region.d.ts +102 -20
  94. package/dist/region.js +175 -23
  95. package/dist/run-session.d.ts +36 -0
  96. package/dist/run-session.js +72 -0
  97. package/dist/schedule-job.d.ts +95 -0
  98. package/dist/schedule-job.js +195 -0
  99. package/dist/scheduler.d.ts +245 -14
  100. package/dist/scheduler.js +919 -109
  101. package/dist/sign.d.ts +8 -1
  102. package/dist/sign.js +49 -3
  103. package/dist/storage/sqlite.d.ts +157 -5
  104. package/dist/storage/sqlite.js +661 -20
  105. package/dist/task-events.d.ts +102 -0
  106. package/dist/task-events.js +308 -0
  107. package/dist/tool-surface.d.ts +31 -2
  108. package/dist/tool-surface.js +359 -65
  109. package/dist/types.d.ts +246 -3
  110. package/dist/types.js +8 -1
  111. package/dist/zone-time.d.ts +22 -0
  112. package/dist/zone-time.js +76 -0
  113. package/package.json +10 -5
  114. package/dist/aggregator.d.ts.map +0 -1
  115. package/dist/aggregator.js.map +0 -1
  116. package/dist/budget.d.ts.map +0 -1
  117. package/dist/budget.js.map +0 -1
  118. package/dist/data/tables.generated.d.ts.map +0 -1
  119. package/dist/data/tables.generated.js.map +0 -1
  120. package/dist/energy.d.ts.map +0 -1
  121. package/dist/energy.js.map +0 -1
  122. package/dist/grid.d.ts.map +0 -1
  123. package/dist/grid.js.map +0 -1
  124. package/dist/history.d.ts.map +0 -1
  125. package/dist/history.js.map +0 -1
  126. package/dist/index.d.ts.map +0 -1
  127. package/dist/index.js.map +0 -1
  128. package/dist/notify.d.ts.map +0 -1
  129. package/dist/notify.js.map +0 -1
  130. package/dist/paths.d.ts.map +0 -1
  131. package/dist/paths.js.map +0 -1
  132. package/dist/providers/anthropic.d.ts.map +0 -1
  133. package/dist/providers/anthropic.js.map +0 -1
  134. package/dist/providers/base.d.ts.map +0 -1
  135. package/dist/providers/base.js.map +0 -1
  136. package/dist/providers/defaults.d.ts.map +0 -1
  137. package/dist/providers/defaults.js.map +0 -1
  138. package/dist/providers/gemini.d.ts.map +0 -1
  139. package/dist/providers/gemini.js.map +0 -1
  140. package/dist/providers/index.d.ts.map +0 -1
  141. package/dist/providers/index.js.map +0 -1
  142. package/dist/providers/ollama.d.ts.map +0 -1
  143. package/dist/providers/ollama.js.map +0 -1
  144. package/dist/providers/openai.d.ts.map +0 -1
  145. package/dist/providers/openai.js.map +0 -1
  146. package/dist/quota.d.ts.map +0 -1
  147. package/dist/quota.js.map +0 -1
  148. package/dist/recommend.d.ts.map +0 -1
  149. package/dist/recommend.js.map +0 -1
  150. package/dist/redact.d.ts.map +0 -1
  151. package/dist/redact.js.map +0 -1
  152. package/dist/region.d.ts.map +0 -1
  153. package/dist/region.js.map +0 -1
  154. package/dist/routing.d.ts.map +0 -1
  155. package/dist/routing.js.map +0 -1
  156. package/dist/scheduler.d.ts.map +0 -1
  157. package/dist/scheduler.js.map +0 -1
  158. package/dist/select-window.d.ts.map +0 -1
  159. package/dist/select-window.js.map +0 -1
  160. package/dist/sign.d.ts.map +0 -1
  161. package/dist/sign.js.map +0 -1
  162. package/dist/storage/sqlite.d.ts.map +0 -1
  163. package/dist/storage/sqlite.js.map +0 -1
  164. package/dist/tool-surface.d.ts.map +0 -1
  165. package/dist/tool-surface.js.map +0 -1
  166. package/dist/types.d.ts.map +0 -1
  167. package/dist/types.js.map +0 -1
@@ -0,0 +1,57 @@
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";
3
+ /** Slack's cap on a section block's text. */
4
+ export const SLACK_SECTION_MAX = 3000;
5
+ export function slackBody(payload) {
6
+ const title = escapeAngle(payload.title);
7
+ const text = escapeAngle(payload.text);
8
+ return JSON.stringify({
9
+ text,
10
+ blocks: [{ type: "section", text: { type: "mrkdwn", text: clipEscaped(`*${title}*\n${text}`, SLACK_SECTION_MAX) } }],
11
+ });
12
+ }
13
+ const SLACK_URL_TEXT = "Slack did not accept this URL. Create a new webhook in Slack and paste it again.";
14
+ const SLACK_GONE_TEXT = "Slack removed this webhook. Add a new one in your Slack app and paste it here.";
15
+ const SLACK_ARCHIVED_TEXT = "The Slack channel of this webhook is archived. Add a webhook for another channel and paste it here.";
16
+ const SLACK_FORMAT_TEXT = "Slack refused the message format. Update Tidegap and try again.";
17
+ export const slack = {
18
+ kind: "slack",
19
+ label: "Slack",
20
+ description: "Messages in a Slack channel through an Incoming Webhook.",
21
+ ready: true,
22
+ fields: [
23
+ {
24
+ name: "url",
25
+ label: "Webhook URL",
26
+ input: "url",
27
+ required: true,
28
+ secret: true,
29
+ placeholder: "https://hooks.slack.com/services/T…/B…/…",
30
+ pattern: String.raw `https://hooks\.slack\.com/services/[A-Za-z0-9_/-]+|${LOOPBACK_URL}`,
31
+ invalid: "Paste the Incoming Webhook URL. It starts with https://hooks.slack.com/services/.",
32
+ },
33
+ ],
34
+ steps: [
35
+ { text: "Open your Slack apps and create one: Create New App → From scratch.", link: "https://api.slack.com/apps" },
36
+ { text: "Open Incoming Webhooks and turn them on." },
37
+ { text: "Add New Webhook, then pick the channel for Tidegap messages." },
38
+ { text: "Copy the webhook URL, paste it here and press Connect." },
39
+ ],
40
+ defaultEvents: ["task_done", "task_failed", "not_ready"],
41
+ docsAnchor: "notify-slack",
42
+ errors: {
43
+ auth: { text: SLACK_URL_TEXT, field: "url" },
44
+ http_404: { text: SLACK_GONE_TEXT, field: "url" },
45
+ http_410: { text: SLACK_ARCHIVED_TEXT, field: "url" },
46
+ http_400: { text: SLACK_FORMAT_TEXT },
47
+ slack_payload: { text: SLACK_FORMAT_TEXT },
48
+ slack_webhook_gone: { text: SLACK_GONE_TEXT, field: "url" },
49
+ slack_channel_not_found: { text: "The Slack channel of this webhook no longer exists. Add a webhook for another channel and paste it here.", field: "url" },
50
+ slack_channel_archived: { text: SLACK_ARCHIVED_TEXT, field: "url" },
51
+ slack_action_prohibited: { text: "A Slack admin restricted posting to this channel. Ask the admin, or add a webhook for another channel.", field: "url" },
52
+ },
53
+ format(payload, values) {
54
+ return { type: "http", method: "POST", url: String(values.url), headers: { "Content-Type": "application/json" }, body: slackBody(payload) };
55
+ },
56
+ };
57
+ //# sourceMappingURL=slack.js.map
@@ -0,0 +1,4 @@
1
+ /** Telegram (coherence KTD10 to KTD15). Sends through `TelegramClient`, not a `format` (KTD3); the bot token stays in the env file (Q2). */
2
+ import type { KindDescriptor } from "../registry.js";
3
+ export declare const telegram: KindDescriptor;
4
+ //# sourceMappingURL=telegram.d.ts.map
@@ -0,0 +1,26 @@
1
+ /** Telegram (coherence KTD10 to KTD15). Sends through `TelegramClient`, not a `format` (KTD3); the bot token stays in the env file (Q2). */
2
+ export const telegram = {
3
+ kind: "telegram",
4
+ label: "Telegram",
5
+ description: "Messages from your own bot, with buttons to run, postpone or cancel tasks.",
6
+ ready: true,
7
+ fields: [
8
+ {
9
+ name: "bot_token",
10
+ label: "Bot token",
11
+ input: "password",
12
+ required: true,
13
+ secret: true,
14
+ pattern: "\\d{5,12}:[A-Za-z0-9_-]{30,50}",
15
+ placeholder: "123456789:AA…",
16
+ },
17
+ ],
18
+ steps: [
19
+ { text: "Open @BotFather in Telegram.", link: "https://t.me/BotFather" },
20
+ { text: "Send /newbot and pick a name. Use a new bot for Tidegap only." },
21
+ { text: "Copy the token it sends and paste it here." },
22
+ ],
23
+ defaultEvents: ["task_done", "task_failed", "clean_window", "not_ready"],
24
+ docsAnchor: "notify-telegram",
25
+ };
26
+ //# sourceMappingURL=telegram.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Generic webhook (R11, R13, KTD2, KTD13): a POST to any URL the user owns.
3
+ * Three bodies: the Tidegap JSON (`tidegap`, raw text), a plain `{"text"}`
4
+ * (Google Chat, Mattermost, Matrix hookshot) and a Microsoft Teams Adaptive
5
+ * Card (`teams`, the Workflows "Post to a channel when a webhook request is
6
+ * received" template). Optional HMAC signing and custom header lines.
7
+ */
8
+ import type { KindDescriptor } from "../registry.js";
9
+ import type { NotificationPayload } from "../payload.js";
10
+ /** Bumped only when the Tidegap JSON body changes shape, so receivers can pin it. */
11
+ export declare const WEBHOOK_BODY_VERSION = 1;
12
+ declare const FORMATS: readonly ["tidegap", "text", "teams"];
13
+ export type WebhookFormat = (typeof FORMATS)[number];
14
+ /** The `tidegap` format body: the payload, raw, plus `version`. */
15
+ export declare function webhookBody(payload: NotificationPayload): string;
16
+ /** Most header lines (KTD13). */
17
+ export declare const MAX_HEADER_LINES = 10;
18
+ export declare const HEADERS_TEXT = "Write one \"Name: value\" per line, at most 10. Host, Content-Length, Content-Type, Transfer-Encoding, Connection and X-Tidegap-* are set by Tidegap.";
19
+ /** The `headers` field as a map, or undefined when a line breaks a KTD13 rule. Empty lines are skipped. */
20
+ export declare function parseHeaders(text: string): Record<string, string> | undefined;
21
+ /** A Teams Workflows message with one Adaptive Card 1.4: the title in bold, then the text. */
22
+ export declare function teamsBody(payload: NotificationPayload): string;
23
+ /**
24
+ * Webhook hosts shared by many receivers, where the path names the receiver:
25
+ * a signing secret or headers typed for one path never follow a new path.
26
+ */
27
+ export declare const WEBHOOK_PATH_HOSTS: readonly string[];
28
+ export declare const webhook: KindDescriptor;
29
+ export {};
30
+ //# sourceMappingURL=webhook.d.ts.map
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Generic webhook (R11, R13, KTD2, KTD13): a POST to any URL the user owns.
3
+ * Three bodies: the Tidegap JSON (`tidegap`, raw text), a plain `{"text"}`
4
+ * (Google Chat, Mattermost, Matrix hookshot) and a Microsoft Teams Adaptive
5
+ * Card (`teams`, the Workflows "Post to a channel when a webhook request is
6
+ * received" template). Optional HMAC signing and custom header lines.
7
+ */
8
+ import { defuseMentions, escapeAngle, escapeChars, optString } from "./shared.js";
9
+ /** Bumped only when the Tidegap JSON body changes shape, so receivers can pin it. */
10
+ export const WEBHOOK_BODY_VERSION = 1;
11
+ const FORMATS = ["tidegap", "text", "teams"];
12
+ function formatOf(v) {
13
+ return FORMATS.find((f) => f === v) ?? "tidegap";
14
+ }
15
+ /** The `tidegap` format body: the payload, raw, plus `version`. */
16
+ export function webhookBody(payload) {
17
+ const { event, level, title, text, at, task, recovered } = payload;
18
+ return JSON.stringify({ version: WEBHOOK_BODY_VERSION, event, level, title, text, at, ...(task ? { task } : {}), ...(recovered ? { recovered } : {}) });
19
+ }
20
+ /** Most header lines (KTD13). */
21
+ export const MAX_HEADER_LINES = 10;
22
+ /** RFC 7230 token. */
23
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
24
+ /** Printable ASCII and tab: Node refuses other bytes in a header, and CR or LF would split it. */
25
+ const HEADER_VALUE = /^[\t\x20-\x7e]*$/;
26
+ const RESERVED_HEADER = /^(host|content-length|content-type|transfer-encoding|connection|x-tidegap-.*)$/i;
27
+ export const HEADERS_TEXT = `Write one "Name: value" per line, at most ${MAX_HEADER_LINES}. Host, Content-Length, Content-Type, Transfer-Encoding, Connection and X-Tidegap-* are set by Tidegap.`;
28
+ /** The `headers` field as a map, or undefined when a line breaks a KTD13 rule. Empty lines are skipped. */
29
+ export function parseHeaders(text) {
30
+ const lines = text.split("\n").filter((l) => l.trim());
31
+ if (lines.length > MAX_HEADER_LINES)
32
+ return undefined;
33
+ const out = {};
34
+ for (const line of lines) {
35
+ const colon = line.indexOf(":");
36
+ if (colon <= 0)
37
+ return undefined;
38
+ const name = line.slice(0, colon).trim();
39
+ const value = line.slice(colon + 1).trim();
40
+ if (!HEADER_NAME.test(name) || RESERVED_HEADER.test(name) || !HEADER_VALUE.test(value))
41
+ return undefined;
42
+ out[name] = value;
43
+ }
44
+ return out;
45
+ }
46
+ /**
47
+ * Plain text for a receiver that reads `<…>` links, `[label](url)` markdown
48
+ * links (Mattermost, Matrix) and `@` group mentions. A zero-width space
49
+ * between `]` and `(` keeps a markdown link from forming.
50
+ */
51
+ function plain(text) {
52
+ return defuseMentions(escapeAngle(text)).replace(/\]\(/g, "]\u200B(");
53
+ }
54
+ /** Teams TextBlock markdown: no live link, emphasis or group mention. */
55
+ function teamsText(text) {
56
+ return defuseMentions(escapeChars(text, "\\[]()*_"));
57
+ }
58
+ /** A Teams Workflows message with one Adaptive Card 1.4: the title in bold, then the text. */
59
+ export function teamsBody(payload) {
60
+ return JSON.stringify({
61
+ type: "message",
62
+ attachments: [
63
+ {
64
+ contentType: "application/vnd.microsoft.card.adaptive",
65
+ contentUrl: null,
66
+ content: {
67
+ $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
68
+ type: "AdaptiveCard",
69
+ version: "1.4",
70
+ body: [
71
+ { type: "TextBlock", text: teamsText(payload.title), weight: "Bolder", size: "Medium", wrap: true },
72
+ { type: "TextBlock", text: teamsText(payload.text), wrap: true },
73
+ ],
74
+ },
75
+ },
76
+ ],
77
+ });
78
+ }
79
+ function bodyOf(format, payload) {
80
+ if (format === "text")
81
+ return JSON.stringify({ text: plain(payload.text) });
82
+ if (format === "teams")
83
+ return teamsBody(payload);
84
+ return webhookBody(payload);
85
+ }
86
+ /**
87
+ * Webhook hosts shared by many receivers, where the path names the receiver:
88
+ * a signing secret or headers typed for one path never follow a new path.
89
+ */
90
+ export const WEBHOOK_PATH_HOSTS = [
91
+ "*.logic.azure.com",
92
+ "*.webhook.office.com",
93
+ "hooks.zapier.com",
94
+ "hooks.slack.com",
95
+ "discord.com",
96
+ "*.discord.com",
97
+ "discordapp.com",
98
+ "chat.googleapis.com",
99
+ "maker.ifttt.com",
100
+ "*.make.com",
101
+ ];
102
+ export const webhook = {
103
+ kind: "webhook",
104
+ label: "Webhook",
105
+ description: "A POST to any URL you own: your server, n8n, Home Assistant, Teams, Google Chat.",
106
+ ready: true,
107
+ fields: [
108
+ { name: "url", label: "Webhook URL", input: "url", required: true, secret: true, placeholder: "https://example.com/hooks/tidegap", keepPathHosts: WEBHOOK_PATH_HOSTS },
109
+ {
110
+ name: "format",
111
+ label: "Body format",
112
+ input: "select",
113
+ default: "tidegap",
114
+ options: [
115
+ { value: "tidegap", label: "Tidegap JSON" },
116
+ { value: "text", label: "Plain text {\"text\"}: Google Chat, Mattermost, Matrix hookshot" },
117
+ { value: "teams", label: "Microsoft Teams card (Workflows)" },
118
+ ],
119
+ help: 'Tidegap JSON is {"version": 1, "event", "level", "title", "text", "at", "task"}. The Connect and Send test message has "event": "test".',
120
+ },
121
+ {
122
+ name: "secret",
123
+ label: "Signing secret",
124
+ input: "password",
125
+ secret: true,
126
+ advanced: true,
127
+ keepWith: "url",
128
+ help: 'Optional. Adds X-Tidegap-Timestamp and X-Tidegap-Signature: sha256=HMAC-SHA256(secret, "<timestamp>.<body>").',
129
+ },
130
+ {
131
+ name: "headers",
132
+ label: "Extra headers",
133
+ input: "textarea",
134
+ secret: true,
135
+ advanced: true,
136
+ keepWith: "url",
137
+ maxLines: MAX_HEADER_LINES,
138
+ placeholder: "Authorization: Bearer …",
139
+ help: "Optional. One \"Name: value\" per line, for example an Authorization header. Stored as a secret.",
140
+ },
141
+ ],
142
+ steps: [
143
+ { text: "Create an incoming webhook in the receiving app and copy its URL. Teams: in the channel, Workflows → \"Post to a channel when a webhook request is received\"." },
144
+ { text: "Pick the body format: Tidegap JSON for your own code, n8n or Home Assistant; Plain text for Google Chat, Mattermost and Matrix; Teams card for Teams." },
145
+ { text: "Optional: add a signing secret or headers such as Authorization." },
146
+ { text: 'Press Connect. Tidegap sends a test message with "event": "test"; answer it with any 2xx status.' },
147
+ ],
148
+ defaultEvents: ["task_done", "task_failed", "clean_window", "not_ready"],
149
+ docsAnchor: "notify-webhook",
150
+ worksWith: "Microsoft Teams (Workflows), Google Chat, Mattermost and Matrix (hookshot).",
151
+ errors: {
152
+ http_413: { text: "The receiver refused the message as too large. Raise its body limit, or pick the Plain text format." },
153
+ http_400: { text: "The receiver refused the message body (HTTP 400). Check that the body format matches the receiver.", field: "format" },
154
+ },
155
+ validate(values) {
156
+ if (typeof values.headers === "string" && !parseHeaders(values.headers))
157
+ return { field: "headers", text: HEADERS_TEXT };
158
+ return undefined;
159
+ },
160
+ format(payload, values) {
161
+ const headers = optString(values.headers);
162
+ const extra = headers ? parseHeaders(headers) : {};
163
+ // validate() refuses such headers on both the connect and the send path; never drop them silently.
164
+ if (!extra)
165
+ throw new Error("webhook headers failed validate");
166
+ const secret = optString(values.secret);
167
+ return {
168
+ type: "http",
169
+ method: "POST",
170
+ url: String(values.url),
171
+ headers: { ...extra, "Content-Type": "application/json" },
172
+ body: bodyOf(formatOf(values.format), payload),
173
+ ...(secret ? { sign: { secret } } : {}),
174
+ };
175
+ },
176
+ };
177
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The one payload model every channel formats from (KTD2). Text comes from
3
+ * {@link eventMessage}, so every channel says what Telegram says, with its
4
+ * redaction and the 600-character preview. Title and text are untrusted
5
+ * plain text: a `format` for a receiver that renders markup escapes them.
6
+ */
7
+ import type { TaskStatus } from "../types.js";
8
+ import type { ChannelEvent, EventKind } from "./types.js";
9
+ export type NotificationLevel = "info" | "success" | "warning" | "error";
10
+ /** A payload's event: an {@link EventKind}, or `test` for the message a Connect or Send test sends. */
11
+ export type PayloadEvent = EventKind | "test";
12
+ export interface NotificationPayload {
13
+ event: PayloadEvent;
14
+ level: NotificationLevel;
15
+ /** One line. */
16
+ title: string;
17
+ /** The full message, as Telegram sends it. */
18
+ text: string;
19
+ /** ISO-8601: when the event happened (a task's completion), else when the payload was built. */
20
+ at: string;
21
+ task?: {
22
+ id: string;
23
+ title: string;
24
+ status: TaskStatus;
25
+ grams?: number;
26
+ };
27
+ /** On `not_ready` only: the tick daemon runs again after a sent alert ("running again"). */
28
+ recovered?: true;
29
+ }
30
+ /** The test message text, the same on every channel. */
31
+ export declare const TEST_MESSAGE_TEXT = "Test message from Tidegap. Notifications work.";
32
+ /** The payload of the test message a Connect or Send test sends (`event: "test"`). */
33
+ export declare function testPayload(now?: Date): NotificationPayload;
34
+ /** The payload of one event. */
35
+ export declare function payloadFor(event: ChannelEvent, now?: Date): NotificationPayload;
36
+ //# sourceMappingURL=payload.d.ts.map
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The one payload model every channel formats from (KTD2). Text comes from
3
+ * {@link eventMessage}, so every channel says what Telegram says, with its
4
+ * redaction and the 600-character preview. Title and text are untrusted
5
+ * plain text: a `format` for a receiver that renders markup escapes them.
6
+ */
7
+ import { eventMessage, eventTitle, jobPausedTitle } from "./format.js";
8
+ const LEVEL = {
9
+ task_done: "success",
10
+ task_failed: "error",
11
+ clean_window: "info",
12
+ not_ready: "warning",
13
+ digest: "info",
14
+ };
15
+ function validIso(iso) {
16
+ return iso && Number.isFinite(Date.parse(iso)) ? iso : undefined;
17
+ }
18
+ /** The test message text, the same on every channel. */
19
+ export const TEST_MESSAGE_TEXT = "Test message from Tidegap. Notifications work.";
20
+ /** The payload of the test message a Connect or Send test sends (`event: "test"`). */
21
+ export function testPayload(now = new Date()) {
22
+ return { event: "test", level: "info", title: "Tidegap test message", text: TEST_MESSAGE_TEXT, at: now.toISOString() };
23
+ }
24
+ /** The payload of one event. */
25
+ export function payloadFor(event, now = new Date()) {
26
+ const { text } = eventMessage(event, now);
27
+ const recovered = event.kind === "not_ready" && event.recovered === true;
28
+ const base = {
29
+ event: event.kind,
30
+ level: recovered && event.problems.length === 0 ? "success" : LEVEL[event.kind],
31
+ text,
32
+ ...(recovered ? { recovered: true } : {}),
33
+ };
34
+ switch (event.kind) {
35
+ case "task_done":
36
+ case "task_failed": {
37
+ const record = event.task;
38
+ const title = eventTitle(record, event.jobTitle);
39
+ const grams = record.receipt?.actualCarbonGCo2 ?? record.receipt?.estimatedCarbonGCo2;
40
+ const done = event.kind === "task_done";
41
+ const head = event.kind === "task_failed" && event.jobPaused
42
+ ? jobPausedTitle(event.jobPaused)
43
+ : event.jobTitle
44
+ ? `${title}: ${done ? "done" : "failed"}`
45
+ : `${done ? "Done" : "Failed"}: ${title}`;
46
+ return {
47
+ ...base,
48
+ title: head,
49
+ at: validIso(record.completedAt) ?? now.toISOString(),
50
+ task: { id: record.taskId, title, status: record.status, ...(typeof grams === "number" && Number.isFinite(grams) ? { grams } : {}) },
51
+ };
52
+ }
53
+ case "clean_window":
54
+ return { ...base, title: "Clean window starting", at: validIso(event.window.start) ?? now.toISOString() };
55
+ case "not_ready":
56
+ return { ...base, title: text.split("\n")[0], at: now.toISOString() };
57
+ case "digest":
58
+ return { ...base, title: event.title.split("\n")[0].trim(), at: now.toISOString() };
59
+ }
60
+ }
61
+ //# sourceMappingURL=payload.js.map
@@ -0,0 +1,24 @@
1
+ /** Pure notification planning (KTD10): which channel receives which event, with quiet hours. */
2
+ import { type Channel, type ChannelEvent, type EventKind, type SendJob } from "./types.js";
3
+ /** True when local time `now` is in the quiet hours [22:00, 09:00), the `tonight` and `tomorrow_morning` preset starts. */
4
+ export declare function isQuietTime(now: Date): boolean;
5
+ /**
6
+ * One job per (event, enabled channel subscribed to the event's kind), in
7
+ * event order. A channel with quiet `night` gets no job in the quiet hours,
8
+ * except the daily summary (`digest`).
9
+ */
10
+ export declare function planNotifications(events: readonly ChannelEvent[], channels: readonly Channel[], now?: Date): SendJob[];
11
+ /**
12
+ * Fold alerts into the daily summary: a channel that gets the summary in
13
+ * this run gets no separate job for a task, problem or window the summary
14
+ * lists (an alert held by quiet hours then arrives once, inside the
15
+ * summary). Other channels and alerts the summary does not list keep their
16
+ * jobs. `dropped` holds the jobs the fold removed, so the host can send them
17
+ * when the summary fails on their channel; `folded` names their event kinds.
18
+ */
19
+ export declare function foldIntoDigest(jobs: readonly SendJob[]): {
20
+ jobs: SendJob[];
21
+ dropped: SendJob[];
22
+ folded: Set<EventKind>;
23
+ };
24
+ //# sourceMappingURL=plan.d.ts.map
@@ -0,0 +1,66 @@
1
+ /** Pure notification planning (KTD10): which channel receives which event, with quiet hours. */
2
+ import { MORNING_START_H, TONIGHT_START_H } from "../postpone.js";
3
+ import { channelQuiet } from "./types.js";
4
+ /** True when local time `now` is in the quiet hours [22:00, 09:00), the `tonight` and `tomorrow_morning` preset starts. */
5
+ export function isQuietTime(now) {
6
+ const h = now.getHours();
7
+ return h >= TONIGHT_START_H || h < MORNING_START_H;
8
+ }
9
+ /**
10
+ * One job per (event, enabled channel subscribed to the event's kind), in
11
+ * event order. A channel with quiet `night` gets no job in the quiet hours,
12
+ * except the daily summary (`digest`).
13
+ */
14
+ export function planNotifications(events, channels, now = new Date()) {
15
+ const quiet = isQuietTime(now);
16
+ const jobs = [];
17
+ for (const event of events) {
18
+ for (const channel of channels) {
19
+ if (!channel.enabled || !channel.events.includes(event.kind))
20
+ continue;
21
+ if (quiet && event.kind !== "digest" && channelQuiet(channel) === "night")
22
+ continue;
23
+ jobs.push({ channel, event });
24
+ }
25
+ }
26
+ return jobs;
27
+ }
28
+ /** True when the summary `covers` lists what `event` reports. */
29
+ function coveredBy(event, covers) {
30
+ switch (event.kind) {
31
+ case "task_done":
32
+ return covers.taskIds.includes(event.task.taskId);
33
+ case "task_failed":
34
+ // An auto-pause notice is sent on its own, even when the summary lists the failed run.
35
+ return !event.jobPaused && covers.taskIds.includes(event.task.taskId);
36
+ case "not_ready":
37
+ // The summary does not say the daemon runs again, so a recovery is never folded.
38
+ return covers.notReady && !event.recovered;
39
+ case "clean_window":
40
+ return covers.cleanWindow === event.window.start;
41
+ case "digest":
42
+ return false;
43
+ }
44
+ }
45
+ /**
46
+ * Fold alerts into the daily summary: a channel that gets the summary in
47
+ * this run gets no separate job for a task, problem or window the summary
48
+ * lists (an alert held by quiet hours then arrives once, inside the
49
+ * summary). Other channels and alerts the summary does not list keep their
50
+ * jobs. `dropped` holds the jobs the fold removed, so the host can send them
51
+ * when the summary fails on their channel; `folded` names their event kinds.
52
+ */
53
+ export function foldIntoDigest(jobs) {
54
+ const coversByChannel = new Map();
55
+ for (const j of jobs)
56
+ if (j.event.kind === "digest" && j.event.covers)
57
+ coversByChannel.set(j.channel.id, j.event.covers);
58
+ const kept = [];
59
+ const dropped = [];
60
+ for (const j of jobs) {
61
+ const covers = coversByChannel.get(j.channel.id);
62
+ (covers && coveredBy(j.event, covers) ? dropped : kept).push(j);
63
+ }
64
+ return { jobs: kept, dropped, folded: new Set(dropped.map((j) => j.event.kind)) };
65
+ }
66
+ //# sourceMappingURL=plan.js.map