@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/dist/quota.d.ts CHANGED
@@ -20,6 +20,7 @@
20
20
  * and must be between 0 and 168. A malformed entry disables that label and
21
21
  * never throws. File I/O only; no environment reads.
22
22
  */
23
+ import type { SleepReading } from "./readiness.js";
23
24
  import type { Scheduler } from "./scheduler.js";
24
25
  export declare const DEFAULT_QUOTA_MARGIN_H = 2;
25
26
  /** One provider label's weekly reset. `weekday` is 0 = Sunday … 6 = Saturday. */
@@ -100,11 +101,15 @@ export declare function replanSweep(scheduler: Scheduler, now?: Date): Promise<s
100
101
  /**
101
102
  * The shared pre-tick step every ticker runs before `Scheduler.tick`
102
103
  * (`tidegap tick` and the OpenClaw interval loop): record `last_tick_at` in the
103
- * ledger, sweep passed quota deadlines, then re-plan unplanned rows the
104
- * forecast now reaches (`replanSweep`). Never throws.
104
+ * ledger, run the job sweep (record finished occurrences, keep one live
105
+ * occurrence per active job), sweep passed quota deadlines, then re-plan
106
+ * unplanned rows the forecast now reaches (`replanSweep`, which plans new
107
+ * job occurrences too). Never throws.
105
108
  */
106
109
  export declare function prepareTick(scheduler: Scheduler, opts: {
107
110
  quotaConfig: QuotaResetConfig;
108
111
  now?: Date;
112
+ /** The host's sleep counter now (the CLI tick), so a run the machine slept through is not failed as interrupted. */
113
+ sleepNow?: SleepReading | null;
109
114
  }): Promise<string[]>;
110
115
  //# sourceMappingURL=quota.d.ts.map
package/dist/quota.js CHANGED
@@ -22,6 +22,8 @@
22
22
  */
23
23
  import { existsSync, readFileSync } from "node:fs";
24
24
  import { carbonBudgetConfigPath, parseKeyValues } from "./budget.js";
25
+ import { sweepJobs } from "./jobs.js";
26
+ import { isValidTimeZone, zoneOffsetMs } from "./zone-time.js";
25
27
  const RESET_PREFIX = "TIDEGAP_QUOTA_RESET_";
26
28
  const MARGIN_PREFIX = "TIDEGAP_QUOTA_MARGIN_H_";
27
29
  export const DEFAULT_QUOTA_MARGIN_H = 2;
@@ -37,15 +39,6 @@ const WEEKDAY_NAMES = [
37
39
  "friday",
38
40
  "saturday",
39
41
  ];
40
- function isValidTimeZone(tz) {
41
- try {
42
- new Intl.DateTimeFormat("en-US", { timeZone: tz });
43
- return true;
44
- }
45
- catch {
46
- return false;
47
- }
48
- }
49
42
  /** `mon` or `monday` (any case) to 1; anything else to undefined. */
50
43
  function parseWeekday(raw) {
51
44
  const v = raw.toLowerCase();
@@ -116,22 +109,6 @@ export function loadQuotaResetConfig(opts = {}) {
116
109
  }
117
110
  return quotaResetConfigFromValues(values, opts.defaultTimeZone);
118
111
  }
119
- /** Offset of `timeZone` from UTC at `instantMs`, in ms (local - UTC). */
120
- function zoneOffsetMs(instantMs, timeZone) {
121
- const parts = new Intl.DateTimeFormat("en-US", {
122
- timeZone,
123
- hourCycle: "h23",
124
- year: "numeric",
125
- month: "2-digit",
126
- day: "2-digit",
127
- hour: "2-digit",
128
- minute: "2-digit",
129
- second: "2-digit",
130
- }).formatToParts(new Date(instantMs));
131
- const get = (t) => Number(parts.find((p) => p.type === t)?.value);
132
- const asUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
133
- return asUtc - Math.floor(instantMs / 1000) * 1000;
134
- }
135
112
  /** The UTC instant of local wall time y-m-d h:mi in `timeZone`. */
136
113
  function zonedToUtcMs(y, mo, d, h, mi, timeZone) {
137
114
  const wall = Date.UTC(y, mo, d, h, mi);
@@ -307,8 +284,10 @@ export async function replanSweep(scheduler, now = new Date()) {
307
284
  /**
308
285
  * The shared pre-tick step every ticker runs before `Scheduler.tick`
309
286
  * (`tidegap tick` and the OpenClaw interval loop): record `last_tick_at` in the
310
- * ledger, sweep passed quota deadlines, then re-plan unplanned rows the
311
- * forecast now reaches (`replanSweep`). Never throws.
287
+ * ledger, run the job sweep (record finished occurrences, keep one live
288
+ * occurrence per active job), sweep passed quota deadlines, then re-plan
289
+ * unplanned rows the forecast now reaches (`replanSweep`, which plans new
290
+ * job occurrences too). Never throws.
312
291
  */
313
292
  export async function prepareTick(scheduler, opts) {
314
293
  const now = opts.now ?? new Date();
@@ -319,6 +298,12 @@ export async function prepareTick(scheduler, opts) {
319
298
  catch (err) {
320
299
  messages.push(`could not record last_tick_at: ${errMessage(err)}`);
321
300
  }
301
+ try {
302
+ messages.push(...(await sweepJobs(scheduler, now, { sleepNow: opts.sleepNow })).messages);
303
+ }
304
+ catch (err) {
305
+ messages.push(`job sweep failed: ${errMessage(err)}`);
306
+ }
322
307
  messages.push(...(await sweepQuotaDeadlines(scheduler, opts.quotaConfig, now)));
323
308
  messages.push(...(await replanSweep(scheduler, now)));
324
309
  return messages;
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Readiness (coherence KTD1 to KTD3): one answer to "will queued tasks
3
+ * run?" from two facts, a ticker runs and each pending task's provider has
4
+ * a runner. Pure over facts the host gathers; core spawns nothing.
5
+ * A fact nobody can observe is "unknown" and raises no problem (R2).
6
+ */
7
+ import type { MetaStore } from "./postpone.js";
8
+ import { type DurationValue } from "./run-limits.js";
9
+ import type { TickDetails } from "./scheduler.js";
10
+ import type { TaskEvent } from "./task-events.js";
11
+ import type { TaskRecord, TaskStatus } from "./types.js";
12
+ /**
13
+ * The tick daemon as the host sees it. `installed` = the unit file exists
14
+ * and whether it is loaded was not probed; `unknown` = nothing on this
15
+ * host shows it (Windows, ledger-only hosts such as the MCP server).
16
+ */
17
+ export type DaemonFact = "loaded" | "installed" | "installed_not_loaded" | "not_installed" | "unknown";
18
+ /** Ledger meta `tick_runners`: the providers a tick's adapters served (KTD2). */
19
+ export interface TickRunnersSnapshot {
20
+ /** ISO-8601 time of the tick that wrote it. */
21
+ at: string;
22
+ providers: string[];
23
+ /** `skipped`: the macOS login-shell `claude` lookup did not run (nothing needed it). */
24
+ claude_lookup: "done" | "skipped";
25
+ }
26
+ /** Which providers have a runner; `unknown` lists providers nobody could check. */
27
+ export interface RunnerFact {
28
+ providers: string[];
29
+ unknown: string[];
30
+ source: "snapshot" | "probe";
31
+ /** Informational lines from the probe (a configured runner that cannot start). */
32
+ notes?: string[];
33
+ }
34
+ /**
35
+ * The machine's sleep counter at one moment: how long it slept since boot.
36
+ * Two readings of the same boot give the sleep between them, so a gap in
37
+ * the ticks that sleep explains raises no problem. The host reads it
38
+ * (macOS: `sysctl kern.waketime kern.wake_abs_time`; Linux: boot time minus
39
+ * the monotonic clock); core only compares readings.
40
+ */
41
+ export interface SleepReading {
42
+ /** Epoch ms of the boot; tells two boots apart. */
43
+ boot_at: number;
44
+ /** Total ms asleep since the boot. */
45
+ slept_ms: number;
46
+ /** Epoch ms of the last wake, when the host knows it (macOS). */
47
+ woke_at?: number;
48
+ /** Epoch ms of the tick that stored the reading (ledger meta only). */
49
+ at?: number;
50
+ }
51
+ /** Ledger meta key of the {@link SleepReading} the last CLI tick took. */
52
+ export declare const TICK_SLEEP_META_KEY = "last_tick_sleep";
53
+ /**
54
+ * Ledger meta key: who started the last CLI tick. `unit` is the launchd or
55
+ * systemd unit or a `tick --daemon` loop; `manual` is a one-off
56
+ * `tidegap tick --once` from a shell, which proves nothing about the unit.
57
+ */
58
+ export declare const TICK_BY_META_KEY = "last_tick_by";
59
+ /**
60
+ * Ms asleep between two readings; 0 when they cannot be compared (missing,
61
+ * another boot, a counter that went back). Never more than `wallGapMs`.
62
+ */
63
+ export declare function sleptBetween(then: SleepReading | null | undefined, now: SleepReading | null | undefined, wallGapMs: number): number;
64
+ /**
65
+ * True when the sleep counter is worth reading now: a stored reading exists
66
+ * and the wall gap since the last tick is over two intervals (shorter gaps
67
+ * raise no problem, so the read is skipped). Shared by every host.
68
+ */
69
+ export declare function sleepReadNeeded(lastTickSleep: SleepReading | null | undefined, lastTickAt: string | null | undefined, now: Date, intervalS: number): boolean;
70
+ /** Read the {@link TICK_SLEEP_META_KEY} reading with its tick time; null when absent or malformed. */
71
+ export declare function readTickSleep(store: Pick<MetaStore, "getMeta">): SleepReading | null;
72
+ /**
73
+ * Write the reading of the tick at `at`; null removes it. The tick time is
74
+ * stored with it: another ticker (the OpenClaw loop) can move `last_tick_at`
75
+ * without a reading, and an old reading must never pair with a newer tick.
76
+ */
77
+ export declare function writeTickSleep(store: Pick<MetaStore, "setMeta"> & {
78
+ deleteMeta(key: string): void;
79
+ }, reading: SleepReading | null, at: Date): void;
80
+ export interface ReadinessFacts {
81
+ daemon: DaemonFact;
82
+ /** Ledger meta `last_tick_at`, or null when no ticker ever ran. */
83
+ lastTickAt?: string | Date | null;
84
+ /**
85
+ * The sleep reading the last tick took (ledger meta `last_tick_sleep`).
86
+ * Used only when its `at` is within one interval of `lastTickAt`.
87
+ */
88
+ lastTickSleep?: SleepReading | null;
89
+ /** The sleep reading now. Both readings: sleep after the last tick does not count as a missed tick. */
90
+ sleepNow?: SleepReading | null;
91
+ /** The daemon's last exit code (`launchctl print`), when known. */
92
+ daemonLastExit?: number | null;
93
+ /** Names the machine in the sleep note: "the Mac" on darwin, else "the computer". */
94
+ platform?: NodeJS.Platform;
95
+ /** Seconds between ticks; default 300 with a daemon on disk, else 60. */
96
+ tickIntervalS?: number;
97
+ /** Null when no runner fact is known (no fresh snapshot, no probe). */
98
+ runners: RunnerFact | null;
99
+ /** Pending provider-call tasks by provider. */
100
+ pendingByProvider: Record<string, number>;
101
+ /**
102
+ * The oldest `running` row a locked Node tick dispatched ({@link oldestTickRun}).
103
+ * The tick runs due rows one at a time, so this run holds every other due
104
+ * task while it lasts.
105
+ */
106
+ oldestRun?: OldestRun | null;
107
+ now?: Date;
108
+ }
109
+ /** A run that holds the tick: its task, when its dispatch began, and its time limit when known. */
110
+ export interface OldestRun {
111
+ taskId: string;
112
+ /** ISO-8601 time of its `dispatched` event. */
113
+ startedAt: string;
114
+ timeLimit?: DurationValue;
115
+ }
116
+ export type ReadinessCode = "no_daemon" | "daemon_not_loaded" | "daemon_stale" | "long_run" | "no_runner";
117
+ /** Problems of the ticker, not of the runners: only a process outside the tick can see them (KTD11). */
118
+ export declare const TICKER_CODES: readonly ReadinessCode[];
119
+ export interface ReadinessProblem {
120
+ code: ReadinessCode;
121
+ /** One plain sentence (R3). */
122
+ message: string;
123
+ /** The fix: a command (`tidegap install`) or one instruction. */
124
+ fix: string;
125
+ /** `no_runner` only. */
126
+ provider?: string;
127
+ /** `no_runner` only: pending tasks of that provider. */
128
+ tasks?: number;
129
+ /** `long_run` only: the task that holds the tick. */
130
+ task_id?: string;
131
+ }
132
+ /** The readiness result every surface shows; JSON as-is in the API and MCP. */
133
+ export interface Readiness {
134
+ ready: boolean;
135
+ /** Ordered `no_daemon`, `daemon_not_loaded`, `daemon_stale`, `long_run`, `no_runner`. */
136
+ problems: ReadinessProblem[];
137
+ /** The first problem's sentence plus its fix; null when ready. */
138
+ line: string | null;
139
+ /** Informational lines that are not problems ("first tick within 5 minutes"). */
140
+ notes: string[];
141
+ /**
142
+ * `recent`: no ticker problem. `slept_s`: seconds the machine slept since
143
+ * the last tick (0 when unknown); that time is not counted as missed ticks.
144
+ */
145
+ ticker: {
146
+ daemon: DaemonFact;
147
+ last_tick_at: string | null;
148
+ interval_s: number;
149
+ recent: boolean;
150
+ slept_s: number;
151
+ last_exit: number | null;
152
+ };
153
+ runners: {
154
+ source: "snapshot" | "probe" | "unknown";
155
+ providers: string[];
156
+ unknown: string[];
157
+ };
158
+ }
159
+ /** Ledger meta key of the {@link TickRunnersSnapshot}. */
160
+ export declare const TICK_RUNNERS_META_KEY = "tick_runners";
161
+ /** The default tick interval for a daemon fact (as `DispatcherControl` uses). */
162
+ export declare function tickIntervalFor(daemon: DaemonFact): number;
163
+ /** Line text: a command fix reads "Run `cmd`."; an instruction reads "Fix: ...". */
164
+ export declare function problemLine(p: ReadinessProblem): string;
165
+ /** Assess readiness from gathered facts (KTD1, KTD3). */
166
+ export declare function assessReadiness(facts: ReadinessFacts): Readiness;
167
+ /** The runner fact of a snapshot: a skipped lookup leaves `claude-code` and key-less `anthropic` unknown. */
168
+ export declare function runnersFromSnapshot(snapshot: TickRunnersSnapshot): RunnerFact;
169
+ /** True when `snapshot` is at most two tick intervals old (KTD2: then it wins over live probes). */
170
+ export declare function snapshotIsFresh(snapshot: TickRunnersSnapshot, now: Date, intervalS: number): boolean;
171
+ /** Read the `tick_runners` snapshot; null when absent or malformed. */
172
+ export declare function readTickRunners(store: Pick<MetaStore, "getMeta">): TickRunnersSnapshot | null;
173
+ /** Write the `tick_runners` snapshot (every CLI tick, KTD2). */
174
+ export declare function writeTickRunners(store: Pick<MetaStore, "setMeta">, snapshot: TickRunnersSnapshot): void;
175
+ /**
176
+ * Pending (queued, scheduled, submitted) provider-call tasks by provider. A
177
+ * command job occurrence counts for `command` (the CLI tick runs it) and for
178
+ * its summarize step's provider, which needs a runner too.
179
+ */
180
+ export declare function pendingProvidersFromStore(store: {
181
+ list(filter: {
182
+ status: TaskStatus;
183
+ }): Array<{
184
+ bodyJson?: string;
185
+ }>;
186
+ }): Record<string, number>;
187
+ /** A row's newest event, progress lines aside, when it is a dispatch by a locked tick: its tick and time. */
188
+ export declare function tickDispatch(events: readonly TaskEvent[]): {
189
+ tick: TickDetails;
190
+ at: string;
191
+ } | undefined;
192
+ /**
193
+ * The oldest `running` row a locked Node tick dispatched (the readiness
194
+ * `long_run` fact), or null. A row another writer runs (the Python tick, the
195
+ * MCP server) holds no Node tick and is left out. So is a Batch row: it is
196
+ * `running` only while a poll checks its batch, and its dispatch is the
197
+ * submit, hours before.
198
+ */
199
+ export declare function oldestTickRun(store: {
200
+ list(filter: {
201
+ status: TaskStatus;
202
+ }): Array<Pick<TaskRecord<unknown>, "taskId" | "bodyJson" | "batchId">>;
203
+ listTaskEvents(taskId: string): TaskEvent[];
204
+ }): OldestRun | null;
205
+ //# sourceMappingURL=readiness.d.ts.map
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Readiness (coherence KTD1 to KTD3): one answer to "will queued tasks
3
+ * run?" from two facts, a ticker runs and each pending task's provider has
4
+ * a runner. Pure over facts the host gathers; core spawns nothing.
5
+ * A fact nobody can observe is "unknown" and raises no problem (R2).
6
+ */
7
+ import { formatDuration, runLimitsFromDetails, versionedCaps } from "./run-limits.js";
8
+ /** Ledger meta key of the {@link SleepReading} the last CLI tick took. */
9
+ export const TICK_SLEEP_META_KEY = "last_tick_sleep";
10
+ /**
11
+ * Ledger meta key: who started the last CLI tick. `unit` is the launchd or
12
+ * systemd unit or a `tick --daemon` loop; `manual` is a one-off
13
+ * `tidegap tick --once` from a shell, which proves nothing about the unit.
14
+ */
15
+ export const TICK_BY_META_KEY = "last_tick_by";
16
+ /** Two readings this far apart in boot time belong to different boots. */
17
+ const BOOT_TOLERANCE_MS = 120_000;
18
+ /** Sleep shorter than this explains nothing and is not shown. */
19
+ const SLEEP_MIN_MS = 60_000;
20
+ /**
21
+ * Ms asleep between two readings; 0 when they cannot be compared (missing,
22
+ * another boot, a counter that went back). Never more than `wallGapMs`.
23
+ */
24
+ export function sleptBetween(then, now, wallGapMs) {
25
+ if (!then || !now || Math.abs(then.boot_at - now.boot_at) > BOOT_TOLERANCE_MS)
26
+ return 0;
27
+ const slept = now.slept_ms - then.slept_ms;
28
+ return Number.isFinite(slept) && slept > 0 ? Math.min(slept, Math.max(0, wallGapMs)) : 0;
29
+ }
30
+ /**
31
+ * True when the sleep counter is worth reading now: a stored reading exists
32
+ * and the wall gap since the last tick is over two intervals (shorter gaps
33
+ * raise no problem, so the read is skipped). Shared by every host.
34
+ */
35
+ export function sleepReadNeeded(lastTickSleep, lastTickAt, now, intervalS) {
36
+ return !!lastTickSleep && now.getTime() - Date.parse(lastTickAt ?? "") > 2 * intervalS * 1000;
37
+ }
38
+ /** Read the {@link TICK_SLEEP_META_KEY} reading with its tick time; null when absent or malformed. */
39
+ export function readTickSleep(store) {
40
+ const raw = store.getMeta(TICK_SLEEP_META_KEY);
41
+ if (!raw)
42
+ return null;
43
+ try {
44
+ const v = JSON.parse(raw);
45
+ if (!Number.isFinite(v.boot_at) || !Number.isFinite(v.slept_ms) || !Number.isFinite(v.at))
46
+ return null;
47
+ return { boot_at: v.boot_at, slept_ms: v.slept_ms, at: v.at };
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ /**
54
+ * Write the reading of the tick at `at`; null removes it. The tick time is
55
+ * stored with it: another ticker (the OpenClaw loop) can move `last_tick_at`
56
+ * without a reading, and an old reading must never pair with a newer tick.
57
+ */
58
+ export function writeTickSleep(store, reading, at) {
59
+ if (reading)
60
+ store.setMeta(TICK_SLEEP_META_KEY, JSON.stringify({ boot_at: reading.boot_at, slept_ms: reading.slept_ms, at: at.getTime() }));
61
+ else
62
+ store.deleteMeta(TICK_SLEEP_META_KEY);
63
+ }
64
+ /** Problems of the ticker, not of the runners: only a process outside the tick can see them (KTD11). */
65
+ export const TICKER_CODES = ["no_daemon", "daemon_not_loaded", "daemon_stale"];
66
+ /** Ledger meta key of the {@link TickRunnersSnapshot}. */
67
+ export const TICK_RUNNERS_META_KEY = "tick_runners";
68
+ const DAEMON_INTERVAL_S = 300;
69
+ const NO_DAEMON_INTERVAL_S = 60;
70
+ const ENV_FILE = "~/.config/tidegap/env";
71
+ const INSTALL = "tidegap install";
72
+ const TICK_ONCE = "tidegap tick --once";
73
+ const ORDER = ["no_daemon", "daemon_not_loaded", "daemon_stale", "long_run", "no_runner"];
74
+ const PENDING = ["queued", "scheduled", "submitted"];
75
+ /** The fix for a provider with no runner. */
76
+ const RUNNER_FIX = {
77
+ anthropic: `install Claude Code, or add ANTHROPIC_API_KEY to ${ENV_FILE}`,
78
+ "claude-code": `install Claude Code, or set TIDEGAP_CLAUDE_BIN in ${ENV_FILE}`,
79
+ openai: `add OPENAI_API_KEY to ${ENV_FILE}`,
80
+ gemini: `add GEMINI_API_KEY to ${ENV_FILE}`,
81
+ ollama: `set OLLAMA_HOST in ${ENV_FILE}`,
82
+ // Only the CLI tick runs a command job's shell step.
83
+ command: INSTALL,
84
+ };
85
+ function daemonOnDisk(d) {
86
+ return d === "loaded" || d === "installed" || d === "installed_not_loaded";
87
+ }
88
+ /** The default tick interval for a daemon fact (as `DispatcherControl` uses). */
89
+ export function tickIntervalFor(daemon) {
90
+ return daemonOnDisk(daemon) ? DAEMON_INTERVAL_S : NO_DAEMON_INTERVAL_S;
91
+ }
92
+ /** Line text: a command fix reads "Run `cmd`."; an instruction reads "Fix: ...". */
93
+ export function problemLine(p) {
94
+ if (p.fix === TICK_ONCE)
95
+ return `${p.message} Run \`${p.fix}\` and check the error.`;
96
+ return p.fix.startsWith("tidegap ") ? `${p.message} Run \`${p.fix}\`.` : `${p.message} Fix: ${p.fix}.`;
97
+ }
98
+ /** Local HH:MM. */
99
+ function hhmm(ms) {
100
+ const d = new Date(ms);
101
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
102
+ }
103
+ /**
104
+ * "paused while the Mac slept (11:05–11:24)". The clock window needs the
105
+ * wake time and fits only one sleep after the last tick; else the length.
106
+ */
107
+ function sleepNote(sleptMs, lastMs, nowMs, wokeAt, platform) {
108
+ const machine = platform === "darwin" ? "the Mac" : "the computer";
109
+ const when = wokeAt !== undefined && wokeAt - sleptMs >= lastMs && wokeAt <= nowMs
110
+ ? `${hhmm(wokeAt - sleptMs)}–${hhmm(wokeAt)}`
111
+ : `about ${Math.round(sleptMs / 60_000)} minutes`;
112
+ return `the tick daemon paused while ${machine} slept (${when})`;
113
+ }
114
+ /** Assess readiness from gathered facts (KTD1, KTD3). */
115
+ export function assessReadiness(facts) {
116
+ const now = facts.now ?? new Date();
117
+ const intervalS = facts.tickIntervalS ?? tickIntervalFor(facts.daemon);
118
+ const last = facts.lastTickAt ? new Date(facts.lastTickAt) : null;
119
+ const lastMs = last && Number.isFinite(last.getTime()) ? last.getTime() : null;
120
+ const wallGap = lastMs === null ? 0 : now.getTime() - lastMs;
121
+ const then = facts.lastTickSleep;
122
+ const paired = then?.at !== undefined && lastMs !== null && Math.abs(then.at - lastMs) <= intervalS * 1000 ? then : null;
123
+ const slept = sleptBetween(paired, facts.sleepNow, wallGap);
124
+ const asleep = slept >= SLEEP_MIN_MS;
125
+ // Missed ticks are counted on awake time only. After a sleep, launchd may
126
+ // start a new interval at the wake, so one more interval is allowed.
127
+ const recent = lastMs !== null && wallGap - slept <= (asleep ? 3 : 2) * intervalS * 1000;
128
+ const lastExit = typeof facts.daemonLastExit === "number" ? facts.daemonLastExit : null;
129
+ const problems = [];
130
+ const notes = [];
131
+ if (recent && asleep && wallGap > 2 * intervalS * 1000) {
132
+ notes.push(sleepNote(slept, lastMs, now.getTime(), facts.sleepNow?.woke_at, facts.platform));
133
+ }
134
+ if (!recent) {
135
+ const d = facts.daemon;
136
+ if (d === "installed_not_loaded") {
137
+ problems.push({
138
+ code: "daemon_not_loaded",
139
+ message: "Tasks will not run: the tick daemon is installed but not loaded.",
140
+ fix: INSTALL,
141
+ });
142
+ }
143
+ else if (d === "loaded" || d === "installed") {
144
+ if (lastMs === null) {
145
+ notes.push("first tick within 5 minutes");
146
+ }
147
+ else {
148
+ // A loaded unit that stopped ticking needs the tick's own error, not a reinstall.
149
+ const min = Math.round(wallGap / 60_000);
150
+ const exited = d === "loaded" && lastExit !== null && lastExit !== 0 ? ` and exited with code ${lastExit}` : "";
151
+ problems.push({
152
+ code: "daemon_stale",
153
+ message: `Tasks may not run: the tick daemon last ran ${min} minutes ago${exited}.`,
154
+ fix: d === "loaded" ? TICK_ONCE : INSTALL,
155
+ });
156
+ }
157
+ }
158
+ else {
159
+ problems.push({ code: "no_daemon", message: "Tasks will not run: no tick daemon.", fix: INSTALL });
160
+ }
161
+ }
162
+ const run = facts.oldestRun;
163
+ const runMs = run ? now.getTime() - Date.parse(run.startedAt) : NaN;
164
+ if (run && runMs > 2 * intervalS * 1000) {
165
+ const limit = run.timeLimit === undefined ? "" : run.timeLimit === "none" ? " (no time limit)" : ` (time limit ${formatDuration(run.timeLimit)})`;
166
+ problems.push({
167
+ code: "long_run",
168
+ message: `Task ${run.taskId} has run for ${Math.floor(runMs / 60_000)} minutes${limit}; due tasks wait until it ends.`,
169
+ fix: `tidegap queue cancel ${run.taskId}`,
170
+ task_id: run.taskId,
171
+ });
172
+ }
173
+ const runners = facts.runners;
174
+ if (runners?.notes)
175
+ notes.push(...runners.notes);
176
+ if (runners) {
177
+ for (const [provider, count] of Object.entries(facts.pendingByProvider).sort(([a], [b]) => a.localeCompare(b))) {
178
+ if (count <= 0 || runners.providers.includes(provider) || runners.unknown.includes(provider))
179
+ continue;
180
+ // Only a CLI tick runs the shell step and its snapshot names `command`; a
181
+ // probe cannot see it, and a tick that is not running is a ticker problem.
182
+ if (provider === "command" && runners.source !== "snapshot")
183
+ continue;
184
+ problems.push({
185
+ code: "no_runner",
186
+ message: `Tasks will not run: ${count} ${provider} ${count === 1 ? "task has" : "tasks have"} no runner.`,
187
+ fix: RUNNER_FIX[provider] ?? `configure the ${provider} provider in ${ENV_FILE}`,
188
+ provider,
189
+ tasks: count,
190
+ });
191
+ }
192
+ }
193
+ problems.sort((a, b) => ORDER.indexOf(a.code) - ORDER.indexOf(b.code));
194
+ return {
195
+ ready: problems.length === 0,
196
+ problems,
197
+ line: problems[0] ? problemLine(problems[0]) : null,
198
+ notes,
199
+ ticker: { daemon: facts.daemon, last_tick_at: lastMs === null ? null : new Date(lastMs).toISOString(), interval_s: intervalS, recent, slept_s: Math.round(slept / 1000), last_exit: lastExit },
200
+ runners: runners
201
+ ? { source: runners.source, providers: [...runners.providers], unknown: [...runners.unknown] }
202
+ : { source: "unknown", providers: [], unknown: [] },
203
+ };
204
+ }
205
+ /** The runner fact of a snapshot: a skipped lookup leaves `claude-code` and key-less `anthropic` unknown. */
206
+ export function runnersFromSnapshot(snapshot) {
207
+ const providers = [...snapshot.providers];
208
+ const unknown = snapshot.claude_lookup === "skipped" ? ["claude-code", "anthropic"].filter((p) => !providers.includes(p)) : [];
209
+ return { providers, unknown, source: "snapshot" };
210
+ }
211
+ /** True when `snapshot` is at most two tick intervals old (KTD2: then it wins over live probes). */
212
+ export function snapshotIsFresh(snapshot, now, intervalS) {
213
+ const at = Date.parse(snapshot.at);
214
+ return Number.isFinite(at) && now.getTime() - at <= 2 * intervalS * 1000;
215
+ }
216
+ /** Read the `tick_runners` snapshot; null when absent or malformed. */
217
+ export function readTickRunners(store) {
218
+ const raw = store.getMeta(TICK_RUNNERS_META_KEY);
219
+ if (!raw)
220
+ return null;
221
+ try {
222
+ const v = JSON.parse(raw);
223
+ if (typeof v.at !== "string" || !Array.isArray(v.providers))
224
+ return null;
225
+ return {
226
+ at: v.at,
227
+ providers: v.providers.filter((p) => typeof p === "string"),
228
+ claude_lookup: v.claude_lookup === "skipped" ? "skipped" : "done",
229
+ };
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ }
235
+ /** Write the `tick_runners` snapshot (every CLI tick, KTD2). */
236
+ export function writeTickRunners(store, snapshot) {
237
+ store.setMeta(TICK_RUNNERS_META_KEY, JSON.stringify(snapshot));
238
+ }
239
+ /**
240
+ * Pending (queued, scheduled, submitted) provider-call tasks by provider. A
241
+ * command job occurrence counts for `command` (the CLI tick runs it) and for
242
+ * its summarize step's provider, which needs a runner too.
243
+ */
244
+ export function pendingProvidersFromStore(store) {
245
+ const out = {};
246
+ const add = (p) => {
247
+ if (typeof p === "string")
248
+ out[p] = (out[p] ?? 0) + 1;
249
+ };
250
+ for (const status of PENDING) {
251
+ for (const rec of store.list({ status })) {
252
+ let body;
253
+ try {
254
+ body = JSON.parse(rec.bodyJson ?? "");
255
+ }
256
+ catch {
257
+ continue;
258
+ }
259
+ add(body?.provider);
260
+ if (body?.provider === "command")
261
+ add(body.summarize?.provider);
262
+ }
263
+ }
264
+ return out;
265
+ }
266
+ /** A row's newest event, progress lines aside, when it is a dispatch by a locked tick: its tick and time. */
267
+ export function tickDispatch(events) {
268
+ let last;
269
+ for (let i = events.length - 1; i >= 0 && !last; i--)
270
+ if (events[i].kind !== "progress")
271
+ last = events[i];
272
+ if (last?.kind !== "dispatched")
273
+ return undefined;
274
+ const t = last.details.tick;
275
+ if (!t || typeof t.id !== "string" || !Number.isInteger(t.pid))
276
+ return undefined;
277
+ return { tick: { id: t.id, pid: t.pid, ...(typeof t.started_at === "string" ? { started_at: t.started_at } : {}) }, at: last.at };
278
+ }
279
+ /**
280
+ * The time limit of a run (the command limit of a command row, else the LLM
281
+ * limit): the one its `dispatched` event recorded, else, for a run dispatched
282
+ * before limits were recorded, the one its row names itself (an old stored
283
+ * default counts as unset). Undefined when neither is known.
284
+ */
285
+ function runTimeLimit(bodyJson, details) {
286
+ let spec;
287
+ try {
288
+ spec = JSON.parse(bodyJson ?? "");
289
+ }
290
+ catch {
291
+ spec = undefined;
292
+ }
293
+ const command = spec?.provider === "command";
294
+ const recorded = runLimitsFromDetails(details);
295
+ if (recorded)
296
+ return (command ? recorded.command_timeout : recorded.llm_timeout)?.value;
297
+ if (!spec?.caps || typeof spec.caps !== "object")
298
+ return undefined;
299
+ const caps = versionedCaps(spec.caps);
300
+ const value = command ? caps.commandTimeoutMs : caps.llmTimeoutMs;
301
+ return value === "none" || (typeof value === "number" && value > 0) ? value : undefined;
302
+ }
303
+ /**
304
+ * The oldest `running` row a locked Node tick dispatched (the readiness
305
+ * `long_run` fact), or null. A row another writer runs (the Python tick, the
306
+ * MCP server) holds no Node tick and is left out. So is a Batch row: it is
307
+ * `running` only while a poll checks its batch, and its dispatch is the
308
+ * submit, hours before.
309
+ */
310
+ export function oldestTickRun(store) {
311
+ let oldest = null;
312
+ for (const row of store.list({ status: "running" })) {
313
+ if (row.batchId)
314
+ continue;
315
+ const events = store.listTaskEvents(row.taskId);
316
+ const dispatch = tickDispatch(events);
317
+ if (!dispatch || (oldest && Date.parse(oldest.startedAt) <= Date.parse(dispatch.at)))
318
+ continue;
319
+ // tickDispatch found it: the newest event apart from progress lines.
320
+ const dispatched = [...events].reverse().find((e) => e.kind !== "progress");
321
+ const timeLimit = runTimeLimit(row.bodyJson, dispatched?.details);
322
+ oldest = { taskId: row.taskId, startedAt: dispatch.at, ...(timeLimit !== undefined ? { timeLimit } : {}) };
323
+ }
324
+ return oldest;
325
+ }
326
+ //# sourceMappingURL=readiness.js.map