@tidegap/core 0.18.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 (171) hide show
  1. package/README.md +3 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/budget.d.ts +0 -12
  5. package/dist/budget.js +2 -24
  6. package/dist/channels/commands.d.ts +137 -0
  7. package/dist/channels/commands.js +377 -0
  8. package/dist/channels/delivery-codes.d.ts +9 -0
  9. package/dist/channels/delivery-codes.js +53 -0
  10. package/dist/channels/digest.d.ts +102 -0
  11. package/dist/channels/digest.js +146 -0
  12. package/dist/channels/format.d.ts +127 -0
  13. package/dist/channels/format.js +407 -0
  14. package/dist/channels/index.d.ts +15 -0
  15. package/dist/channels/index.js +15 -0
  16. package/dist/channels/kinds/command.d.ts +13 -0
  17. package/dist/channels/kinds/command.js +65 -0
  18. package/dist/channels/kinds/discord.d.ts +16 -0
  19. package/dist/channels/kinds/discord.js +67 -0
  20. package/dist/channels/kinds/email.d.ts +20 -0
  21. package/dist/channels/kinds/email.js +162 -0
  22. package/dist/channels/kinds/index.d.ts +8 -0
  23. package/dist/channels/kinds/index.js +17 -0
  24. package/dist/channels/kinds/ntfy.d.ts +25 -0
  25. package/dist/channels/kinds/ntfy.js +163 -0
  26. package/dist/channels/kinds/pushover.d.ts +11 -0
  27. package/dist/channels/kinds/pushover.js +77 -0
  28. package/dist/channels/kinds/shared.d.ts +25 -0
  29. package/dist/channels/kinds/shared.js +39 -0
  30. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  31. package/dist/channels/kinds/shortcuts.js +45 -0
  32. package/dist/channels/kinds/slack.d.ts +8 -0
  33. package/dist/channels/kinds/slack.js +57 -0
  34. package/dist/channels/kinds/telegram.d.ts +4 -0
  35. package/dist/channels/kinds/telegram.js +26 -0
  36. package/dist/channels/kinds/webhook.d.ts +30 -0
  37. package/dist/channels/kinds/webhook.js +177 -0
  38. package/dist/channels/payload.d.ts +36 -0
  39. package/dist/channels/payload.js +61 -0
  40. package/dist/channels/plan.d.ts +24 -0
  41. package/dist/channels/plan.js +66 -0
  42. package/dist/channels/registry.d.ts +191 -0
  43. package/dist/channels/registry.js +125 -0
  44. package/dist/channels/telegram.d.ts +110 -0
  45. package/dist/channels/telegram.js +168 -0
  46. package/dist/channels/types.d.ts +107 -0
  47. package/dist/channels/types.js +26 -0
  48. package/dist/claude-tools.d.ts +29 -0
  49. package/dist/claude-tools.js +49 -0
  50. package/dist/data/tables.generated.d.ts +6 -0
  51. package/dist/data/tables.generated.js +37 -0
  52. package/dist/energy.d.ts +77 -0
  53. package/dist/energy.js +131 -0
  54. package/dist/grid.d.ts +19 -2
  55. package/dist/grid.js +84 -28
  56. package/dist/handoff.d.ts +152 -0
  57. package/dist/handoff.js +430 -0
  58. package/dist/history.d.ts +2 -0
  59. package/dist/history.js +3 -1
  60. package/dist/index.d.ts +46 -16
  61. package/dist/index.js +34 -8
  62. package/dist/job-cadence.d.ts +76 -0
  63. package/dist/job-cadence.js +240 -0
  64. package/dist/jobs.d.ts +173 -0
  65. package/dist/jobs.js +794 -0
  66. package/dist/notify.d.ts +2 -0
  67. package/dist/notify.js +2 -1
  68. package/dist/paths.d.ts +13 -46
  69. package/dist/paths.js +51 -219
  70. package/dist/postpone.d.ts +113 -0
  71. package/dist/postpone.js +185 -0
  72. package/dist/providers/anthropic.js +7 -3
  73. package/dist/providers/base.d.ts +113 -1
  74. package/dist/providers/base.js +15 -0
  75. package/dist/providers/budget.d.ts +25 -0
  76. package/dist/providers/budget.js +57 -0
  77. package/dist/providers/defaults.js +4 -0
  78. package/dist/providers/defer.d.ts +16 -0
  79. package/dist/providers/defer.js +31 -0
  80. package/dist/providers/gemini.d.ts +1 -0
  81. package/dist/providers/gemini.js +27 -20
  82. package/dist/providers/index.d.ts +2 -2
  83. package/dist/providers/index.js +1 -1
  84. package/dist/providers/ollama.d.ts +1 -0
  85. package/dist/providers/ollama.js +26 -22
  86. package/dist/providers/openai.js +5 -5
  87. package/dist/providers/timeout.d.ts +18 -0
  88. package/dist/providers/timeout.js +33 -0
  89. package/dist/quota.d.ts +7 -2
  90. package/dist/quota.js +13 -29
  91. package/dist/readiness.d.ts +169 -0
  92. package/dist/readiness.js +254 -0
  93. package/dist/redact.d.ts +42 -0
  94. package/dist/redact.js +110 -0
  95. package/dist/region-host.d.ts +30 -0
  96. package/dist/region-host.js +69 -0
  97. package/dist/region.d.ts +102 -20
  98. package/dist/region.js +175 -23
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +95 -0
  102. package/dist/schedule-job.js +195 -0
  103. package/dist/scheduler.d.ts +245 -14
  104. package/dist/scheduler.js +925 -110
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +157 -5
  108. package/dist/storage/sqlite.js +661 -20
  109. package/dist/task-events.d.ts +102 -0
  110. package/dist/task-events.js +308 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +359 -65
  113. package/dist/types.d.ts +246 -3
  114. package/dist/types.js +8 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +11 -6
  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
@@ -19,6 +19,7 @@
19
19
  * hosted providers. There is no special-cased "local" carbon logic here.
20
20
  */
21
21
  import { conversation } from "./base.js";
22
+ import { withLlmTimeout } from "./timeout.js";
22
23
  const DEFAULT_HOST = "http://localhost:11434";
23
24
  /** Normalize a host string into a scheme-qualified base URL with no trailing slash. */
24
25
  function normalizeHost(raw) {
@@ -67,31 +68,34 @@ export class OllamaAdapter {
67
68
  body.options = ollamaOptions;
68
69
  }
69
70
  const url = `${this.host}/api/chat`;
70
- let res;
71
- try {
72
- res = await fetchImpl(url, {
73
- method: "POST",
74
- headers: { "content-type": "application/json" },
75
- body: JSON.stringify(body),
76
- });
77
- }
78
- catch (err) {
79
- // Connection refused / DNS / TLS — the local server is not reachable.
80
- const detail = err instanceof Error ? err.message : String(err);
81
- throw new Error(`OllamaAdapter: could not reach Ollama at ${this.host} (${detail}). ` +
82
- `Is \`ollama serve\` running? Set OLLAMA_HOST to override the address.`);
83
- }
84
- if (!res.ok) {
85
- let detail = "";
71
+ const data = (await withLlmTimeout(this.provider, options.timeoutMs, async (request) => {
72
+ let res;
86
73
  try {
87
- detail = (await res.text()).slice(0, 300);
74
+ res = await fetchImpl(url, {
75
+ method: "POST",
76
+ headers: { "content-type": "application/json" },
77
+ body: JSON.stringify(body),
78
+ ...(request ? { signal: request.signal } : {}),
79
+ });
88
80
  }
89
- catch {
90
- detail = "(no response body)";
81
+ catch (err) {
82
+ // Connection refused / DNS / TLS — the local server is not reachable.
83
+ const detail = err instanceof Error ? err.message : String(err);
84
+ throw new Error(`OllamaAdapter: could not reach Ollama at ${this.host} (${detail}). ` +
85
+ `Is \`ollama serve\` running? Set OLLAMA_HOST to override the address.`);
91
86
  }
92
- throw new Error(`Ollama API ${res.status}: ${detail}`);
93
- }
94
- const data = (await res.json());
87
+ if (!res.ok) {
88
+ let detail = "";
89
+ try {
90
+ detail = (await res.text()).slice(0, 300);
91
+ }
92
+ catch {
93
+ detail = "(no response body)";
94
+ }
95
+ throw new Error(`Ollama API ${res.status}: ${detail}`);
96
+ }
97
+ return res.json();
98
+ }));
95
99
  const inputTokens = data.prompt_eval_count;
96
100
  const outputTokens = data.eval_count;
97
101
  return {
@@ -10,6 +10,8 @@
10
10
  * to /v1/files, then referenced by id from POST /v1/batches.
11
11
  */
12
12
  import { conversation } from "./base.js";
13
+ import { budgetMaxTokens } from "./budget.js";
14
+ import { withLlmTimeout } from "./timeout.js";
13
15
  /** o-series reasoning models (o1, o3, o4-mini, …). */
14
16
  function isOSeriesModel(model) {
15
17
  return /^o\d/.test(model.trim().toLowerCase());
@@ -57,13 +59,11 @@ export class OpenAIAdapter {
57
59
  return Boolean(this.client) || Boolean(this.apiKey);
58
60
  }
59
61
  async dispatch(model, prompt, options = {}) {
62
+ const maxTokens = budgetMaxTokens(model, prompt, options);
60
63
  const client = await this.getClient();
61
64
  const messages = chatMessages(prompt, options);
62
- const res = (await client.chat.completions.create({
63
- model,
64
- messages,
65
- ...completionParams(model, options),
66
- }));
65
+ const req = { model, messages, ...completionParams(model, { ...options, maxTokens }) };
66
+ const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => request ? client.chat.completions.create(req, request) : client.chat.completions.create(req)));
67
67
  const text = res.choices?.[0]?.message?.content ?? "";
68
68
  return {
69
69
  text,
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The model time limit of an API adapter (KTD14): a job's `llmTimeoutMs`
3
+ * reaches the adapter as `timeoutMs`. The call gets an abort signal, and the
4
+ * dispatch rejects when the limit passes, even when the client ignores the
5
+ * signal. An SDK client also gets the limit as its own request timeout, so
6
+ * its default (10 minutes) cannot end a longer call first, unlabelled. The error names the cap in its details (`stopped_by:
7
+ * "llm_timeout"`), so no caller reads the message text for it, and it is
8
+ * not retried: the limit is spent.
9
+ */
10
+ /** The longest delay `setTimeout` honours; a larger one fires at once. Every timer that takes a user's limit clamps to it. */
11
+ export declare const MAX_TIMER_MS: number;
12
+ /** What an SDK request takes: the abort signal and its own timeout (the same limit, clamped). */
13
+ export interface LlmRequestOptions {
14
+ signal: AbortSignal;
15
+ timeout: number;
16
+ }
17
+ export declare function withLlmTimeout<T>(provider: string, timeoutMs: number | undefined, call: (request: LlmRequestOptions | undefined) => Promise<T>): Promise<T>;
18
+ //# sourceMappingURL=timeout.d.ts.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The model time limit of an API adapter (KTD14): a job's `llmTimeoutMs`
3
+ * reaches the adapter as `timeoutMs`. The call gets an abort signal, and the
4
+ * dispatch rejects when the limit passes, even when the client ignores the
5
+ * signal. An SDK client also gets the limit as its own request timeout, so
6
+ * its default (10 minutes) cannot end a longer call first, unlabelled. The error names the cap in its details (`stopped_by:
7
+ * "llm_timeout"`), so no caller reads the message text for it, and it is
8
+ * not retried: the limit is spent.
9
+ */
10
+ import { NonRetryableError } from "./base.js";
11
+ /** The longest delay `setTimeout` honours; a larger one fires at once. Every timer that takes a user's limit clamps to it. */
12
+ export const MAX_TIMER_MS = 2 ** 31 - 1;
13
+ export async function withLlmTimeout(provider, timeoutMs, call) {
14
+ if (timeoutMs === undefined || !Number.isFinite(timeoutMs) || timeoutMs <= 0)
15
+ return call(undefined);
16
+ const controller = new AbortController();
17
+ const limit = Math.min(timeoutMs, MAX_TIMER_MS);
18
+ let timer;
19
+ const expired = new Promise((_, reject) => {
20
+ timer = setTimeout(() => {
21
+ // Settled before the abort, so a client that rejects on abort at once cannot win the race.
22
+ reject(new NonRetryableError(`${provider}: timed out after ${timeoutMs / 1000}s`, { stopped_by: "llm_timeout" }));
23
+ controller.abort();
24
+ }, limit);
25
+ });
26
+ try {
27
+ return await Promise.race([call({ signal: controller.signal, timeout: limit }), expired]);
28
+ }
29
+ finally {
30
+ clearTimeout(timer);
31
+ }
32
+ }
33
+ //# sourceMappingURL=timeout.js.map
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
@@ -21,7 +21,9 @@
21
21
  * never throws. File I/O only; no environment reads.
22
22
  */
23
23
  import { existsSync, readFileSync } from "node:fs";
24
- import { carbonBudgetConfigPath, parseKeyValues, withTidegapKeys } from "./budget.js";
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();
@@ -79,7 +72,6 @@ export function parseQuotaResetValue(label, value, marginH, defaultTimeZone) {
79
72
  /** Parse quota schedules out of already-read KEY=VALUE pairs. */
80
73
  export function quotaResetConfigFromValues(values, defaultTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone) {
81
74
  const out = {};
82
- values = withTidegapKeys(values);
83
75
  for (const [key, value] of Object.entries(values)) {
84
76
  if (!key.startsWith(RESET_PREFIX))
85
77
  continue;
@@ -117,22 +109,6 @@ export function loadQuotaResetConfig(opts = {}) {
117
109
  }
118
110
  return quotaResetConfigFromValues(values, opts.defaultTimeZone);
119
111
  }
120
- /** Offset of `timeZone` from UTC at `instantMs`, in ms (local - UTC). */
121
- function zoneOffsetMs(instantMs, timeZone) {
122
- const parts = new Intl.DateTimeFormat("en-US", {
123
- timeZone,
124
- hourCycle: "h23",
125
- year: "numeric",
126
- month: "2-digit",
127
- day: "2-digit",
128
- hour: "2-digit",
129
- minute: "2-digit",
130
- second: "2-digit",
131
- }).formatToParts(new Date(instantMs));
132
- const get = (t) => Number(parts.find((p) => p.type === t)?.value);
133
- const asUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
134
- return asUtc - Math.floor(instantMs / 1000) * 1000;
135
- }
136
112
  /** The UTC instant of local wall time y-m-d h:mi in `timeZone`. */
137
113
  function zonedToUtcMs(y, mo, d, h, mi, timeZone) {
138
114
  const wall = Date.UTC(y, mo, d, h, mi);
@@ -308,8 +284,10 @@ export async function replanSweep(scheduler, now = new Date()) {
308
284
  /**
309
285
  * The shared pre-tick step every ticker runs before `Scheduler.tick`
310
286
  * (`tidegap tick` and the OpenClaw interval loop): record `last_tick_at` in the
311
- * ledger, sweep passed quota deadlines, then re-plan unplanned rows the
312
- * 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.
313
291
  */
314
292
  export async function prepareTick(scheduler, opts) {
315
293
  const now = opts.now ?? new Date();
@@ -320,6 +298,12 @@ export async function prepareTick(scheduler, opts) {
320
298
  catch (err) {
321
299
  messages.push(`could not record last_tick_at: ${errMessage(err)}`);
322
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
+ }
323
307
  messages.push(...(await sweepQuotaDeadlines(scheduler, opts.quotaConfig, now)));
324
308
  messages.push(...(await replanSweep(scheduler, now)));
325
309
  return messages;
@@ -0,0 +1,169 @@
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 { TaskStatus } from "./types.js";
9
+ /**
10
+ * The tick daemon as the host sees it. `installed` = the unit file exists
11
+ * and whether it is loaded was not probed; `unknown` = nothing on this
12
+ * host shows it (Windows, ledger-only hosts such as the MCP server).
13
+ */
14
+ export type DaemonFact = "loaded" | "installed" | "installed_not_loaded" | "not_installed" | "unknown";
15
+ /** Ledger meta `tick_runners`: the providers a tick's adapters served (KTD2). */
16
+ export interface TickRunnersSnapshot {
17
+ /** ISO-8601 time of the tick that wrote it. */
18
+ at: string;
19
+ providers: string[];
20
+ /** `skipped`: the macOS login-shell `claude` lookup did not run (nothing needed it). */
21
+ claude_lookup: "done" | "skipped";
22
+ }
23
+ /** Which providers have a runner; `unknown` lists providers nobody could check. */
24
+ export interface RunnerFact {
25
+ providers: string[];
26
+ unknown: string[];
27
+ source: "snapshot" | "probe";
28
+ /** Informational lines from the probe (a configured runner that cannot start). */
29
+ notes?: string[];
30
+ }
31
+ /**
32
+ * The machine's sleep counter at one moment: how long it slept since boot.
33
+ * Two readings of the same boot give the sleep between them, so a gap in
34
+ * the ticks that sleep explains raises no problem. The host reads it
35
+ * (macOS: `sysctl kern.waketime kern.wake_abs_time`; Linux: boot time minus
36
+ * the monotonic clock); core only compares readings.
37
+ */
38
+ export interface SleepReading {
39
+ /** Epoch ms of the boot; tells two boots apart. */
40
+ boot_at: number;
41
+ /** Total ms asleep since the boot. */
42
+ slept_ms: number;
43
+ /** Epoch ms of the last wake, when the host knows it (macOS). */
44
+ woke_at?: number;
45
+ /** Epoch ms of the tick that stored the reading (ledger meta only). */
46
+ at?: number;
47
+ }
48
+ /** Ledger meta key of the {@link SleepReading} the last CLI tick took. */
49
+ export declare const TICK_SLEEP_META_KEY = "last_tick_sleep";
50
+ /**
51
+ * Ledger meta key: who started the last CLI tick. `unit` is the launchd or
52
+ * systemd unit or a `tick --daemon` loop; `manual` is a one-off
53
+ * `tidegap tick --once` from a shell, which proves nothing about the unit.
54
+ */
55
+ export declare const TICK_BY_META_KEY = "last_tick_by";
56
+ /**
57
+ * Ms asleep between two readings; 0 when they cannot be compared (missing,
58
+ * another boot, a counter that went back). Never more than `wallGapMs`.
59
+ */
60
+ export declare function sleptBetween(then: SleepReading | null | undefined, now: SleepReading | null | undefined, wallGapMs: number): number;
61
+ /**
62
+ * True when the sleep counter is worth reading now: a stored reading exists
63
+ * and the wall gap since the last tick is over two intervals (shorter gaps
64
+ * raise no problem, so the read is skipped). Shared by every host.
65
+ */
66
+ export declare function sleepReadNeeded(lastTickSleep: SleepReading | null | undefined, lastTickAt: string | null | undefined, now: Date, intervalS: number): boolean;
67
+ /** Read the {@link TICK_SLEEP_META_KEY} reading with its tick time; null when absent or malformed. */
68
+ export declare function readTickSleep(store: Pick<MetaStore, "getMeta">): SleepReading | null;
69
+ /**
70
+ * Write the reading of the tick at `at`; null removes it. The tick time is
71
+ * stored with it: another ticker (the OpenClaw loop) can move `last_tick_at`
72
+ * without a reading, and an old reading must never pair with a newer tick.
73
+ */
74
+ export declare function writeTickSleep(store: Pick<MetaStore, "setMeta"> & {
75
+ deleteMeta(key: string): void;
76
+ }, reading: SleepReading | null, at: Date): void;
77
+ export interface ReadinessFacts {
78
+ daemon: DaemonFact;
79
+ /** Ledger meta `last_tick_at`, or null when no ticker ever ran. */
80
+ lastTickAt?: string | Date | null;
81
+ /**
82
+ * The sleep reading the last tick took (ledger meta `last_tick_sleep`).
83
+ * Used only when its `at` is within one interval of `lastTickAt`.
84
+ */
85
+ lastTickSleep?: SleepReading | null;
86
+ /** The sleep reading now. Both readings: sleep after the last tick does not count as a missed tick. */
87
+ sleepNow?: SleepReading | null;
88
+ /** The daemon's last exit code (`launchctl print`), when known. */
89
+ daemonLastExit?: number | null;
90
+ /** Names the machine in the sleep note: "the Mac" on darwin, else "the computer". */
91
+ platform?: NodeJS.Platform;
92
+ /** Seconds between ticks; default 300 with a daemon on disk, else 60. */
93
+ tickIntervalS?: number;
94
+ /** Null when no runner fact is known (no fresh snapshot, no probe). */
95
+ runners: RunnerFact | null;
96
+ /** Pending provider-call tasks by provider. */
97
+ pendingByProvider: Record<string, number>;
98
+ now?: Date;
99
+ }
100
+ export type ReadinessCode = "no_daemon" | "daemon_not_loaded" | "daemon_stale" | "no_runner";
101
+ /** Problems of the ticker, not of the runners: only a process outside the tick can see them (KTD11). */
102
+ export declare const TICKER_CODES: readonly ReadinessCode[];
103
+ export interface ReadinessProblem {
104
+ code: ReadinessCode;
105
+ /** One plain sentence (R3). */
106
+ message: string;
107
+ /** The fix: a command (`tidegap install`) or one instruction. */
108
+ fix: string;
109
+ /** `no_runner` only. */
110
+ provider?: string;
111
+ /** `no_runner` only: pending tasks of that provider. */
112
+ tasks?: number;
113
+ }
114
+ /** The readiness result every surface shows; JSON as-is in the API and MCP. */
115
+ export interface Readiness {
116
+ ready: boolean;
117
+ /** Ordered `no_daemon`, `daemon_not_loaded`, `daemon_stale`, `no_runner`. */
118
+ problems: ReadinessProblem[];
119
+ /** The first problem's sentence plus its fix; null when ready. */
120
+ line: string | null;
121
+ /** Informational lines that are not problems ("first tick within 5 minutes"). */
122
+ notes: string[];
123
+ /**
124
+ * `recent`: no ticker problem. `slept_s`: seconds the machine slept since
125
+ * the last tick (0 when unknown); that time is not counted as missed ticks.
126
+ */
127
+ ticker: {
128
+ daemon: DaemonFact;
129
+ last_tick_at: string | null;
130
+ interval_s: number;
131
+ recent: boolean;
132
+ slept_s: number;
133
+ last_exit: number | null;
134
+ };
135
+ runners: {
136
+ source: "snapshot" | "probe" | "unknown";
137
+ providers: string[];
138
+ unknown: string[];
139
+ };
140
+ }
141
+ /** Ledger meta key of the {@link TickRunnersSnapshot}. */
142
+ export declare const TICK_RUNNERS_META_KEY = "tick_runners";
143
+ /** The default tick interval for a daemon fact (as `DispatcherControl` uses). */
144
+ export declare function tickIntervalFor(daemon: DaemonFact): number;
145
+ /** Line text: a command fix reads "Run `cmd`."; an instruction reads "Fix: ...". */
146
+ export declare function problemLine(p: ReadinessProblem): string;
147
+ /** Assess readiness from gathered facts (KTD1, KTD3). */
148
+ export declare function assessReadiness(facts: ReadinessFacts): Readiness;
149
+ /** The runner fact of a snapshot: a skipped lookup leaves `claude-code` and key-less `anthropic` unknown. */
150
+ export declare function runnersFromSnapshot(snapshot: TickRunnersSnapshot): RunnerFact;
151
+ /** True when `snapshot` is at most two tick intervals old (KTD2: then it wins over live probes). */
152
+ export declare function snapshotIsFresh(snapshot: TickRunnersSnapshot, now: Date, intervalS: number): boolean;
153
+ /** Read the `tick_runners` snapshot; null when absent or malformed. */
154
+ export declare function readTickRunners(store: Pick<MetaStore, "getMeta">): TickRunnersSnapshot | null;
155
+ /** Write the `tick_runners` snapshot (every CLI tick, KTD2). */
156
+ export declare function writeTickRunners(store: Pick<MetaStore, "setMeta">, snapshot: TickRunnersSnapshot): void;
157
+ /**
158
+ * Pending (queued, scheduled, submitted) provider-call tasks by provider. A
159
+ * command job occurrence counts for `command` (the CLI tick runs it) and for
160
+ * its summarize step's provider, which needs a runner too.
161
+ */
162
+ export declare function pendingProvidersFromStore(store: {
163
+ list(filter: {
164
+ status: TaskStatus;
165
+ }): Array<{
166
+ bodyJson?: string;
167
+ }>;
168
+ }): Record<string, number>;
169
+ //# sourceMappingURL=readiness.d.ts.map