@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,407 @@
1
+ /**
2
+ * Channel message texts and their buttons (KTD10, KTD15, R26, R27). Plain
3
+ * text only. Every title goes through `displayTitle` and control-character
4
+ * stripping; a result preview is the first {@link TELEGRAM_PREVIEW_CHARS}
5
+ * characters, default-redacted, and absent for a task that redacts its
6
+ * receipt (Key Decisions, Q4).
7
+ *
8
+ * Button table, per message:
9
+ *
10
+ * | Message | Buttons |
11
+ * |--------------------|------------------------------------------------------|
12
+ * | task done | [Result] |
13
+ * | task failed | none |
14
+ * | `/queue` listing | per task row: [n Later ▾] [n Run now] [n Cancel], each only when `taskActions` allows it |
15
+ * | `/jobs` listing | none: `/jobs pause|resume|run <n|id>` act on it |
16
+ * | Later ▾ menu | one row per available `postponeOptions` entry: [<label> · <time>] |
17
+ * | clean window | none |
18
+ * | not ready | none |
19
+ * | replies and `/result` | none |
20
+ */
21
+ import { displayTitle, stripControlChars, taskActions, taskResultText } from "../history.js";
22
+ import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason } from "../jobs.js";
23
+ import { clip } from "../notify.js";
24
+ import { localTimeLabel } from "../postpone.js";
25
+ import { problemLine, TICKER_CODES } from "../readiness.js";
26
+ import { isValidTimeZone } from "../zone-time.js";
27
+ import { redactPrompt } from "../redact.js";
28
+ import { freshReasonText, shortSessionId } from "../run-session.js";
29
+ import { TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX } from "./telegram.js";
30
+ /** Characters of result text a done message previews (Q4). */
31
+ export const TELEGRAM_PREVIEW_CHARS = 600;
32
+ /** Most messages one `/result` sends before pointing to `tidegap queue show`. */
33
+ export const RESULT_MAX_PARTS = 4;
34
+ /** Tasks one `/queue` lists. */
35
+ export const QUEUE_LIST_MAX = 10;
36
+ /** Jobs one `/jobs` lists; the same cap as the digest's lists. */
37
+ export const JOBS_LIST_MAX = 10;
38
+ const ACTION_CODE = { later: "l", cancel: "c", run: "x", result: "r" };
39
+ const PRESET_CODE = { "1h": "h", tonight: "n", tomorrow_morning: "m", after_limit_reset: "r" };
40
+ /** `<action>:<task_id>[:<preset code>]` (KTD15). */
41
+ export function encodeCallback(action, taskId, preset) {
42
+ return `${ACTION_CODE[action]}:${taskId}${action === "later" && preset ? `:${PRESET_CODE[preset]}` : ""}`;
43
+ }
44
+ /**
45
+ * True when every button of a task fits Telegram's 64-byte `callback_data`
46
+ * and `parseCallback` can read it back. A task id that does not (a long
47
+ * custom id) gets no buttons; its commands still work by number or id.
48
+ */
49
+ export function callbackFits(taskId) {
50
+ return /^[A-Za-z0-9_~.-]{1,100}$/.test(taskId) && new TextEncoder().encode(encodeCallback("later", taskId, "1h")).length <= TELEGRAM_CALLBACK_MAX_BYTES;
51
+ }
52
+ /** The decoding tables, for `parseCallback`. */
53
+ export const CALLBACK_ACTIONS = Object.fromEntries(Object.entries(ACTION_CODE).map(([name, code]) => [code, name]));
54
+ 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
+ /** The title a message shows: `displayTitle`, one line, at most 80 characters, else the task id. */
66
+ export function messageTitle(record) {
67
+ const t = stripControlChars(displayTitle(record) ?? "").trim();
68
+ return t ? clip(t, 80) : record.taskId;
69
+ }
70
+ /** Result text safe to send: default-redacted, control characters removed, newlines kept. */
71
+ function safeResult(record) {
72
+ return stripControlChars(redactPrompt(taskResultText(record) ?? "", undefined), { multiline: true }).trim();
73
+ }
74
+ function showCommand(record) {
75
+ return `tidegap queue show ${record.taskId}`;
76
+ }
77
+ function when(iso, now, label = localTimeLabel) {
78
+ const t = iso ? new Date(iso) : undefined;
79
+ return t && Number.isFinite(t.getTime()) ? label(t, now) : undefined;
80
+ }
81
+ /**
82
+ * Where a claude-code run happened (R12), or undefined for a run without
83
+ * that record. Names the directory by its last segment only: the full path
84
+ * stays off the chat.
85
+ */
86
+ function runSessionLine(record) {
87
+ const session = record.receipt?.session;
88
+ if (!session)
89
+ return undefined;
90
+ if (session.mode === "fresh") {
91
+ return `Ran in a fresh session: ${session.reason ? freshReasonText(session.reason) : "no session"}`;
92
+ }
93
+ const origin = session.originSessionId ?? record.originSessionId;
94
+ const dir = record.originCwd?.split("/").filter(Boolean).pop();
95
+ const where = dir ? ` (${stripControlChars(dir)})` : "";
96
+ return origin ? `Ran in a copy of session ${shortSessionId(origin)}${where}` : `Ran in a copy of its session${where}`;
97
+ }
98
+ /** A job's title as a message shows it (one line, at most 80 characters), or undefined when blank. */
99
+ function cleanJobTitle(title) {
100
+ const t = stripControlChars(title ?? "").trim();
101
+ return t ? clip(t, 80) : undefined;
102
+ }
103
+ /** The title a task event's message shows: the job's title for a job occurrence, else {@link messageTitle}. */
104
+ export function eventTitle(record, jobTitle) {
105
+ return cleanJobTitle(jobTitle) ?? messageTitle(record);
106
+ }
107
+ /**
108
+ * Task done (R26): title, time, where it ran, the preview or the redaction
109
+ * note, and a [Result] button. A job occurrence (`jobTitle`) leads with
110
+ * `<job title>: <result>` (jobs R22).
111
+ */
112
+ export function taskDoneMessage(record, now = new Date(), jobTitle) {
113
+ const job = cleanJobTitle(jobTitle);
114
+ const redacted = isRedactedTask(record);
115
+ const preview = redacted ? "" : clip(safeResult(record), TELEGRAM_PREVIEW_CHARS);
116
+ const lines = [job ? `${job}: ${preview ? clip(preview.replace(/\s+/g, " "), 200) : "done"}` : `Done: ${messageTitle(record)}`];
117
+ const at = when(record.completedAt, now);
118
+ if (at)
119
+ lines.push(`Finished ${at}`);
120
+ const ran = runSessionLine(record);
121
+ if (ran)
122
+ lines.push(ran);
123
+ if (redacted) {
124
+ lines.push("", `The result is not sent here: this task redacts its receipt. Run \`${showCommand(record)}\`.`);
125
+ }
126
+ else if (preview && (!job || preview.length > 200 || /\n/.test(preview))) {
127
+ lines.push("", preview);
128
+ }
129
+ const buttons = callbackFits(record.taskId) ? [[{ text: "Result", data: encodeCallback("result", record.taskId) }]] : undefined;
130
+ return { text: lines.join("\n"), ...(buttons ? { buttons } : {}) };
131
+ }
132
+ /** The first non-blank error line, default-redacted, one line, at most `max` characters. */
133
+ function firstErrorLine(error, max = 300) {
134
+ const line = (error ?? "").split(/\r?\n/).find((l) => l.trim()) ?? "unknown error";
135
+ return clip(stripControlChars(redactPrompt(line, undefined)).trim(), max);
136
+ }
137
+ /**
138
+ * Task failed: title, time, the first error line, the show command. No
139
+ * buttons. A job occurrence (`jobTitle`) leads with `<job title>: failed`.
140
+ */
141
+ export function taskFailedMessage(record, now = new Date(), jobTitle) {
142
+ const job = cleanJobTitle(jobTitle);
143
+ const lines = [job ? `${job}: failed` : `Failed: ${messageTitle(record)}`];
144
+ const at = when(record.completedAt, now);
145
+ if (at)
146
+ lines.push(`Failed ${at}`);
147
+ lines.push(firstErrorLine(record.error));
148
+ lines.push(`Run \`${showCommand(record)}\`.`);
149
+ return { text: lines.join("\n") };
150
+ }
151
+ /** The first line of an auto-pause notice (jobs KTD10): `job '<title>' paused after 3 failures: <reason>`. */
152
+ export function jobPausedTitle(notice) {
153
+ const title = cleanJobTitle(notice.title) ?? notice.jobId;
154
+ return `job '${title}' paused after ${JOB_AUTO_PAUSE_FAILURES} failures: ${firstErrorLine(notice.reason, 200)}`;
155
+ }
156
+ /** The auto-pause notice: the sentence, then how to resume. No buttons. */
157
+ export function jobPausedMessage(notice) {
158
+ return { text: `${jobPausedTitle(notice)}\nResume it: tidegap jobs resume ${notice.jobId}` };
159
+ }
160
+ /** A clean window starting. No buttons. */
161
+ export function cleanWindowMessage(window, now = new Date()) {
162
+ const start = when(window.start, now) ?? window.start;
163
+ const end = when(window.end, now) ?? window.end;
164
+ const g = typeof window.g === "number" ? `, ${Math.round(window.g)} gCO2e/kWh` : "";
165
+ return { text: `Clean window starting: ${start} to ${end}${g}. Queued tasks run in it when their deadline allows.` };
166
+ }
167
+ /**
168
+ * Tasks will not run (R26): "the tick daemon stopped" for ticker problems,
169
+ * "tasks cannot run" otherwise; `recovered` heads it "running again". No buttons.
170
+ */
171
+ export function notReadyMessage(problems, recovered = false) {
172
+ const ticker = problems.some((p) => TICKER_CODES.includes(p.code));
173
+ const head = recovered
174
+ ? "Tidegap: the tick daemon is running again."
175
+ : ticker
176
+ ? "Tidegap: the tick daemon is not running."
177
+ : "Tidegap: queued tasks cannot run.";
178
+ return { text: [head, ...problems.map(problemLine)].join("\n") };
179
+ }
180
+ /** The message for a planned event. */
181
+ export function eventMessage(event, now = new Date()) {
182
+ switch (event.kind) {
183
+ case "task_done":
184
+ return taskDoneMessage(event.task, now, event.jobTitle);
185
+ case "task_failed":
186
+ return event.jobPaused ? jobPausedMessage(event.jobPaused) : taskFailedMessage(event.task, now, event.jobTitle);
187
+ case "clean_window":
188
+ return cleanWindowMessage(event.window, now);
189
+ case "not_ready":
190
+ return notReadyMessage(event.problems, event.recovered === true);
191
+ case "digest":
192
+ return { text: `${event.title}\n${event.text}` };
193
+ }
194
+ }
195
+ /** The planned start a listing shows: `running`, else the future plan, else "next tick". */
196
+ function plannedLabel(record, now) {
197
+ if (record.status === "running")
198
+ return "running";
199
+ if (record.status === "submitted")
200
+ return "at the provider";
201
+ const iso = [record.scheduledFor, record.notBefore].find((v) => v && Date.parse(v) > now.getTime());
202
+ return iso ? when(iso, now) : "next tick";
203
+ }
204
+ /** `/queue` (R27): numbered tasks and one button row per task. `ids[n-1]` is task n. */
205
+ export function queueMessage(records, now = new Date()) {
206
+ const listed = records.slice(0, QUEUE_LIST_MAX);
207
+ if (listed.length === 0)
208
+ return { text: "The queue is empty.", ids: [] };
209
+ const lines = [`Queue, next ${listed.length}:`];
210
+ const buttons = [];
211
+ listed.forEach((r, i) => {
212
+ const n = i + 1;
213
+ lines.push(`${n}. ${messageTitle(r)} · ${plannedLabel(r, now)}`);
214
+ const a = callbackFits(r.taskId) ? taskActions(r) : { later: false, runNow: false, cancel: false };
215
+ const row = [];
216
+ if (a.later)
217
+ row.push({ text: `${n} Later ▾`, data: encodeCallback("later", r.taskId) });
218
+ if (a.runNow)
219
+ row.push({ text: `${n} Run now`, data: encodeCallback("run", r.taskId) });
220
+ if (a.cancel)
221
+ row.push({ text: `${n} Cancel`, data: encodeCallback("cancel", r.taskId) });
222
+ if (row.length > 0)
223
+ buttons.push(row);
224
+ });
225
+ lines.push("", "Numbers stay valid for 10 minutes. Example: /later 1 tonight");
226
+ return { text: lines.join("\n"), buttons, ids: listed.map((r) => r.taskId) };
227
+ }
228
+ /** A job's title: one line, at most 80 characters, else the job id. */
229
+ export function jobTitle(job) {
230
+ const t = stripControlChars(job.title).trim();
231
+ return t ? clip(t, 80) : job.jobId;
232
+ }
233
+ const WEEKDAY_NAMES = { mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat", sun: "Sun" };
234
+ function cadenceText(cadence) {
235
+ switch (cadence.kind) {
236
+ case "daily":
237
+ return "every day";
238
+ case "weekdays":
239
+ return "every weekday";
240
+ case "weekly":
241
+ return `every ${cadence.days.map((d) => WEEKDAY_NAMES[d] ?? d).join(", ")}`;
242
+ case "hours":
243
+ return `at least every ${cadence.every} h`;
244
+ }
245
+ }
246
+ /** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
247
+ export function zoneTimeLabel(at, now, timeZone) {
248
+ const parts = (d) => {
249
+ // An unknown zone falls back to the system zone.
250
+ const fmt = new Intl.DateTimeFormat("en-US", { timeZone: isValidTimeZone(timeZone) ? timeZone : undefined, weekday: "short", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
251
+ const p = Object.fromEntries(fmt.formatToParts(d).map((x) => [x.type, x.value]));
252
+ return { day: `${p.year}-${p.month}-${p.day}`, weekday: p.weekday, time: `${p.hour}:${p.minute}` };
253
+ };
254
+ const a = parts(at);
255
+ return a.day === parts(now).day ? a.time : `${a.weekday} ${a.time}`;
256
+ }
257
+ /** The {@link jobNextLabel} of a job whose occurrence is running. */
258
+ export const JOB_RUNNING_NOW = "running now";
259
+ /**
260
+ * The next run of a job from its live occurrence: running, the planned
261
+ * hour of a scheduled one, or `~` and the earliest start of a queued one.
262
+ * Undefined without a live occurrence.
263
+ */
264
+ export function jobNextLabel(job, pending, now) {
265
+ if (!pending)
266
+ return undefined;
267
+ if (pending.status === "running" || pending.status === "submitted")
268
+ return JOB_RUNNING_NOW;
269
+ if (pending.status !== "scheduled" && pending.status !== "queued")
270
+ return undefined;
271
+ const planned = pending.status === "scheduled" ? pending.scheduledFor : undefined;
272
+ const label = when(planned ?? pending.notBefore ?? pending.scheduledFor, now, (t) => zoneTimeLabel(t, now, job.timeZone));
273
+ return label && `${planned ? "" : "~"}${label}`;
274
+ }
275
+ /** Why a paused job is paused, one line, default-redacted. */
276
+ function pausedText(job) {
277
+ const reason = job.pauseReason ?? "manual";
278
+ if (reason === "manual")
279
+ return "paused";
280
+ const safe = (text) => clip(stripControlChars(redactPrompt(text, undefined)).trim(), 120);
281
+ const auto = jobAutoPauseReason(reason);
282
+ if (auto !== undefined)
283
+ return `paused after ${job.consecutiveFailures || JOB_AUTO_PAUSE_FAILURES} failures: ${safe(auto)}`;
284
+ return `paused: ${safe(reason)}`;
285
+ }
286
+ /** One `/jobs` line without its number. */
287
+ function jobLine(job, taskOf, now) {
288
+ if (job.status === "paused")
289
+ return `${jobTitle(job)} - ${pausedText(job)}`;
290
+ const parts = [jobTitle(job)];
291
+ parts.push(job.window ? `${cadenceText(job.cadence)} ${job.window.start}-${job.window.end}` : cadenceText(job.cadence));
292
+ const next = jobNextLabel(job, job.pendingTaskId ? taskOf(job.pendingTaskId) : undefined, now);
293
+ if (next)
294
+ parts.push(next === JOB_RUNNING_NOW ? next : `next ${next}`);
295
+ if (job.lastOutcome) {
296
+ const last = job.lastTaskId ? taskOf(job.lastTaskId) : undefined;
297
+ const at = when(last?.completedAt ?? job.lastRunStartedAt, now, (t) => zoneTimeLabel(t, now, job.timeZone));
298
+ const count = job.lastOutcome === "failed" && job.consecutiveFailures > 0 ? ` (${job.consecutiveFailures} of ${JOB_AUTO_PAUSE_FAILURES})` : "";
299
+ parts.push(`last ${job.lastOutcome}${at ? ` ${at}` : ""}${count}`);
300
+ }
301
+ return parts.join(" - ");
302
+ }
303
+ /**
304
+ * `/jobs` (R28): counts, then one numbered line per job, active ones first, at most
305
+ * {@link JOBS_LIST_MAX}, then "and N more". Times are in each job's zone.
306
+ * `ids[n-1]` is job n.
307
+ */
308
+ export function jobsMessage(jobs, taskOf, now = new Date()) {
309
+ if (jobs.length === 0)
310
+ return { text: "No jobs. Create one on the page: tidegap ui", ids: [] };
311
+ const active = jobs.filter((j) => j.status === "active").length;
312
+ const paused = jobs.filter((j) => j.status === "paused").length;
313
+ // Active first, then paused; each group keeps the ledger's order (oldest first).
314
+ const listed = [...jobs].sort((x, y) => Number(x.status === "paused") - Number(y.status === "paused")).slice(0, JOBS_LIST_MAX);
315
+ const lines = [`Jobs (${[active ? `${active} active` : "", paused ? `${paused} paused` : ""].filter(Boolean).join(", ")})`];
316
+ listed.forEach((j, i) => lines.push(`${i + 1}. ${jobLine(j, taskOf, now)}`));
317
+ if (jobs.length > listed.length)
318
+ lines.push(`and ${jobs.length - listed.length} more`);
319
+ lines.push("", "Numbers stay valid for 10 minutes. Example: /jobs pause 1", "Edit jobs on the page: tidegap ui");
320
+ return { text: lines.join("\n"), ids: listed.map((j) => j.jobId) };
321
+ }
322
+ /** The Later ▾ menu of one task: one button per available option. */
323
+ export function laterMenuMessage(record, options, now = new Date()) {
324
+ const available = callbackFits(record.taskId) ? options.filter((o) => o.available && o.not_before) : [];
325
+ if (available.length === 0) {
326
+ const why = options.map((o) => `${o.label}: ${o.reason ?? "unavailable"}`).join("\n");
327
+ return { text: `Later: ${messageTitle(record)}\nNo option is available now.\n${why}` };
328
+ }
329
+ return {
330
+ text: `Later: ${messageTitle(record)}`,
331
+ buttons: available.map((o) => [
332
+ { text: `${o.label} · ${localTimeLabel(new Date(o.not_before), now)}`, data: encodeCallback("later", record.taskId, o.preset) },
333
+ ]),
334
+ };
335
+ }
336
+ /** Split text into parts of at most `max` characters, preferring line breaks. */
337
+ export function splitMessage(text, max = TELEGRAM_MESSAGE_MAX) {
338
+ const parts = [];
339
+ let rest = text;
340
+ while (rest.length > max) {
341
+ let cut = rest.lastIndexOf("\n", max);
342
+ if (cut < max / 2)
343
+ cut = max;
344
+ parts.push(rest.slice(0, cut));
345
+ rest = rest.slice(cut).replace(/^\n/, "");
346
+ }
347
+ if (rest.length > 0 || parts.length === 0)
348
+ parts.push(rest);
349
+ return parts;
350
+ }
351
+ /**
352
+ * `/result` and the Result button (R27): no result text for a redacted
353
+ * task; otherwise the result in parts of 4096 characters, at most
354
+ * {@link RESULT_MAX_PARTS}, then a pointer to `tidegap queue show`.
355
+ */
356
+ export function resultMessages(record) {
357
+ const title = messageTitle(record);
358
+ if (isRedactedTask(record)) {
359
+ return [{ text: `${title}\nThis task is redacted; run \`${showCommand(record)}\`.` }];
360
+ }
361
+ if (record.status !== "completed") {
362
+ return [{ text: `${title} is ${record.status}; it has no result.` }];
363
+ }
364
+ const body = safeResult(record);
365
+ if (!body)
366
+ return [{ text: `${title}\nThe result is empty.` }];
367
+ const max = TELEGRAM_MESSAGE_MAX - 100;
368
+ const parts = splitMessage(body, max);
369
+ const out = parts.slice(0, RESULT_MAX_PARTS).map((p) => ({ text: p }));
370
+ out[0] = { text: `${title}\n\n${out[0].text}` };
371
+ if (parts.length > RESULT_MAX_PARTS)
372
+ out.push({ text: `The result is longer. Run \`${showCommand(record)}\` for the rest.` });
373
+ return out;
374
+ }
375
+ /** `/later` grammar (KTD15), quoted by `/help` and the reset-time reply. */
376
+ export const LATER_GRAMMAR = "/later <n|id> <1h|tonight|tomorrow|reset [HH:MM]|HH:MM>";
377
+ /** `/jobs` grammar, quoted by `/help` and the usage reply. */
378
+ export const JOBS_GRAMMAR = "/jobs [pause|resume|run <n|id>]";
379
+ /** `/help`. */
380
+ export const HELP_TEXT = [
381
+ "Tidegap commands:",
382
+ "/queue - the next 10 tasks, numbered",
383
+ `${LATER_GRAMMAR} - run a task later`,
384
+ "/run <n|id> - run a task at the next tick",
385
+ "/cancel <n|id> - cancel a task",
386
+ "/result <n|id> - the result of a finished task",
387
+ `${JOBS_GRAMMAR} - list recurring jobs; pause, resume or run one`,
388
+ "/help - this list",
389
+ "Numbers come from the last /queue or /jobs and stay valid for 10 minutes.",
390
+ ].join("\n");
391
+ /** The bot's command menu (`setMyCommands`), parsed from {@link HELP_TEXT}: one source of truth. */
392
+ export function telegramCommands(help = HELP_TEXT) {
393
+ const out = [];
394
+ for (const line of help.split("\n")) {
395
+ // Bot API: command 1-32 chars of a-z, 0-9, _; description 1-256 chars.
396
+ const sep = line.indexOf(" - ");
397
+ if (!line.startsWith("/") || sep < 0)
398
+ continue;
399
+ const name = /^\/([a-z0-9_]{1,32})(?:\s|$)/.exec(line.slice(0, sep));
400
+ const description = line.slice(sep + 3).trim();
401
+ const m = name && description ? [line, name[1], description] : null;
402
+ if (m)
403
+ out.push({ command: m[1], description: m[2].slice(0, 256) });
404
+ }
405
+ return out;
406
+ }
407
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1,15 @@
1
+ /** Channels (coherence KTD10 to KTD15): types, the kind registry, the payload model, planning, the Telegram client, commands and texts. */
2
+ export * from "./types.js";
3
+ export * from "./plan.js";
4
+ export * from "./digest.js";
5
+ export * from "./registry.js";
6
+ export * from "./delivery-codes.js";
7
+ export * from "./payload.js";
8
+ export * from "./kinds/index.js";
9
+ export { webhookBody, WEBHOOK_BODY_VERSION } from "./kinds/webhook.js";
10
+ export { PUSHOVER_MESSAGES_PATH } from "./kinds/pushover.js";
11
+ export { isLoopbackSmtpHost } from "./kinds/email.js";
12
+ export * from "./telegram.js";
13
+ export * from "./format.js";
14
+ export * from "./commands.js";
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,15 @@
1
+ /** Channels (coherence KTD10 to KTD15): types, the kind registry, the payload model, planning, the Telegram client, commands and texts. */
2
+ export * from "./types.js";
3
+ export * from "./plan.js";
4
+ export * from "./digest.js";
5
+ export * from "./registry.js";
6
+ export * from "./delivery-codes.js";
7
+ export * from "./payload.js";
8
+ export * from "./kinds/index.js";
9
+ export { webhookBody, WEBHOOK_BODY_VERSION } from "./kinds/webhook.js";
10
+ export { PUSHOVER_MESSAGES_PATH } from "./kinds/pushover.js";
11
+ export { isLoopbackSmtpHost } from "./kinds/email.js";
12
+ export * from "./telegram.js";
13
+ export * from "./format.js";
14
+ export * from "./commands.js";
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Command: a program on this computer gets each message as the Tidegap JSON
3
+ * (the webhook's `tidegap` body, `version: 1`) on its standard input. The
4
+ * host runs it with an argv array and no shell, a fixed working directory,
5
+ * a minimal environment (no secret, no Tidegap variable) and a time limit,
6
+ * and only when the file is the user's own and no one else can change it.
7
+ * Use it for scripts: a local logger, a home-automation CLI, `osascript`.
8
+ */
9
+ import type { KindDescriptor } from "../registry.js";
10
+ /** The `args` field as argv items: one per non-empty line, trimmed. */
11
+ export declare function commandArgs(text: string | number | undefined): string[];
12
+ export declare const command: KindDescriptor;
13
+ //# sourceMappingURL=command.d.ts.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Command: a program on this computer gets each message as the Tidegap JSON
3
+ * (the webhook's `tidegap` body, `version: 1`) on its standard input. The
4
+ * host runs it with an argv array and no shell, a fixed working directory,
5
+ * a minimal environment (no secret, no Tidegap variable) and a time limit,
6
+ * and only when the file is the user's own and no one else can change it.
7
+ * Use it for scripts: a local logger, a home-automation CLI, `osascript`.
8
+ */
9
+ import { webhookBody } from "./webhook.js";
10
+ /** Most argument lines. */
11
+ const COMMAND_MAX_ARGS = 10;
12
+ /** The `args` field as argv items: one per non-empty line, trimmed. */
13
+ export function commandArgs(text) {
14
+ return typeof text === "string" ? text.split("\n").map((l) => l.trim()).filter(Boolean) : [];
15
+ }
16
+ export const command = {
17
+ kind: "command",
18
+ label: "Command",
19
+ description: "Runs a program on this computer with each message as JSON on its standard input.",
20
+ platforms: ["darwin", "linux"],
21
+ ready: true,
22
+ fields: [
23
+ {
24
+ name: "path",
25
+ label: "Program",
26
+ input: "text",
27
+ required: true,
28
+ maxLength: 1024,
29
+ pattern: "/[\\s\\S]*",
30
+ placeholder: "/Users/you/bin/on-tidegap",
31
+ invalid: "Type the full path of the program, starting with /.",
32
+ help: "The full path of an executable file that you own. Tidegap runs it directly, with no shell.",
33
+ },
34
+ {
35
+ name: "args",
36
+ label: "Arguments",
37
+ input: "textarea",
38
+ advanced: true,
39
+ maxLines: COMMAND_MAX_ARGS,
40
+ maxLength: 2048,
41
+ placeholder: "--quiet",
42
+ help: `Optional. One argument per line, at most ${COMMAND_MAX_ARGS}; no quotes needed. They are not secret: other programs on this computer can see them.`,
43
+ },
44
+ ],
45
+ steps: [
46
+ { text: "Write a program or script that reads JSON from its standard input. Make it executable and writable only by you (chmod 755)." },
47
+ { text: 'The JSON is {"version": 1, "event", "level", "title", "text", "at", "task"}; the test message has "event": "test".' },
48
+ { text: "It runs in your home folder with only PATH, HOME, LANG and TMPDIR set, and must finish in 20 seconds." },
49
+ { text: "Type the full path here and press Connect. Exit code 0 means delivered." },
50
+ ],
51
+ defaultEvents: ["task_done", "task_failed", "not_ready"],
52
+ docsAnchor: "notify-command",
53
+ target: (values) => String(values.path ?? "Command"),
54
+ errors: {
55
+ not_found: { text: "There is no program at this path. Check the path.", field: "path" },
56
+ not_executable: { text: "This file is not executable. Run chmod +x on it, or pick another file.", field: "path" },
57
+ unsafe_path: { text: "Tidegap runs only a program you own, in a folder only you can change. Run chmod go-w on the file and its folder.", field: "path" },
58
+ timeout: { text: "The program did not finish in 20 seconds. Make it exit sooner, or start slow work in the background.", field: "path" },
59
+ command_failed: { text: "The program exited with an error. Run it by hand with a test message on its input to see why.", field: "path" },
60
+ },
61
+ format(payload, values) {
62
+ return { type: "command", path: String(values.path), args: commandArgs(values.args), input: webhookBody(payload) };
63
+ },
64
+ };
65
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Discord (R12): a channel webhook. One embed per message, colored by level;
3
+ * markdown specials escaped and `allowed_mentions` empty, so a task title can
4
+ * neither link nor ping (KTD2). Sent with `?wait=true`, so Discord answers
5
+ * only after it accepted the message.
6
+ */
7
+ import type { KindDescriptor } from "../registry.js";
8
+ import type { NotificationPayload } from "../payload.js";
9
+ /** Discord's caps on an embed's title and description. */
10
+ export declare const DISCORD_TITLE_MAX = 256;
11
+ export declare const DISCORD_DESCRIPTION_MAX = 4096;
12
+ export declare function discordBody(payload: NotificationPayload): string;
13
+ /** The webhook URL with `wait=true`, other query parameters (`thread_id`) kept. */
14
+ export declare function discordUrl(raw: string): string;
15
+ export declare const discord: KindDescriptor;
16
+ //# sourceMappingURL=discord.d.ts.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Discord (R12): a channel webhook. One embed per message, colored by level;
3
+ * markdown specials escaped and `allowed_mentions` empty, so a task title can
4
+ * neither link nor ping (KTD2). Sent with `?wait=true`, so Discord answers
5
+ * only after it accepted the message.
6
+ */
7
+ import { clipEscaped, escapeChars, LEVEL_COLOR, LOOPBACK_URL } from "./shared.js";
8
+ /** Discord's caps on an embed's title and description. */
9
+ export const DISCORD_TITLE_MAX = 256;
10
+ export const DISCORD_DESCRIPTION_MAX = 4096;
11
+ /** Discord markdown: emphasis, code, spoilers, quotes, headings, masked links and `<@…>` mentions. */
12
+ const SPECIALS = "\\*_~`|>[]()#<";
13
+ export function discordBody(payload) {
14
+ return JSON.stringify({
15
+ username: "Tidegap",
16
+ embeds: [
17
+ {
18
+ title: clipEscaped(escapeChars(payload.title, SPECIALS), DISCORD_TITLE_MAX),
19
+ description: clipEscaped(escapeChars(payload.text, SPECIALS), DISCORD_DESCRIPTION_MAX),
20
+ color: LEVEL_COLOR[payload.level],
21
+ timestamp: payload.at,
22
+ },
23
+ ],
24
+ allowed_mentions: { parse: [] },
25
+ });
26
+ }
27
+ /** The webhook URL with `wait=true`, other query parameters (`thread_id`) kept. */
28
+ export function discordUrl(raw) {
29
+ const url = new URL(raw);
30
+ url.searchParams.set("wait", "true");
31
+ return url.toString();
32
+ }
33
+ const DISCORD_URL_TEXT = "Discord does not know this webhook. Copy the URL again from Server Settings → Integrations → Webhooks.";
34
+ export const discord = {
35
+ kind: "discord",
36
+ label: "Discord",
37
+ description: "Messages in a Discord channel through a webhook.",
38
+ ready: true,
39
+ fields: [
40
+ {
41
+ name: "url",
42
+ label: "Webhook URL",
43
+ input: "url",
44
+ required: true,
45
+ secret: true,
46
+ placeholder: "https://discord.com/api/webhooks/…/…",
47
+ pattern: String.raw `https://(?:(?:canary|ptb)\.)?discord(?:app)?\.com/api(?:/v\d+)?/webhooks/\d+/[A-Za-z0-9_-]+(?:\?\S*)?|${LOOPBACK_URL}`,
48
+ invalid: "Paste the Discord webhook URL. It starts with https://discord.com/api/webhooks/.",
49
+ },
50
+ ],
51
+ steps: [
52
+ { text: "In Discord, open Server Settings → Integrations." },
53
+ { text: "Open Webhooks → New Webhook, then pick the channel for Tidegap messages." },
54
+ { text: "Press Copy Webhook URL, paste it here and press Connect." },
55
+ ],
56
+ defaultEvents: ["task_done", "task_failed", "not_ready"],
57
+ docsAnchor: "notify-discord",
58
+ errors: {
59
+ auth: { text: DISCORD_URL_TEXT, field: "url" },
60
+ http_404: { text: DISCORD_URL_TEXT, field: "url" },
61
+ http_400: { text: "Discord refused the message format. Update Tidegap and try again." },
62
+ },
63
+ format(payload, values) {
64
+ return { type: "http", method: "POST", url: discordUrl(String(values.url)), headers: { "Content-Type": "application/json" }, body: discordBody(payload) };
65
+ },
66
+ };
67
+ //# sourceMappingURL=discord.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Email via SMTP (R12, KTD5): plain-text mail through the user's own SMTP
3
+ * account. The host's client (`packages/cli/src/channels/smtp.ts`) sends
4
+ * the spec; this file holds the fields, the provider presets and the
5
+ * where-to-get-it steps. TLS is always verified; security `none` (no TLS at
6
+ * all) is allowed only to a mail server on this computer.
7
+ *
8
+ * Outlook.com and Hotmail personal accounts are not supported: Microsoft
9
+ * turned off password SMTP for them on 2024-09-16 and they need OAuth,
10
+ * which would need a Tidegap-owned client id (R20).
11
+ */
12
+ import type { KindDescriptor } from "../registry.js";
13
+ /** A plain `local@domain` address: no spaces, CR, LF, `<`, `>`, quotes, commas or semicolons. */
14
+ export declare const EMAIL_ADDRESS: string;
15
+ /** Hosts that never leave this computer: `none` (no TLS) is allowed only to these. */
16
+ export declare function isLoopbackSmtpHost(host: string): boolean;
17
+ /** One line for a header: CR, LF and other control characters become spaces. */
18
+ export declare function headerLine(text: string): string;
19
+ export declare const email: KindDescriptor;
20
+ //# sourceMappingURL=email.d.ts.map