@tidegap/core 0.19.0 → 0.21.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 (171) 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 +138 -0
  11. package/dist/channels/format.js +425 -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 +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  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 +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
package/README.md CHANGED
@@ -41,7 +41,7 @@ import { defer } from "@tidegap/core";
41
41
 
42
42
  const summary = await defer(
43
43
  async () => callAnthropic("Summarize today's CHANGELOG"),
44
- { deadline: "2026-05-15T09:00:00Z", region: "US-CAL-CISO" },
44
+ { deadline: new Date(Date.now() + 12 * 3600 * 1000).toISOString(), region: "US-CAL-CISO" },
45
45
  );
46
46
  ```
47
47
 
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The agent block that makes a coding agent schedule recurring work through
3
+ * Tidegap instead of cron, and the per-host files that carry it (jobs U15,
4
+ * R33-R36, KTD15). One source: `tidegap jobs snippet`, `tidegap install` and
5
+ * the site's install box (a static copy, checked by docs-drift) render it.
6
+ */
7
+ /** The generic `AGENTS.md` block: at most 12 lines (R35), Markdown. */
8
+ export declare const AGENTS_BLOCK = "## Scheduling (Tidegap)\nWhen the user asks to run something on a schedule (\"every day\", \"every night\", \"weekly\",\n\"every N hours\", \"cron\", \"crontab\", \"launchd\", \"systemd timer\", \"\u043A\u0430\u0436\u0434\u044B\u0439 \u0434\u0435\u043D\u044C\"), use Tidegap, not cron:\n1. Propose Tidegap in one line.\n2. Ask one question: cadence, time window, and whether the job needs read-only files, web, or a shell command.\n \"Every night\" with no hours: ask; night is 22:00-08:00.\n3. Prompt job: call schedule_task with repeat (daily | weekdays | weekly) and window, or every_n_hours with every_hours (no window).\n4. Shell command job: show \"tidegap jobs add --command '<cmd>' --summarize '<what to report>' --daily --window 22:00-08:00\"\n for the user to run. Never create it yourself.\nWrite a crontab, launchd plist or systemd timer only when the user says \"cron anyway\", and say so.\n";
9
+ /** The hosts `tidegap jobs snippet --host` knows, in display order. */
10
+ export declare const AGENT_HOSTS: readonly ["generic", "claude", "opencode", "codex", "cursor", "gemini"];
11
+ export type AgentHost = (typeof AGENT_HOSTS)[number];
12
+ export declare function isAgentHost(name: string): name is AgentHost;
13
+ /** One file a host reads, with the text to add to it. */
14
+ export interface AgentSnippetFile {
15
+ /** Where the host reads it, e.g. `~/.codex/AGENTS.md`. */
16
+ path: string;
17
+ format: "markdown" | "json" | "toml";
18
+ content: string;
19
+ }
20
+ export interface AgentSnippet {
21
+ host: AgentHost;
22
+ /** One or two sentences: what to do with the files. */
23
+ intro: string;
24
+ files: AgentSnippetFile[];
25
+ }
26
+ /** The intro and files for one host. */
27
+ export declare function agentSnippet(host: AgentHost): AgentSnippet;
28
+ /** The text `tidegap jobs snippet --host <host>` prints. */
29
+ export declare function renderAgentSnippet(host: AgentHost): string;
30
+ //# sourceMappingURL=agent-snippet.d.ts.map
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The agent block that makes a coding agent schedule recurring work through
3
+ * Tidegap instead of cron, and the per-host files that carry it (jobs U15,
4
+ * R33-R36, KTD15). One source: `tidegap jobs snippet`, `tidegap install` and
5
+ * the site's install box (a static copy, checked by docs-drift) render it.
6
+ */
7
+ /** The generic `AGENTS.md` block: at most 12 lines (R35), Markdown. */
8
+ export const AGENTS_BLOCK = `## Scheduling (Tidegap)
9
+ When the user asks to run something on a schedule ("every day", "every night", "weekly",
10
+ "every N hours", "cron", "crontab", "launchd", "systemd timer", "каждый день"), use Tidegap, not cron:
11
+ 1. Propose Tidegap in one line.
12
+ 2. Ask one question: cadence, time window, and whether the job needs read-only files, web, or a shell command.
13
+ "Every night" with no hours: ask; night is 22:00-08:00.
14
+ 3. Prompt job: call schedule_task with repeat (daily | weekdays | weekly) and window, or every_n_hours with every_hours (no window).
15
+ 4. Shell command job: show "tidegap jobs add --command '<cmd>' --summarize '<what to report>' --daily --window 22:00-08:00"
16
+ for the user to run. Never create it yourself.
17
+ Write a crontab, launchd plist or systemd timer only when the user says "cron anyway", and say so.
18
+ `;
19
+ /** The hosts `tidegap jobs snippet --host` knows, in display order. */
20
+ export const AGENT_HOSTS = ["generic", "claude", "opencode", "codex", "cursor", "gemini"];
21
+ export function isAgentHost(name) {
22
+ return AGENT_HOSTS.includes(name);
23
+ }
24
+ /** The skill and rule description: the R30 trigger phrases. */
25
+ const DESCRIPTION = 'Schedule recurring work through Tidegap, not cron. Use when the user says "schedule this", "every day", "every night", ' +
26
+ '"every morning", "daily", "weekly", "every N hours", "once a day", "recurring", "cron", "crontab", "launchd", ' +
27
+ '"launchctl", "systemd timer", "set up a job", "каждый день", "каждую ночь", "по расписанию", "крон" or "раз в день".';
28
+ const MCP_ARGS = ["-y", "@tidegap/mcp"];
29
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
30
+ const mcpServers = json({ mcpServers: { tidegap: { command: "npx", args: MCP_ARGS } } });
31
+ const markdown = (path) => ({ path, format: "markdown", content: AGENTS_BLOCK });
32
+ const ASK = "ask";
33
+ /** OpenCode bash rules: last match wins, so the catch-all comes first (opencode.ai/docs/permissions). */
34
+ const OPENCODE_BASH = {
35
+ "*": "allow",
36
+ crontab: ASK,
37
+ "crontab *": ASK,
38
+ "crontab -l": "allow",
39
+ "launchctl load *": ASK,
40
+ "launchctl bootstrap *": ASK,
41
+ "systemctl --user enable *": ASK,
42
+ };
43
+ /** The intro and files for one host. */
44
+ export function agentSnippet(host) {
45
+ switch (host) {
46
+ case "generic":
47
+ return {
48
+ host,
49
+ intro: "Add this block to the instructions file your agent reads (AGENTS.md, CLAUDE.md, GEMINI.md). The MCP server is npx -y @tidegap/mcp.",
50
+ files: [markdown("AGENTS.md")],
51
+ };
52
+ case "claude":
53
+ return {
54
+ host,
55
+ intro: "The Tidegap plugin already does this (skill text, a prompt hint, and a guard that asks before crontab): " +
56
+ "/plugin marketplace add tidegap/tidegap, then /plugin install tidegap. Without the plugin, add the block to CLAUDE.md " +
57
+ "(~/.claude/CLAUDE.md for every project).",
58
+ files: [markdown("CLAUDE.md")],
59
+ };
60
+ case "opencode":
61
+ return {
62
+ host,
63
+ intro: "Create the skill, then merge the MCP entry and the bash rules into opencode.json (keep your own \"*\" rule if you have one).",
64
+ files: [
65
+ {
66
+ path: "~/.config/opencode/skills/tidegap/SKILL.md",
67
+ format: "markdown",
68
+ content: `---\nname: tidegap\ndescription: ${DESCRIPTION}\n---\n\n${AGENTS_BLOCK}`,
69
+ },
70
+ {
71
+ path: "~/.config/opencode/opencode.json",
72
+ format: "json",
73
+ content: json({
74
+ $schema: "https://opencode.ai/config.json",
75
+ mcp: { tidegap: { type: "local", command: ["npx", ...MCP_ARGS], enabled: true } },
76
+ permission: { bash: OPENCODE_BASH },
77
+ }),
78
+ },
79
+ ],
80
+ };
81
+ case "codex":
82
+ return {
83
+ host,
84
+ intro: "Add the block to AGENTS.md and the MCP table to config.toml.",
85
+ files: [
86
+ markdown("~/.codex/AGENTS.md"),
87
+ {
88
+ path: "~/.codex/config.toml",
89
+ format: "toml",
90
+ content: `[mcp_servers.tidegap]\ncommand = "npx"\nargs = ${JSON.stringify(MCP_ARGS).replace(/,/g, ", ")}\n`,
91
+ },
92
+ ],
93
+ };
94
+ case "cursor":
95
+ return {
96
+ host,
97
+ intro: "Create the rule in your project and add the MCP entry to .cursor/mcp.json.",
98
+ files: [
99
+ {
100
+ path: ".cursor/rules/tidegap.mdc",
101
+ format: "markdown",
102
+ content: `---\ndescription: ${DESCRIPTION}\nalwaysApply: false\n---\n\n${AGENTS_BLOCK}`,
103
+ },
104
+ { path: ".cursor/mcp.json", format: "json", content: mcpServers },
105
+ ],
106
+ };
107
+ case "gemini":
108
+ return {
109
+ host,
110
+ intro: "Add the block to GEMINI.md and merge the MCP entry into settings.json.",
111
+ files: [markdown("~/.gemini/GEMINI.md"), { path: "~/.gemini/settings.json", format: "json", content: mcpServers }],
112
+ };
113
+ }
114
+ }
115
+ /** The text `tidegap jobs snippet --host <host>` prints. */
116
+ export function renderAgentSnippet(host) {
117
+ const s = agentSnippet(host);
118
+ return [s.intro, ...s.files.map((f) => `${f.path}:\n\n${f.content.trimEnd()}`)].join("\n\n");
119
+ }
120
+ //# sourceMappingURL=agent-snippet.js.map
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Bot commands and button presses (KTD15, R27): parse text and callback
3
+ * data into typed commands, then run them through the same `Scheduler`
4
+ * methods the page uses. Every write re-reads the task and checks it is
5
+ * still in a state that allows the action; a `/queue` number resolves only
6
+ * against the last listing and expires after {@link LISTING_TTL_MS}.
7
+ * `/jobs` lists recurring jobs and pauses, resumes or runs one through the
8
+ * core job actions; its numbers come from the last `/jobs` only.
9
+ */
10
+ import { type PostponeOption, type PostponePreset, type PostponeTarget } from "../postpone.js";
11
+ import type { Scheduler } from "../scheduler.js";
12
+ import type { TaskStore } from "../storage/sqlite.js";
13
+ import type { JobRecord, TaskRecord } from "../types.js";
14
+ import { type CallbackActionName, type OutgoingMessage } from "./format.js";
15
+ /** `/queue` numbers expire after this long (R27). */
16
+ export declare const LISTING_TTL_MS: number;
17
+ /** A task named by its `/queue` number or by its id; a job by its `/jobs` number or id. */
18
+ export type TaskRef = {
19
+ n: number;
20
+ } | {
21
+ id: string;
22
+ };
23
+ /** The `/later` argument (KTD15 Telegram column). `HH:MM` is local time, the next such time after now. */
24
+ export type LaterArg = {
25
+ preset: Exclude<PostponePreset, "after_limit_reset">;
26
+ } | {
27
+ preset: "after_limit_reset";
28
+ resetClock?: string;
29
+ } | {
30
+ clock: string;
31
+ };
32
+ export type ChannelCommand = {
33
+ kind: "help";
34
+ } | {
35
+ kind: "queue";
36
+ }
37
+ /** `/pair <code>` or the deep-link form `/start <code>`. */
38
+ | {
39
+ kind: "pair";
40
+ code?: string;
41
+ } | {
42
+ kind: "later";
43
+ ref: TaskRef;
44
+ arg: LaterArg;
45
+ } | {
46
+ kind: "cancel";
47
+ ref: TaskRef;
48
+ } | {
49
+ kind: "run";
50
+ ref: TaskRef;
51
+ } | {
52
+ kind: "result";
53
+ ref: TaskRef;
54
+ } | {
55
+ kind: "jobs";
56
+ }
57
+ /** `/jobs <action> <n|id>`. */
58
+ | {
59
+ kind: "job";
60
+ action: JobAction;
61
+ ref: TaskRef;
62
+ }
63
+ /** A known command with bad arguments; `reply` says how to use it. */
64
+ | {
65
+ kind: "invalid";
66
+ reply: string;
67
+ } | {
68
+ kind: "unknown";
69
+ };
70
+ /** What `/jobs` can do to one job. */
71
+ export type JobAction = "pause" | "resume" | "run";
72
+ /** Parse a message text. A text that is not a command is `unknown`. */
73
+ export declare function parseCommand(text: string): ChannelCommand;
74
+ /** A parsed button press. `later` without a preset opens the Later ▾ menu. */
75
+ export interface CallbackAction {
76
+ action: CallbackActionName;
77
+ taskId: string;
78
+ preset?: PostponePreset;
79
+ }
80
+ /** Parse `callback_data` (`<action>:<task_id>[:<preset code>]`); null when malformed. */
81
+ export declare function parseCallback(data: string): CallbackAction | null;
82
+ /** The next local `HH:MM` after `now` (today, else tomorrow). */
83
+ export declare function nextClockTime(clock: string, now: Date): Date;
84
+ /** The core postpone target of a `/later` argument. */
85
+ export declare function laterTarget(arg: LaterArg, now: Date): PostponeTarget;
86
+ /** Which numbered listing of a chat: `/queue` tasks or `/jobs` jobs. */
87
+ export type ListingKind = "tasks" | "jobs";
88
+ /**
89
+ * The last `/queue` and `/jobs` listings of one chat: item n of a kind is
90
+ * `ids[n-1]` of that kind's last listing. In memory only, so a restart drops it.
91
+ */
92
+ export declare class QueueListing {
93
+ private readonly ttlMs;
94
+ private readonly lists;
95
+ constructor(ttlMs?: number);
96
+ set(ids: readonly string[], now: Date, kind?: ListingKind): void;
97
+ /** The id of item `n`, or null with no valid listing of that kind (none yet, or expired). */
98
+ resolve(n: number, now: Date, kind?: ListingKind): string | null | undefined;
99
+ }
100
+ /** What a command needs from the host: the ledger, the scheduler's task actions and the job actions. */
101
+ export interface CommandContext {
102
+ getTask(id: string): TaskRecord<unknown> | undefined;
103
+ /** Pending tasks, soonest first. */
104
+ pendingTasks(): TaskRecord<unknown>[];
105
+ postpone(id: string, target: PostponeTarget): Promise<unknown>;
106
+ cancel(id: string): unknown;
107
+ runNow(id: string): unknown;
108
+ laterOptions(record: TaskRecord<unknown>, now: Date): Promise<PostponeOption[]>;
109
+ /** Active and paused jobs, oldest first. */
110
+ listJobs(): JobRecord[];
111
+ /** A job that is not removed. */
112
+ getJob(id: string): JobRecord | undefined;
113
+ pauseJob(id: string): Promise<unknown>;
114
+ resumeJob(id: string): Promise<unknown>;
115
+ runJobNow(id: string): Promise<unknown>;
116
+ now(): Date;
117
+ }
118
+ /** A {@link CommandContext} over a core `Scheduler` and its `TaskStore`. */
119
+ export declare function commandContextFor(scheduler: Scheduler, store: TaskStore): CommandContext;
120
+ /** Run a parsed command for the paired chat. `pair` and `unknown` answer with help; the caller handles pairing. */
121
+ export declare function runCommand(cmd: ChannelCommand, ctx: CommandContext, listing: QueueListing): Promise<OutgoingMessage[]>;
122
+ /** What a host does for a button press: answer the query, maybe remove the pressed message's buttons, send messages. */
123
+ export interface CallbackOutcome {
124
+ answer: {
125
+ text?: string;
126
+ showAlert?: boolean;
127
+ };
128
+ removeButtons: boolean;
129
+ messages: OutgoingMessage[];
130
+ }
131
+ /**
132
+ * Run a button press. A press on a task whose state no longer allows the
133
+ * action answers with an alert naming the state, removes the buttons and
134
+ * writes nothing.
135
+ */
136
+ export declare function runCallback(data: string, ctx: CommandContext): Promise<CallbackOutcome>;
137
+ //# sourceMappingURL=commands.d.ts.map
@@ -0,0 +1,377 @@
1
+ /**
2
+ * Bot commands and button presses (KTD15, R27): parse text and callback
3
+ * data into typed commands, then run them through the same `Scheduler`
4
+ * methods the page uses. Every write re-reads the task and checks it is
5
+ * still in a state that allows the action; a `/queue` number resolves only
6
+ * against the last listing and expires after {@link LISTING_TTL_MS}.
7
+ * `/jobs` lists recurring jobs and pauses, resumes or runs one through the
8
+ * core job actions; its numbers come from the last `/jobs` only.
9
+ */
10
+ import { taskActions } from "../history.js";
11
+ import { getJob, JobActionError, listJobs, pauseJob, resumeJob, runJobNow } from "../jobs.js";
12
+ import { localTimeLabel, NEEDS_RESET_TIME, } from "../postpone.js";
13
+ import { CALLBACK_ACTIONS, CALLBACK_PRESETS, HELP_TEXT, JOB_RUNNING_NOW, jobNextLabel, JOBS_GRAMMAR, jobsMessage, jobTitle, LATER_GRAMMAR, laterMenuMessage, messageTitle, QUEUE_LIST_MAX, queueMessage, resultMessages, } from "./format.js";
14
+ /** `/queue` numbers expire after this long (R27). */
15
+ export const LISTING_TTL_MS = 10 * 60_000;
16
+ const JOB_ACTIONS = new Set(["pause", "resume", "run"]);
17
+ const CLOCK = /^([01]?\d|2[0-3]):([0-5]\d)$/;
18
+ function parseRef(word) {
19
+ if (!word)
20
+ return undefined;
21
+ if (/^\d{1,3}$/.test(word))
22
+ return { n: Number(word) };
23
+ return /^[A-Za-z0-9_~.-]{1,100}$/.test(word) ? { id: word } : undefined;
24
+ }
25
+ function refLabel(ref) {
26
+ return "n" in ref ? String(ref.n) : ref.id;
27
+ }
28
+ function parseLaterArg(words) {
29
+ const [w, extra] = words.map((x) => x.toLowerCase());
30
+ if (w === "1h" && extra === undefined)
31
+ return { preset: "1h" };
32
+ if (w === "tonight" && extra === undefined)
33
+ return { preset: "tonight" };
34
+ if (w === "tomorrow" && extra === undefined)
35
+ return { preset: "tomorrow_morning" };
36
+ if (w === "reset") {
37
+ if (extra === undefined)
38
+ return { preset: "after_limit_reset" };
39
+ return CLOCK.test(extra) && words.length === 2 ? { preset: "after_limit_reset", resetClock: extra } : undefined;
40
+ }
41
+ if (w !== undefined && CLOCK.test(w) && extra === undefined)
42
+ return { clock: w };
43
+ return undefined;
44
+ }
45
+ /** Parse a message text. A text that is not a command is `unknown`. */
46
+ export function parseCommand(text) {
47
+ const words = text.trim().split(/\s+/);
48
+ const head = words.shift() ?? "";
49
+ if (!head.startsWith("/"))
50
+ return { kind: "unknown" };
51
+ const name = head.slice(1).split("@")[0].toLowerCase();
52
+ switch (name) {
53
+ case "help":
54
+ return { kind: "help" };
55
+ case "queue":
56
+ return { kind: "queue" };
57
+ case "start":
58
+ case "pair":
59
+ return words[0] ? { kind: "pair", code: words[0] } : { kind: "pair" };
60
+ case "later": {
61
+ const ref = parseRef(words[0]);
62
+ const arg = parseLaterArg(words.slice(1));
63
+ return ref && arg ? { kind: "later", ref, arg } : { kind: "invalid", reply: `Usage: ${LATER_GRAMMAR}` };
64
+ }
65
+ case "jobs": {
66
+ if (words.length === 0)
67
+ return { kind: "jobs" };
68
+ const action = words[0].toLowerCase();
69
+ const ref = parseRef(words[1]);
70
+ if (!JOB_ACTIONS.has(action) || !ref || words.length > 2)
71
+ return { kind: "invalid", reply: `Usage: ${JOBS_GRAMMAR}` };
72
+ return { kind: "job", action: action, ref };
73
+ }
74
+ case "cancel":
75
+ case "run":
76
+ case "result": {
77
+ const ref = parseRef(words[0]);
78
+ if (!ref || words.length > 1)
79
+ return { kind: "invalid", reply: `Usage: /${name} <n|id>` };
80
+ return { kind: name, ref };
81
+ }
82
+ default:
83
+ return { kind: "unknown" };
84
+ }
85
+ }
86
+ /** Parse `callback_data` (`<action>:<task_id>[:<preset code>]`); null when malformed. */
87
+ export function parseCallback(data) {
88
+ const m = /^([a-z]):([A-Za-z0-9_~.-]{1,100}?)(?::([a-z]))?$/.exec(data);
89
+ if (!m)
90
+ return null;
91
+ const action = CALLBACK_ACTIONS[m[1]];
92
+ if (!action)
93
+ return null;
94
+ if (m[3] === undefined)
95
+ return { action, taskId: m[2] };
96
+ const preset = CALLBACK_PRESETS[m[3]];
97
+ if (action !== "later" || !preset)
98
+ return null;
99
+ return { action, taskId: m[2], preset };
100
+ }
101
+ /** The next local `HH:MM` after `now` (today, else tomorrow). */
102
+ export function nextClockTime(clock, now) {
103
+ const m = CLOCK.exec(clock);
104
+ if (!m)
105
+ throw new Error(`not HH:MM: ${clock}`);
106
+ const at = new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(m[1]), Number(m[2]), 0, 0);
107
+ if (at.getTime() <= now.getTime())
108
+ at.setDate(at.getDate() + 1);
109
+ return at;
110
+ }
111
+ /** The core postpone target of a `/later` argument. */
112
+ export function laterTarget(arg, now) {
113
+ if ("clock" in arg)
114
+ return { until: nextClockTime(arg.clock, now) };
115
+ if (arg.preset === "after_limit_reset") {
116
+ return arg.resetClock ? { preset: "after_limit_reset", resetAt: nextClockTime(arg.resetClock, now) } : { preset: "after_limit_reset" };
117
+ }
118
+ return { preset: arg.preset };
119
+ }
120
+ /**
121
+ * The last `/queue` and `/jobs` listings of one chat: item n of a kind is
122
+ * `ids[n-1]` of that kind's last listing. In memory only, so a restart drops it.
123
+ */
124
+ export class QueueListing {
125
+ ttlMs;
126
+ lists = new Map();
127
+ constructor(ttlMs = LISTING_TTL_MS) {
128
+ this.ttlMs = ttlMs;
129
+ }
130
+ set(ids, now, kind = "tasks") {
131
+ this.lists.set(kind, { ids: [...ids], at: now.getTime() });
132
+ }
133
+ /** The id of item `n`, or null with no valid listing of that kind (none yet, or expired). */
134
+ resolve(n, now, kind = "tasks") {
135
+ const list = this.lists.get(kind);
136
+ if (!list || now.getTime() - list.at > this.ttlMs)
137
+ return null;
138
+ return list.ids[n - 1];
139
+ }
140
+ }
141
+ const PENDING = ["running", "submitted", "scheduled", "queued"];
142
+ function plannedMs(r) {
143
+ const t = Date.parse(r.scheduledFor ?? r.notBefore ?? r.enqueuedAt);
144
+ return Number.isFinite(t) ? t : Number.MAX_SAFE_INTEGER;
145
+ }
146
+ /** A {@link CommandContext} over a core `Scheduler` and its `TaskStore`. */
147
+ export function commandContextFor(scheduler, store) {
148
+ return {
149
+ getTask: (id) => store.get(id),
150
+ pendingTasks: () => PENDING.flatMap((status) => store.list({ status }))
151
+ .sort((a, b) => plannedMs(a) - plannedMs(b))
152
+ .slice(0, QUEUE_LIST_MAX),
153
+ postpone: (id, target) => scheduler.postponeTask(id, target, { actor: "telegram" }),
154
+ cancel: (id) => scheduler.cancelTask(id, { actor: "telegram" }),
155
+ runNow: (id) => scheduler.runNow(id, { actor: "telegram" }),
156
+ laterOptions: (record, now) => scheduler.postponeOptionsFor(record, now),
157
+ listJobs: () => listJobs(scheduler),
158
+ getJob: (id) => {
159
+ const job = getJob(scheduler, id);
160
+ return job && job.status !== "removed" ? job : undefined;
161
+ },
162
+ pauseJob: (id) => pauseJob(scheduler, id, { actor: "telegram" }),
163
+ resumeJob: (id) => resumeJob(scheduler, id, { actor: "telegram" }),
164
+ runJobNow: (id) => runJobNow(scheduler, id, { actor: "telegram" }),
165
+ now: () => new Date(),
166
+ };
167
+ }
168
+ /** The refusal text of a scheduler error, without its `action: task <id>:` prefix. */
169
+ function refusalText(err) {
170
+ const msg = err instanceof Error ? err.message : String(err);
171
+ return msg.replace(/^[a-zA-Z]+: task \S+?:? /, "");
172
+ }
173
+ /** The id a ref names: a number resolves against the last listing of `kind`, an id passes through. */
174
+ function resolveId(ref, ctx, listing, kind) {
175
+ if (!("n" in ref))
176
+ return { ok: true, id: ref.id };
177
+ const [command, noun] = kind === "jobs" ? ["/jobs", "job"] : ["/queue", "task"];
178
+ const hit = listing.resolve(ref.n, ctx.now(), kind);
179
+ if (hit === null)
180
+ return { ok: false, reply: `Send ${command} first: ${noun} numbers come from the last ${command} and expire after 10 minutes.` };
181
+ if (hit === undefined)
182
+ return { ok: false, reply: `The last ${command} has no ${noun} ${ref.n}.` };
183
+ return { ok: true, id: hit };
184
+ }
185
+ function resolveTask(ref, ctx, listing) {
186
+ const resolved = resolveId(ref, ctx, listing, "tasks");
187
+ if (!resolved.ok)
188
+ return resolved;
189
+ const record = ctx.getTask(resolved.id);
190
+ return record ? { ok: true, record } : { ok: false, reply: `There is no task ${refLabel(ref)}.` };
191
+ }
192
+ function resolveJob(ref, ctx, listing) {
193
+ const resolved = resolveId(ref, ctx, listing, "jobs");
194
+ if (!resolved.ok)
195
+ return resolved;
196
+ const job = ctx.getJob(resolved.id);
197
+ return job ? { ok: true, job } : { ok: false, reply: `There is no job ${refLabel(ref)}.` };
198
+ }
199
+ const JOB_REFUSED = { pause: "Not paused", resume: "Not resumed", run: "Not started" };
200
+ /** Pause, resume or run one job. The state is checked first; a job action refusal is quoted, any other error is not. */
201
+ async function runJobAction(action, ref, ctx, listing) {
202
+ const res = resolveJob(ref, ctx, listing);
203
+ if (!res.ok)
204
+ return res.reply;
205
+ const { job } = res;
206
+ const title = jobTitle(job);
207
+ if (action === "pause" && job.status === "paused")
208
+ return `${title} is already paused.`;
209
+ if (action === "resume" && job.status !== "paused")
210
+ return `${title} is not paused.`;
211
+ if (action === "run" && job.status === "paused")
212
+ return `${title} is paused. Resume it first: /jobs resume ${refLabel(ref)}`;
213
+ try {
214
+ if (action === "pause")
215
+ await ctx.pauseJob(job.jobId);
216
+ else if (action === "resume")
217
+ await ctx.resumeJob(job.jobId);
218
+ else
219
+ await ctx.runJobNow(job.jobId);
220
+ }
221
+ catch (err) {
222
+ // Other exception text can hold paths or SQL: only the fixed job action refusals reach the chat.
223
+ const why = err instanceof JobActionError ? err.message : "unexpected error. Check the job on the page: tidegap ui";
224
+ return `${JOB_REFUSED[action]}: ${title}: ${why}`;
225
+ }
226
+ if (action === "pause")
227
+ return `Paused: ${title}.`;
228
+ if (action === "run")
229
+ return `Runs at the next tick: ${title}.`;
230
+ const after = ctx.getJob(job.jobId);
231
+ const next = after?.pendingTaskId ? jobNextLabel(after, ctx.getTask(after.pendingTaskId), ctx.now()) : undefined;
232
+ if (next === JOB_RUNNING_NOW)
233
+ return `Resumed: ${title}. A run is in progress.`;
234
+ return next ? `Resumed: ${title}. Next ${next}.` : `Resumed: ${title}.`;
235
+ }
236
+ /** "<title> is already completed." */
237
+ function notAllowed(record) {
238
+ return `${messageTitle(record)} is already ${record.status}.`;
239
+ }
240
+ /** The confirmation of a move: the title and the new earliest start, read back from the ledger. */
241
+ function movedText(id, ctx, now) {
242
+ const after = ctx.getTask(id);
243
+ const nb = after?.notBefore ?? after?.scheduledFor;
244
+ const at = nb ? localTimeLabel(new Date(nb), now) : "later";
245
+ return `Moved: ${after ? messageTitle(after) : id}. Not before ${at}.`;
246
+ }
247
+ /** Run a parsed command for the paired chat. `pair` and `unknown` answer with help; the caller handles pairing. */
248
+ export async function runCommand(cmd, ctx, listing) {
249
+ const now = ctx.now();
250
+ switch (cmd.kind) {
251
+ case "help":
252
+ case "unknown":
253
+ return [{ text: HELP_TEXT }];
254
+ case "pair":
255
+ return [{ text: "This chat is already paired." }];
256
+ case "invalid":
257
+ return [{ text: cmd.reply }];
258
+ case "queue": {
259
+ const msg = queueMessage(ctx.pendingTasks(), now);
260
+ listing.set(msg.ids, now);
261
+ return [{ text: msg.text, buttons: msg.buttons }];
262
+ }
263
+ case "jobs": {
264
+ const msg = jobsMessage(ctx.listJobs(), (id) => ctx.getTask(id), now);
265
+ listing.set(msg.ids, now, "jobs");
266
+ return [{ text: msg.text }];
267
+ }
268
+ case "job":
269
+ return [{ text: await runJobAction(cmd.action, cmd.ref, ctx, listing) }];
270
+ case "result": {
271
+ const res = resolveTask(cmd.ref, ctx, listing);
272
+ return res.ok ? resultMessages(res.record) : [{ text: res.reply }];
273
+ }
274
+ case "cancel": {
275
+ const res = resolveTask(cmd.ref, ctx, listing);
276
+ if (!res.ok)
277
+ return [{ text: res.reply }];
278
+ if (!taskActions(res.record).cancel)
279
+ return [{ text: notAllowed(res.record) }];
280
+ try {
281
+ ctx.cancel(res.record.taskId);
282
+ }
283
+ catch (err) {
284
+ return [{ text: `Not cancelled: ${refusalText(err)}` }];
285
+ }
286
+ return [{ text: `Cancelled: ${messageTitle(res.record)}.` }];
287
+ }
288
+ case "run": {
289
+ const res = resolveTask(cmd.ref, ctx, listing);
290
+ if (!res.ok)
291
+ return [{ text: res.reply }];
292
+ if (!taskActions(res.record).runNow)
293
+ return [{ text: `${messageTitle(res.record)} is ${res.record.status}; it cannot run now.` }];
294
+ try {
295
+ ctx.runNow(res.record.taskId);
296
+ }
297
+ catch (err) {
298
+ return [{ text: `Not started: ${refusalText(err)}` }];
299
+ }
300
+ return [{ text: `Runs at the next tick: ${messageTitle(res.record)}.` }];
301
+ }
302
+ case "later": {
303
+ const res = resolveTask(cmd.ref, ctx, listing);
304
+ if (!res.ok)
305
+ return [{ text: res.reply }];
306
+ if (!taskActions(res.record).later)
307
+ return [{ text: `${messageTitle(res.record)} is ${res.record.status}; it cannot move.` }];
308
+ try {
309
+ await ctx.postpone(res.record.taskId, laterTarget(cmd.arg, now));
310
+ }
311
+ catch (err) {
312
+ const why = refusalText(err);
313
+ if (why.includes(NEEDS_RESET_TIME)) {
314
+ return [{ text: `${NEEDS_RESET_TIME}: /later ${refLabel(cmd.ref)} reset HH:MM (for example /later ${refLabel(cmd.ref)} reset 14:05)` }];
315
+ }
316
+ return [{ text: `Not moved: ${messageTitle(res.record)}: ${why}` }];
317
+ }
318
+ return [{ text: movedText(res.record.taskId, ctx, now) }];
319
+ }
320
+ }
321
+ }
322
+ /**
323
+ * Run a button press. A press on a task whose state no longer allows the
324
+ * action answers with an alert naming the state, removes the buttons and
325
+ * writes nothing.
326
+ */
327
+ export async function runCallback(data, ctx) {
328
+ const action = parseCallback(data);
329
+ if (!action)
330
+ return { answer: { text: "This button is not valid any more." }, removeButtons: true, messages: [] };
331
+ const now = ctx.now();
332
+ const record = ctx.getTask(action.taskId);
333
+ if (!record)
334
+ return { answer: { text: "This task no longer exists.", showAlert: true }, removeButtons: true, messages: [] };
335
+ const allowed = taskActions(record);
336
+ const gone = () => ({ answer: { text: notAllowed(record), showAlert: true }, removeButtons: true, messages: [] });
337
+ const title = messageTitle(record);
338
+ switch (action.action) {
339
+ case "result":
340
+ return { answer: {}, removeButtons: false, messages: resultMessages(record) };
341
+ case "cancel":
342
+ if (!allowed.cancel)
343
+ return gone();
344
+ try {
345
+ ctx.cancel(record.taskId);
346
+ }
347
+ catch (err) {
348
+ return { answer: { text: refusalText(err), showAlert: true }, removeButtons: false, messages: [] };
349
+ }
350
+ return { answer: { text: "Cancelled" }, removeButtons: true, messages: [{ text: `Cancelled: ${title}.` }] };
351
+ case "run":
352
+ if (!allowed.runNow)
353
+ return gone();
354
+ try {
355
+ ctx.runNow(record.taskId);
356
+ }
357
+ catch (err) {
358
+ return { answer: { text: refusalText(err), showAlert: true }, removeButtons: false, messages: [] };
359
+ }
360
+ return { answer: { text: "Runs at the next tick" }, removeButtons: true, messages: [{ text: `Runs at the next tick: ${title}.` }] };
361
+ case "later": {
362
+ if (!allowed.later)
363
+ return gone();
364
+ if (!action.preset) {
365
+ return { answer: {}, removeButtons: false, messages: [laterMenuMessage(record, await ctx.laterOptions(record, now), now)] };
366
+ }
367
+ try {
368
+ await ctx.postpone(record.taskId, { preset: action.preset });
369
+ }
370
+ catch (err) {
371
+ return { answer: { text: refusalText(err), showAlert: true }, removeButtons: false, messages: [] };
372
+ }
373
+ return { answer: { text: "Moved" }, removeButtons: true, messages: [{ text: movedText(record.taskId, ctx, now) }] };
374
+ }
375
+ }
376
+ }
377
+ //# sourceMappingURL=commands.js.map