@tidegap/core 0.21.0 → 0.22.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.
@@ -56,7 +56,7 @@ export function digestDue(now, lastIso, at = DEFAULT_DIGEST_AT) {
56
56
  return { due, since };
57
57
  }
58
58
  /** Most characters (code points, ellipsis included) of a run preview a job line quotes. */
59
- const JOB_PREVIEW_CHARS = 60;
59
+ const JOB_PREVIEW_CHARS = 100;
60
60
  /** `Mail triage: ok 03:12, "3 messages need a reply..." - next Fri 02:00` (KTD11). */
61
61
  export function jobDigestText(job) {
62
62
  const { last } = job;
@@ -22,7 +22,7 @@ import { type PostponeOption, type PostponePreset } from "../postpone.js";
22
22
  import { type ReadinessProblem } from "../readiness.js";
23
23
  import type { JobRecord, TaskRecord } from "../types.js";
24
24
  import { type InlineKeyboard } from "./telegram.js";
25
- import type { ChannelEvent, CleanWindowEvent, JobPausedNotice } from "./types.js";
25
+ import type { ChannelEvent, CleanWindowEvent, JobEndedNotice, JobPausedNotice } from "./types.js";
26
26
  /** Characters of result text a done message previews (Q4). */
27
27
  export declare const TELEGRAM_PREVIEW_CHARS = 600;
28
28
  /** Most messages one `/result` sends before pointing to `tidegap queue show`. */
@@ -54,12 +54,19 @@ export declare function isRedactedTask(record: TaskRecord<unknown>): boolean;
54
54
  /**
55
55
  * The one-line preview of a run, the same on the jobs page and in the
56
56
  * digest (KTD6): a failed task's first error line with visible text, a
57
- * completed task's result text unless it redacts its receipt, else
58
- * undefined. Default-redacted, control characters removed, whitespace runs
59
- * joined; a longer text is cut to `maxChars - 1` code points plus "…", so
60
- * the result never exceeds `maxChars`.
57
+ * completed task's summary, or its result text without one, unless it
58
+ * redacts its receipt, else undefined. Default-redacted, control characters
59
+ * removed, whitespace runs joined; a longer text is cut to `maxChars - 1`
60
+ * code points plus "…", so the result never exceeds `maxChars`.
61
61
  */
62
62
  export declare function runPreview(record: TaskRecord<unknown>, maxChars: number): string | undefined;
63
+ /**
64
+ * A run's verdict, the one line a person reads first: for a completed run
65
+ * that does not redact its receipt, the first line of its summary, else of
66
+ * its result text; for a failed run, its first error line. Cut to
67
+ * `maxChars`; undefined when there is no such line.
68
+ */
69
+ export declare function runVerdict(record: TaskRecord<unknown>, maxChars?: number): string | undefined;
63
70
  /** `text` cut to `maxChars - 1` code points plus "…" when longer, so it never exceeds `maxChars` (KTD6). */
64
71
  export declare function cutPreview(text: string, maxChars: number): string;
65
72
  /** The title a message shows: `displayTitle`, one line, at most 80 characters, else the task id. */
@@ -68,10 +75,12 @@ export declare function messageTitle(record: TaskRecord<unknown>): string;
68
75
  export declare function eventTitle(record: TaskRecord<unknown>, jobTitle?: string): string;
69
76
  /**
70
77
  * Task done (R26): title, time, where it ran, the preview or the redaction
71
- * note, and a [Result] button. A job occurrence (`jobTitle`) leads with
72
- * `<job title>: <result>` (jobs R22).
78
+ * note, and a [Result] button with the raw result. A job occurrence
79
+ * (`jobTitle`) leads with `<job title> — <verdict>`, adds the job's next run
80
+ * (`jobNext`) to the time line, a `No summary` line when its summarize step
81
+ * failed, and shows its summary in place of the raw preview.
73
82
  */
74
- export declare function taskDoneMessage(record: TaskRecord<unknown>, now?: Date, jobTitle?: string): OutgoingMessage;
83
+ export declare function taskDoneMessage(record: TaskRecord<unknown>, now?: Date, jobTitle?: string, jobNext?: string): OutgoingMessage;
75
84
  /**
76
85
  * Task failed: title, time, the first error line, the show command. No
77
86
  * buttons. A job occurrence (`jobTitle`) leads with `<job title>: failed`.
@@ -81,6 +90,12 @@ export declare function taskFailedMessage(record: TaskRecord<unknown>, now?: Dat
81
90
  export declare function jobPausedTitle(notice: JobPausedNotice): string;
82
91
  /** The auto-pause notice: the sentence, then how to resume. No buttons. */
83
92
  export declare function jobPausedMessage(notice: JobPausedNotice): OutgoingMessage;
93
+ /** The first line of a job's final notice: `Job ended: "<title>"`. */
94
+ export declare function jobEndedTitle(notice: JobEndedNotice): string;
95
+ /** The body of a job's final notice: why it ended, then its last run with its verdict, or its first error line. */
96
+ export declare function jobEndedBody(notice: JobEndedNotice, last: TaskRecord<unknown>): string;
97
+ /** A job's final notice: the title line and the body. No buttons. */
98
+ export declare function jobEndedMessage(notice: JobEndedNotice, last: TaskRecord<unknown>): OutgoingMessage;
84
99
  /** A clean window starting. No buttons. */
85
100
  export declare function cleanWindowMessage(window: CleanWindowEvent, now?: Date): OutgoingMessage;
86
101
  /**
@@ -18,8 +18,8 @@
18
18
  * | not ready | none |
19
19
  * | replies and `/result` | none |
20
20
  */
21
- import { displayTitle, stripControlChars, taskActions, taskResultText } from "../history.js";
22
- import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason } from "../jobs.js";
21
+ import { displayTitle, stripControlChars, taskActions, taskResultText, taskSummaryError, taskSummaryText } from "../history.js";
22
+ import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason, jobEndText } from "../jobs.js";
23
23
  import { clip, firstErrorLine, oneLine } from "../notify.js";
24
24
  import { localTimeLabel } from "../postpone.js";
25
25
  import { problemLine, TICKER_CODES } from "../readiness.js";
@@ -29,6 +29,8 @@ import { freshReasonText, shortSessionId } from "../run-session.js";
29
29
  import { TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX } from "./telegram.js";
30
30
  /** Characters of result text a done message previews (Q4). */
31
31
  export const TELEGRAM_PREVIEW_CHARS = 600;
32
+ /** Most characters of the verdict a job's notice leads with. */
33
+ const VERDICT_CHARS = 120;
32
34
  /** Most messages one `/result` sends before pointing to `tidegap queue show`. */
33
35
  export const RESULT_MAX_PARTS = 4;
34
36
  /** Tasks one `/queue` lists. */
@@ -65,19 +67,42 @@ export function isRedactedTask(record) {
65
67
  /**
66
68
  * The one-line preview of a run, the same on the jobs page and in the
67
69
  * digest (KTD6): a failed task's first error line with visible text, a
68
- * completed task's result text unless it redacts its receipt, else
69
- * undefined. Default-redacted, control characters removed, whitespace runs
70
- * joined; a longer text is cut to `maxChars - 1` code points plus "…", so
71
- * the result never exceeds `maxChars`.
70
+ * completed task's summary, or its result text without one, unless it
71
+ * redacts its receipt, else undefined. Default-redacted, control characters
72
+ * removed, whitespace runs joined; a longer text is cut to `maxChars - 1`
73
+ * code points plus "…", so the result never exceeds `maxChars`.
72
74
  */
73
75
  export function runPreview(record, maxChars) {
74
76
  let text;
75
77
  if (record.status === "failed")
76
78
  text = firstErrorLine(record.error, Infinity);
77
79
  else if (record.status === "completed" && !isRedactedTask(record))
78
- text = oneLine(taskResultText(record) ?? "");
80
+ text = oneLine(taskSummaryText(record) ?? taskResultText(record) ?? "");
79
81
  return text ? cutPreview(text, maxChars) : undefined;
80
82
  }
83
+ /** The first line of `text` with visible text, made one line (default-redacted), or undefined. */
84
+ function firstVisibleLine(text) {
85
+ for (const line of (text ?? "").split(/\r?\n/)) {
86
+ const one = oneLine(line);
87
+ if (one)
88
+ return one;
89
+ }
90
+ return undefined;
91
+ }
92
+ /**
93
+ * A run's verdict, the one line a person reads first: for a completed run
94
+ * that does not redact its receipt, the first line of its summary, else of
95
+ * its result text; for a failed run, its first error line. Cut to
96
+ * `maxChars`; undefined when there is no such line.
97
+ */
98
+ export function runVerdict(record, maxChars = VERDICT_CHARS) {
99
+ let line;
100
+ if (record.status === "failed")
101
+ line = firstErrorLine(record.error, Infinity);
102
+ else if (record.status === "completed" && !isRedactedTask(record))
103
+ line = firstVisibleLine(taskSummaryText(record) ?? taskResultText(record));
104
+ return line ? cutPreview(line, maxChars) : undefined;
105
+ }
81
106
  /** `text` cut to `maxChars - 1` code points plus "…" when longer, so it never exceeds `maxChars` (KTD6). */
82
107
  export function cutPreview(text, maxChars) {
83
108
  const chars = Array.from(text);
@@ -88,9 +113,13 @@ export function messageTitle(record) {
88
113
  const t = stripControlChars(displayTitle(record) ?? "").trim();
89
114
  return t ? clip(t, 80) : record.taskId;
90
115
  }
91
- /** Result text safe to send: default-redacted, control characters removed, newlines kept. */
116
+ /** Text safe to send: default-redacted, control characters removed, newlines kept. */
117
+ function safeText(text) {
118
+ return stripControlChars(redactPrompt(text ?? "", undefined), { multiline: true }).trim();
119
+ }
120
+ /** Result text safe to send. */
92
121
  function safeResult(record) {
93
- return stripControlChars(redactPrompt(taskResultText(record) ?? "", undefined), { multiline: true }).trim();
122
+ return safeText(taskResultText(record));
94
123
  }
95
124
  function showCommand(record) {
96
125
  return `tidegap queue show ${record.taskId}`;
@@ -125,27 +154,65 @@ function cleanJobTitle(title) {
125
154
  export function eventTitle(record, jobTitle) {
126
155
  return cleanJobTitle(jobTitle) ?? messageTitle(record);
127
156
  }
157
+ /**
158
+ * The body of a job run's notice: the summary without its verdict line (the
159
+ * whole summary when that line was cut), else the raw preview when the
160
+ * output has more than its verdict line; "" when there is nothing more.
161
+ */
162
+ function jobDoneBody(record) {
163
+ const summary = safeText(taskSummaryText(record));
164
+ const result = summary ? "" : safeResult(record);
165
+ const verdict = firstVisibleLine(summary || result);
166
+ const cut = verdict !== undefined && Array.from(verdict).length > VERDICT_CHARS;
167
+ if (summary) {
168
+ const rest = cut ? summary : summary.replace(/^\s*[^\n]*\n?/, "").trim();
169
+ return clip(rest, TELEGRAM_PREVIEW_CHARS);
170
+ }
171
+ const preview = clip(result, TELEGRAM_PREVIEW_CHARS);
172
+ return cut || /\n/.test(preview) ? preview : "";
173
+ }
128
174
  /**
129
175
  * Task done (R26): title, time, where it ran, the preview or the redaction
130
- * note, and a [Result] button. A job occurrence (`jobTitle`) leads with
131
- * `<job title>: <result>` (jobs R22).
176
+ * note, and a [Result] button with the raw result. A job occurrence
177
+ * (`jobTitle`) leads with `<job title> — <verdict>`, adds the job's next run
178
+ * (`jobNext`) to the time line, a `No summary` line when its summarize step
179
+ * failed, and shows its summary in place of the raw preview.
132
180
  */
133
- export function taskDoneMessage(record, now = new Date(), jobTitle) {
181
+ export function taskDoneMessage(record, now = new Date(), jobTitle, jobNext) {
134
182
  const job = cleanJobTitle(jobTitle);
135
183
  const redacted = isRedactedTask(record);
136
- const preview = redacted ? "" : clip(safeResult(record), TELEGRAM_PREVIEW_CHARS);
137
- const lines = [job ? `${job}: ${preview ? clip(preview.replace(/\s+/g, " "), 200) : "done"}` : `Done: ${messageTitle(record)}`];
138
184
  const at = when(record.completedAt, now);
139
- if (at)
140
- lines.push(`Finished ${at}`);
185
+ const lines = [];
186
+ let body = "";
187
+ if (job) {
188
+ lines.push(`${job} — ${runVerdict(record) ?? "done"}`);
189
+ const next = jobNext && jobNext !== JOB_RUNNING_NOW ? `next ${jobNext}` : undefined;
190
+ const time = [at && `Finished ${at}`, next].filter(Boolean).join(" · ");
191
+ if (time)
192
+ lines.push(time);
193
+ }
194
+ else {
195
+ lines.push(`Done: ${messageTitle(record)}`);
196
+ if (at)
197
+ lines.push(`Finished ${at}`);
198
+ }
141
199
  const ran = runSessionLine(record);
142
200
  if (ran)
143
201
  lines.push(ran);
202
+ if (job && !redacted) {
203
+ const failed = firstErrorLine(taskSummaryError(record), Infinity);
204
+ if (failed)
205
+ lines.push(`No summary: ${cutPreview(failed, VERDICT_CHARS)}`);
206
+ body = jobDoneBody(record);
207
+ }
208
+ else if (!redacted) {
209
+ body = clip(safeResult(record), TELEGRAM_PREVIEW_CHARS);
210
+ }
144
211
  if (redacted) {
145
212
  lines.push("", `The result is not sent here: this task redacts its receipt. Run \`${showCommand(record)}\`.`);
146
213
  }
147
- else if (preview && (!job || preview.length > 200 || /\n/.test(preview))) {
148
- lines.push("", preview);
214
+ else if (body) {
215
+ lines.push("", body);
149
216
  }
150
217
  const buttons = callbackFits(record.taskId) ? [[{ text: "Result", data: encodeCallback("result", record.taskId) }]] : undefined;
151
218
  return { text: lines.join("\n"), ...(buttons ? { buttons } : {}) };
@@ -175,6 +242,20 @@ export function jobPausedTitle(notice) {
175
242
  export function jobPausedMessage(notice) {
176
243
  return { text: `${jobPausedTitle(notice)}\nResume it: tidegap jobs resume ${notice.jobId}` };
177
244
  }
245
+ /** The first line of a job's final notice: `Job ended: "<title>"`. */
246
+ export function jobEndedTitle(notice) {
247
+ return `Job ended: "${cleanJobTitle(notice.title) ?? notice.jobId}"`;
248
+ }
249
+ /** The body of a job's final notice: why it ended, then its last run with its verdict, or its first error line. */
250
+ export function jobEndedBody(notice, last) {
251
+ const title = cleanJobTitle(notice.title) ?? notice.jobId;
252
+ const verdict = runVerdict(last);
253
+ return `"${title}" ended: ${jobEndText(notice.reason, notice.until)}.\nLast run: ${last.taskId} ${notice.lastOutcome}${verdict ? `: ${verdict}` : "."}`;
254
+ }
255
+ /** A job's final notice: the title line and the body. No buttons. */
256
+ export function jobEndedMessage(notice, last) {
257
+ return { text: `${jobEndedTitle(notice)}\n${jobEndedBody(notice, last)}` };
258
+ }
178
259
  /** A clean window starting. No buttons. */
179
260
  export function cleanWindowMessage(window, now = new Date()) {
180
261
  const start = when(window.start, now) ?? window.start;
@@ -199,8 +280,12 @@ export function notReadyMessage(problems, recovered = false) {
199
280
  export function eventMessage(event, now = new Date()) {
200
281
  switch (event.kind) {
201
282
  case "task_done":
202
- return taskDoneMessage(event.task, now, event.jobTitle);
283
+ if (event.jobEnded)
284
+ return jobEndedMessage(event.jobEnded, event.task);
285
+ return taskDoneMessage(event.task, now, event.jobTitle, event.jobNext);
203
286
  case "task_failed":
287
+ if (event.jobEnded)
288
+ return jobEndedMessage(event.jobEnded, event.task);
204
289
  return event.jobPaused ? jobPausedMessage(event.jobPaused) : taskFailedMessage(event.task, now, event.jobTitle);
205
290
  case "clean_window":
206
291
  return cleanWindowMessage(event.window, now);
@@ -4,7 +4,7 @@
4
4
  * redaction and the 600-character preview. Title and text are untrusted
5
5
  * plain text: a `format` for a receiver that renders markup escapes them.
6
6
  */
7
- import { eventMessage, eventTitle, jobPausedTitle } from "./format.js";
7
+ import { eventMessage, eventTitle, jobEndedTitle, jobPausedTitle } from "./format.js";
8
8
  const LEVEL = {
9
9
  task_done: "success",
10
10
  task_failed: "error",
@@ -38,11 +38,13 @@ export function payloadFor(event, now = new Date()) {
38
38
  const title = eventTitle(record, event.jobTitle);
39
39
  const grams = record.receipt?.actualCarbonGCo2 ?? record.receipt?.estimatedCarbonGCo2;
40
40
  const done = event.kind === "task_done";
41
- const head = event.kind === "task_failed" && event.jobPaused
42
- ? jobPausedTitle(event.jobPaused)
43
- : event.jobTitle
44
- ? `${title}: ${done ? "done" : "failed"}`
45
- : `${done ? "Done" : "Failed"}: ${title}`;
41
+ const head = event.jobEnded
42
+ ? jobEndedTitle(event.jobEnded)
43
+ : event.kind === "task_failed" && event.jobPaused
44
+ ? jobPausedTitle(event.jobPaused)
45
+ : event.jobTitle
46
+ ? `${title}: ${done ? "done" : "failed"}`
47
+ : `${done ? "Done" : "Failed"}: ${title}`;
46
48
  return {
47
49
  ...base,
48
50
  title: head,
@@ -29,10 +29,11 @@ export function planNotifications(events, channels, now = new Date()) {
29
29
  function coveredBy(event, covers) {
30
30
  switch (event.kind) {
31
31
  case "task_done":
32
- return covers.taskIds.includes(event.task.taskId);
32
+ // A job's final notice is sent on its own, even when the summary lists its last run.
33
+ return !event.jobEnded && covers.taskIds.includes(event.task.taskId);
33
34
  case "task_failed":
34
35
  // An auto-pause notice is sent on its own, even when the summary lists the failed run.
35
- return !event.jobPaused && covers.taskIds.includes(event.task.taskId);
36
+ return !event.jobPaused && !event.jobEnded && covers.taskIds.includes(event.task.taskId);
36
37
  case "not_ready":
37
38
  // The summary does not say the daemon runs again, so a recovery is never folded.
38
39
  return covers.notReady && !event.recovered;
@@ -6,7 +6,7 @@
6
6
  * every side effect (spawning the toast, calling the Bot API, sending HTTP).
7
7
  */
8
8
  import type { ReadinessProblem } from "../readiness.js";
9
- import type { TaskRecord } from "../types.js";
9
+ import type { JobEndReason, TaskRecord } from "../types.js";
10
10
  /** Every kind a channel row can have: `os` plus the registry kinds (`kinds/index.ts` lists one descriptor per registry kind). */
11
11
  export declare const CHANNEL_KINDS: readonly ["os", "telegram", "webhook", "slack", "discord", "ntfy", "pushover", "email", "shortcuts", "command"];
12
12
  export type ChannelKind = (typeof CHANNEL_KINDS)[number];
@@ -52,6 +52,17 @@ export interface JobPausedNotice {
52
52
  title: string;
53
53
  reason: string;
54
54
  }
55
+ /**
56
+ * What a job's final notice names: the job, why it ended, its end date for
57
+ * `until`, and the outcome of its last run (`task` of the event).
58
+ */
59
+ export interface JobEndedNotice {
60
+ jobId: string;
61
+ title: string;
62
+ reason: JobEndReason;
63
+ until?: string;
64
+ lastOutcome: "ok" | "failed";
65
+ }
55
66
  /** A task event a channel can receive. A `digest` carries its finished text; the host builds it from the ledger. */
56
67
  export type ChannelEvent =
57
68
  /** `jobTitle`: the task is an occurrence of this job; messages lead with the job's current title. */
@@ -59,6 +70,10 @@ export type ChannelEvent =
59
70
  kind: "task_done";
60
71
  task: TaskRecord<unknown>;
61
72
  jobTitle?: string;
73
+ /** The job's next run as a label (`Sun 10:05`, `~Sun 10:05`), set when the event was built. */
74
+ jobNext?: string;
75
+ /** The job ended after this run; the message is its final notice. */
76
+ jobEnded?: JobEndedNotice;
62
77
  }
63
78
  /**
64
79
  * `jobPaused`: the job paused itself after its third failed slot (jobs
@@ -69,6 +84,7 @@ export type ChannelEvent =
69
84
  task: TaskRecord<unknown>;
70
85
  jobTitle?: string;
71
86
  jobPaused?: JobPausedNotice;
87
+ jobEnded?: JobEndedNotice;
72
88
  } | {
73
89
  kind: "clean_window";
74
90
  window: CleanWindowEvent;
package/dist/grid.d.ts CHANGED
@@ -75,6 +75,8 @@ export declare function electricityMapsFeed(apiKey?: string): GridFeed;
75
75
  * Docs: https://carbon-intensity.github.io/api-definitions/#carbon-intensity
76
76
  */
77
77
  export declare function ukCarbonIntensityFeed(): GridFeed;
78
+ /** The line a keyless EIA feed prints, at most once per process. */
79
+ export declare const EIA_NO_KEY_WARNING = "[tidegap/grid] no EIA API key configured \u2014 using mock data for EIA-eligible zones";
78
80
  /**
79
81
  * Carbon-intensity feed backed by the US Energy Information Administration's
80
82
  * v2 Open Data API. Returns a synthesized hourly forecast from the most
@@ -83,7 +85,9 @@ export declare function ukCarbonIntensityFeed(): GridFeed;
83
85
  * The key is always passed in by the host (CLI/MCP read `TIDEGAP_EIA_API_KEY`;
84
86
  * the OpenClaw plugin reads `eiaApiKey` from plugin config).
85
87
  */
86
- export declare function eiaFeed(apiKey?: string): GridFeed;
88
+ export declare function eiaFeed(apiKey?: string, opts?: {
89
+ quiet?: boolean;
90
+ }): GridFeed;
87
91
  /** One `<Period>` inside an ENTSO-E TimeSeries. */
88
92
  export interface EntsoePeriod {
89
93
  /** ISO-8601 start of the period's time interval. */
@@ -245,5 +249,9 @@ export declare function regionDataSource(zone: string, credentials?: GridFeedCre
245
249
  * `buildDefaultGridFeed()` with no argument is exactly the "no keys
246
250
  * configured" case: free UK feed for GB, deterministic mock everywhere else.
247
251
  */
248
- export declare function buildDefaultGridFeed(credentials?: GridFeedCredentials): GridFeed;
252
+ export declare function buildDefaultGridFeed(credentials?: GridFeedCredentials,
253
+ /** `quiet`: no "no EIA API key" line (a one-off CLI command; a receipt still says mock). */
254
+ opts?: {
255
+ quiet?: boolean;
256
+ }): GridFeed;
249
257
  //# sourceMappingURL=grid.d.ts.map
package/dist/grid.js CHANGED
@@ -380,6 +380,9 @@ const EIA_FUEL_FACTORS = {
380
380
  * window left 11–15 hours-of-day and sent every US ISO to the mock.
381
381
  */
382
382
  const EIA_HISTORY_HOURS = 72;
383
+ /** The line a keyless EIA feed prints, at most once per process. */
384
+ export const EIA_NO_KEY_WARNING = "[tidegap/grid] no EIA API key configured — using mock data for EIA-eligible zones";
385
+ let eiaKeyWarned = false;
383
386
  /**
384
387
  * Carbon-intensity feed backed by the US Energy Information Administration's
385
388
  * v2 Open Data API. Returns a synthesized hourly forecast from the most
@@ -388,15 +391,19 @@ const EIA_HISTORY_HOURS = 72;
388
391
  * The key is always passed in by the host (CLI/MCP read `TIDEGAP_EIA_API_KEY`;
389
392
  * the OpenClaw plugin reads `eiaApiKey` from plugin config).
390
393
  */
391
- export function eiaFeed(apiKey) {
394
+ export function eiaFeed(apiKey, opts = {}) {
392
395
  const key = apiKey;
393
396
  const mock = mockGridFeed();
394
397
  if (!key) {
395
398
  return {
396
399
  source: "mock",
397
400
  async fetchForecast(region, hours) {
398
- // eslint-disable-next-line no-console
399
- console.warn("[tidegap/grid] no EIA API key configured — using mock data for EIA-eligible zones");
401
+ // Once per process, across every keyless feed; a quiet feed (a one-off CLI command) never prints it.
402
+ if (!opts.quiet && !eiaKeyWarned) {
403
+ eiaKeyWarned = true;
404
+ // eslint-disable-next-line no-console
405
+ console.warn(EIA_NO_KEY_WARNING);
406
+ }
400
407
  return mock.fetchForecast(region, hours);
401
408
  },
402
409
  };
@@ -1060,7 +1067,9 @@ export function regionDataSource(zone, credentials = {}) {
1060
1067
  * `buildDefaultGridFeed()` with no argument is exactly the "no keys
1061
1068
  * configured" case: free UK feed for GB, deterministic mock everywhere else.
1062
1069
  */
1063
- export function buildDefaultGridFeed(credentials = {}) {
1070
+ export function buildDefaultGridFeed(credentials = {},
1071
+ /** `quiet`: no "no EIA API key" line (a one-off CLI command; a receipt still says mock). */
1072
+ opts = {}) {
1064
1073
  const feeds = {
1065
1074
  GB: ukCarbonIntensityFeed(),
1066
1075
  };
@@ -1074,7 +1083,7 @@ export function buildDefaultGridFeed(credentials = {}) {
1074
1083
  feeds[zone] = wattTimeFeed({
1075
1084
  username: credentials.wattTimeUsername,
1076
1085
  password: credentials.wattTimePassword,
1077
- fallback: eiaFeed(credentials.eiaApiKey),
1086
+ fallback: eiaFeed(credentials.eiaApiKey, { quiet: opts.quiet }),
1078
1087
  });
1079
1088
  }
1080
1089
  for (const zone of Object.keys(ENTSOE_BIDDING_ZONE_BY_REGION)) {
package/dist/handoff.d.ts CHANGED
@@ -9,6 +9,8 @@
9
9
  * and only Tidegap writes a result file, as a new file, never through a
10
10
  * link.
11
11
  */
12
+ import { type SessionNotice, type TaskStore } from "./storage/sqlite.js";
13
+ import type { TaskRecord } from "./types.js";
12
14
  /** A tool profile: a name for one of the existing tool sets. */
13
15
  export type HandoffProfile = "read" | "web" | "none";
14
16
  export declare const HANDOFF_PROFILES: readonly HandoffProfile[];
@@ -110,8 +112,13 @@ export interface TaskWorkShape {
110
112
  profile?: string;
111
113
  tools?: string[];
112
114
  resultPath?: string;
113
- /** True when the task wakes its idle origin session when it finishes. */
115
+ /**
116
+ * True when the task wakes its idle origin session when it finishes; on
117
+ * a run of a bound job, when the job sweep's decision says so.
118
+ */
114
119
  wake?: boolean;
120
+ /** On a run of a bound job: the job's wake rule, which decides whether this run wakes. */
121
+ wakeRule?: "failures" | "match";
115
122
  /** The shell command of a one-off command task. */
116
123
  command?: string;
117
124
  }
@@ -142,6 +149,12 @@ export declare function wakeError(wake: unknown, origin: {
142
149
  * fallback; it creates that file at start, so the two agree from then on.
143
150
  */
144
151
  export declare function defaultDbPath(): string;
152
+ /**
153
+ * The `wake:` line of a task's work shape, or undefined when it does not
154
+ * wake: a one-off wake task wakes when it finishes; a run of a bound job
155
+ * says the job's rule, since most of its runs do not wake.
156
+ */
157
+ export declare function wakeShapeText(shape: Pick<TaskWorkShape, "wake" | "wakeRule">): string | undefined;
145
158
  /**
146
159
  * True when `dbPath` is the default ledger. The session notice and wake
147
160
  * markers under `~/.tidegap/sessions` belong to it: the plugin's hooks
@@ -151,8 +164,6 @@ export declare function defaultDbPath(): string;
151
164
  * its folder's real path and its name.
152
165
  */
153
166
  export declare function isDefaultLedger(dbPath: string): boolean;
154
- /** A wake marker with no wake task left to wait for goes this long after its last refresh (the waiter refreshes it at every Stop). */
155
- export declare const WAKE_MARKER_MAX_AGE_MS: number;
156
167
  /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
157
168
  export declare function wakeMarkersDir(home?: string): string;
158
169
  /** The wake marker of one session, or undefined for an id that fails the id rule. */
@@ -168,4 +179,56 @@ export declare function wakeMarkerPath(sessionId: string, dir?: string): string
168
179
  export declare function writeWakeMarker(sessionId: string, dir?: string, now?: Date): string | undefined;
169
180
  /** Remove a session's wake marker; a missing one is fine. */
170
181
  export declare function removeWakeMarker(sessionId: string, dir?: string): void;
182
+ /** True for a task queued with wake, and for a run of a job bound to a session. */
183
+ export declare function isWakeTask(record: Pick<TaskRecord<unknown>, "bodyJson">): boolean;
184
+ /**
185
+ * True when a session notice wakes its session: a run of a bound job when
186
+ * the job sweep's decision says so, any other completed or failed wake
187
+ * task. A cancel is someone's own act: it never spends a turn.
188
+ */
189
+ export declare function noticeWakes(n: SessionNotice): boolean;
190
+ /**
191
+ * The wake tasks still to come of one session, or of every session when
192
+ * `sessionId` is undefined: not finished yet, or completed and waiting for
193
+ * its result file (its notice comes once the file is). A row that completed
194
+ * more than {@link SESSION_NOTICE_MAX_AGE_MS} ago no longer counts: it can
195
+ * never be a notice.
196
+ */
197
+ export declare function wakeTasksToCome(store: TaskStore, sessionId: string | undefined, now: Date): TaskRecord<unknown>[];
198
+ /**
199
+ * True when a session has something left to wait for (KTD11): an open wake
200
+ * task, a wake task waiting for its result file, an unclaimed notice that
201
+ * wakes, or an active job bound to it. The bound job counts so a waiter
202
+ * does not stop between a run's finish and the sweep's decision. With
203
+ * `since`, only a task queued after it and a job bound after it count (a
204
+ * second look after a removal); a run of a bound job counts through its
205
+ * job's bind time only, since every run is a fresh row and would keep the
206
+ * 7-day rule from ever ending the marker. An unclaimed wake notice counts
207
+ * whatever its time. The reads go against the job sweep's write order
208
+ * (run, then notice, then job): the job first, so a run that finishes
209
+ * between two reads is seen by one of them. `notices` is the session's
210
+ * notice list when the caller has just read it. Throws when the ledger
211
+ * cannot be read.
212
+ */
213
+ export declare function sessionHasWaitWork(store: TaskStore, sessionId: string, now?: Date, opts?: {
214
+ since?: number;
215
+ notices?: readonly SessionNotice[];
216
+ }): boolean;
217
+ /**
218
+ * Remove a session's wake marker, then look once more
219
+ * ({@link sessionHasWaitWork}, from `since` when given), and write the
220
+ * marker again when the session has something left or the read fails. A
221
+ * writer commits its row (or job) before it writes the marker, so work
222
+ * added while the caller decided is either seen here or writes its marker
223
+ * after the removal. Returns "removed", "kept" or "unread" (the read
224
+ * failed). Never throws.
225
+ */
226
+ export declare function removeWakeMarkerUnlessPending(store: TaskStore, sessionId: string, dir?: string, now?: Date, since?: number): "removed" | "kept" | "unread";
227
+ /**
228
+ * The agent's own act ended something a session waited for (a cancel, a
229
+ * job removed, paused or unbound): drop the session's marker now unless
230
+ * it has something left (KTD12). Only on the default ledger, whose markers
231
+ * these are; `sessionId` undefined does nothing. Never throws.
232
+ */
233
+ export declare function releaseWakeMarker(store: TaskStore | undefined, dbPath: string | undefined, sessionId: string | undefined): void;
171
234
  //# sourceMappingURL=handoff.d.ts.map