@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
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Channel types (coherence KTD10). A channel is a place a host sends task
3
+ * events to: the OS toast (`os`), a paired Telegram chat (`telegram`) or
4
+ * one of the registry kinds in `kinds/` (webhook, Slack, email…). Core
5
+ * holds the types, the kind descriptors and pure planning; the host owns
6
+ * every side effect (spawning the toast, calling the Bot API, sending HTTP).
7
+ */
8
+ import type { ReadinessProblem } from "../readiness.js";
9
+ import type { TaskRecord } from "../types.js";
10
+ /** Every kind a channel row can have: `os` plus the registry kinds (`kinds/index.ts` lists one descriptor per registry kind). */
11
+ export declare const CHANNEL_KINDS: readonly ["os", "telegram", "webhook", "slack", "discord", "ntfy", "pushover", "email", "shortcuts", "command"];
12
+ export type ChannelKind = (typeof CHANNEL_KINDS)[number];
13
+ /** The kinds the registry describes: every kind but the implicit OS toast. */
14
+ export type RegistryKind = Exclude<ChannelKind, "os">;
15
+ /** The events a channel can subscribe to. `digest` is the daily summary. */
16
+ export type EventKind = "task_done" | "task_failed" | "clean_window" | "not_ready" | "digest";
17
+ export declare const EVENT_KINDS: readonly EventKind[];
18
+ /** `config.quiet` of a channel: `night` skips every event but `digest` from 22:00 to 09:00 local time (KTD10). */
19
+ export type QuietMode = "night" | "off";
20
+ /** One row of the ledger `channels` table. */
21
+ export interface Channel {
22
+ id: string;
23
+ kind: ChannelKind;
24
+ enabled: boolean;
25
+ events: EventKind[];
26
+ /**
27
+ * Kind-specific non-secret settings (`telegram`: {@link TelegramChannelConfig})
28
+ * plus the shared `quiet` ({@link QuietMode}, absent = `off`). Secrets never live here.
29
+ */
30
+ config: Record<string, unknown>;
31
+ /** ISO-8601. */
32
+ createdAt: string;
33
+ }
34
+ /** `config` of a telegram channel. The bot token is never stored: the host reads it from its env file. */
35
+ export interface TelegramChannelConfig {
36
+ chat_id: number;
37
+ /** The paired user's @username or first name, for `channels list`. */
38
+ label?: string;
39
+ }
40
+ /** A clean window as the host computed it from the forecast. */
41
+ export interface CleanWindowEvent {
42
+ /** ISO-8601 start; also the dedupe key (`notified:clean_window:<start>`). */
43
+ start: string;
44
+ /** ISO-8601 end. */
45
+ end: string;
46
+ /** Lowest intensity in the window, gCO2e/kWh, when known. */
47
+ g?: number;
48
+ }
49
+ /** What an auto-pause notice names: the job, its title and the first error line. */
50
+ export interface JobPausedNotice {
51
+ jobId: string;
52
+ title: string;
53
+ reason: string;
54
+ }
55
+ /** A task event a channel can receive. A `digest` carries its finished text; the host builds it from the ledger. */
56
+ export type ChannelEvent =
57
+ /** `jobTitle`: the task is an occurrence of this job; messages lead with the job's current title. */
58
+ {
59
+ kind: "task_done";
60
+ task: TaskRecord<unknown>;
61
+ jobTitle?: string;
62
+ }
63
+ /**
64
+ * `jobPaused`: the job paused itself after its third failed slot (jobs
65
+ * KTD10); the message is the pause notice, `task` the last failed occurrence.
66
+ */
67
+ | {
68
+ kind: "task_failed";
69
+ task: TaskRecord<unknown>;
70
+ jobTitle?: string;
71
+ jobPaused?: JobPausedNotice;
72
+ } | {
73
+ kind: "clean_window";
74
+ window: CleanWindowEvent;
75
+ }
76
+ /** `recovered`: a ticker alert was sent before and the tick daemon runs again; `problems` may then be empty. */
77
+ | {
78
+ kind: "not_ready";
79
+ problems: ReadinessProblem[];
80
+ recovered?: true;
81
+ } | {
82
+ kind: "digest";
83
+ title: string;
84
+ text: string;
85
+ covers?: DigestCovers;
86
+ };
87
+ /** What a daily summary lists, so a channel that gets it gets no separate alert for the same thing ({@link foldIntoDigest}). */
88
+ export interface DigestCovers {
89
+ /** Done and failed tasks the summary lists by title (at most `DIGEST_LIST_MAX` of each). */
90
+ taskIds: readonly string[];
91
+ /** The summary lists the open readiness problems. */
92
+ notReady: boolean;
93
+ /** Start of the clean window the summary names. */
94
+ cleanWindow?: string;
95
+ }
96
+ /** One send a host performs: `event` to `channel`. */
97
+ export interface SendJob {
98
+ channel: Channel;
99
+ event: ChannelEvent;
100
+ }
101
+ /** The OS toast as a channel (R23): implicit, done and failed only, enabled by the host's config switch. */
102
+ export declare function osChannel(enabled: boolean): Channel;
103
+ /** The chat id of a telegram channel, or undefined when its config has none. */
104
+ export declare function telegramChatId(channel: Channel): number | undefined;
105
+ /** The channel's quiet mode; anything but `night` is `off`. */
106
+ export declare function channelQuiet(channel: Channel): QuietMode;
107
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Channel types (coherence KTD10). A channel is a place a host sends task
3
+ * events to: the OS toast (`os`), a paired Telegram chat (`telegram`) or
4
+ * one of the registry kinds in `kinds/` (webhook, Slack, email…). Core
5
+ * holds the types, the kind descriptors and pure planning; the host owns
6
+ * every side effect (spawning the toast, calling the Bot API, sending HTTP).
7
+ */
8
+ /** Every kind a channel row can have: `os` plus the registry kinds (`kinds/index.ts` lists one descriptor per registry kind). */
9
+ export const CHANNEL_KINDS = ["os", "telegram", "webhook", "slack", "discord", "ntfy", "pushover", "email", "shortcuts", "command"];
10
+ export const EVENT_KINDS = ["task_done", "task_failed", "clean_window", "not_ready", "digest"];
11
+ /** The OS toast as a channel (R23): implicit, done and failed only, enabled by the host's config switch. */
12
+ export function osChannel(enabled) {
13
+ return { id: "os", kind: "os", enabled, events: ["task_done", "task_failed"], config: {}, createdAt: new Date(0).toISOString() };
14
+ }
15
+ /** The chat id of a telegram channel, or undefined when its config has none. */
16
+ export function telegramChatId(channel) {
17
+ if (channel.kind !== "telegram")
18
+ return undefined;
19
+ const id = channel.config.chat_id;
20
+ return typeof id === "number" && Number.isSafeInteger(id) ? id : undefined;
21
+ }
22
+ /** The channel's quiet mode; anything but `night` is `off`. */
23
+ export function channelQuiet(channel) {
24
+ return channel.config.quiet === "night" ? "night" : "off";
25
+ }
26
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The Claude Code tools a `claude-code` task may use (v1).
3
+ *
4
+ * Read-only on purpose: a task can read web pages, and web content is
5
+ * untrusted (prompt injection). So no tool that runs commands or writes
6
+ * files is ever allowed: `Bash`, `Write` and `Edit` are not on the list.
7
+ * A file tool and a web tool are never allowed together: a fetched page
8
+ * could tell the run to read a local file and send it out in a request.
9
+ */
10
+ /** Every tool name a task, `TIDEGAP_CLAUDE_TOOLS` or the adapter accepts. */
11
+ export declare const CLAUDE_CODE_TOOL_ALLOWLIST: readonly string[];
12
+ /** The tool set of a `claude-code` run when neither the task nor the env names one. */
13
+ export declare const DEFAULT_CLAUDE_CODE_TOOLS: readonly string[];
14
+ /**
15
+ * Check a `tools` value: an array of allowlisted names (`[]` = none).
16
+ * Returns the error message, or `undefined` when the value is valid.
17
+ */
18
+ export declare function claudeCodeToolsError(value: unknown): string | undefined;
19
+ /**
20
+ * The tool set of a `claude-code` task that came from a Claude Code session
21
+ * and names none: read-only file tools, pre-approved inside the session's
22
+ * project directory only.
23
+ */
24
+ export declare const DEFAULT_ORIGIN_TOOLS: readonly string[];
25
+ /** True when `tools` holds a web tool (WebSearch, WebFetch). */
26
+ export declare function includesWebTool(tools: readonly string[]): boolean;
27
+ /** True when `tools` holds a file tool (Read, Grep, Glob). */
28
+ export declare function includesFileTool(tools: readonly string[]): boolean;
29
+ //# sourceMappingURL=claude-tools.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The Claude Code tools a `claude-code` task may use (v1).
3
+ *
4
+ * Read-only on purpose: a task can read web pages, and web content is
5
+ * untrusted (prompt injection). So no tool that runs commands or writes
6
+ * files is ever allowed: `Bash`, `Write` and `Edit` are not on the list.
7
+ * A file tool and a web tool are never allowed together: a fetched page
8
+ * could tell the run to read a local file and send it out in a request.
9
+ */
10
+ /** Tools that read local files. Never combined with {@link CLAUDE_CODE_WEB_TOOLS}. */
11
+ const CLAUDE_CODE_FILE_TOOLS = ["Read", "Grep", "Glob"];
12
+ /** Tools that reach the network. Never combined with the file tools. */
13
+ const CLAUDE_CODE_WEB_TOOLS = ["WebSearch", "WebFetch"];
14
+ /** Every tool name a task, `TIDEGAP_CLAUDE_TOOLS` or the adapter accepts. */
15
+ export const CLAUDE_CODE_TOOL_ALLOWLIST = [...CLAUDE_CODE_WEB_TOOLS, ...CLAUDE_CODE_FILE_TOOLS];
16
+ /** The tool set of a `claude-code` run when neither the task nor the env names one. */
17
+ export const DEFAULT_CLAUDE_CODE_TOOLS = ["WebSearch", "WebFetch"];
18
+ /**
19
+ * Check a `tools` value: an array of allowlisted names (`[]` = none).
20
+ * Returns the error message, or `undefined` when the value is valid.
21
+ */
22
+ export function claudeCodeToolsError(value) {
23
+ const allowed = `allowed: ${CLAUDE_CODE_TOOL_ALLOWLIST.join(", ")} (or [] for none)`;
24
+ if (!Array.isArray(value))
25
+ return `tools must be an array of tool names; ${allowed}`;
26
+ const bad = value.filter((t) => typeof t !== "string" || !CLAUDE_CODE_TOOL_ALLOWLIST.includes(t));
27
+ if (bad.length > 0)
28
+ return `tools ${bad.map((t) => JSON.stringify(t)).join(", ")} not allowed; ${allowed}`;
29
+ const mixesFileAndWeb = value.some((t) => CLAUDE_CODE_FILE_TOOLS.includes(t)) && value.some((t) => CLAUDE_CODE_WEB_TOOLS.includes(t));
30
+ if (mixesFileAndWeb) {
31
+ return "tools cannot combine a file tool (Read, Grep, Glob) with a web tool (WebSearch, WebFetch): a fetched page could make the run send a local file out";
32
+ }
33
+ return undefined;
34
+ }
35
+ /**
36
+ * The tool set of a `claude-code` task that came from a Claude Code session
37
+ * and names none: read-only file tools, pre-approved inside the session's
38
+ * project directory only.
39
+ */
40
+ export const DEFAULT_ORIGIN_TOOLS = CLAUDE_CODE_FILE_TOOLS;
41
+ /** True when `tools` holds a web tool (WebSearch, WebFetch). */
42
+ export function includesWebTool(tools) {
43
+ return tools.some((t) => CLAUDE_CODE_WEB_TOOLS.includes(t));
44
+ }
45
+ /** True when `tools` holds a file tool (Read, Grep, Glob). */
46
+ export function includesFileTool(tools) {
47
+ return tools.some((t) => CLAUDE_CODE_FILE_TOOLS.includes(t));
48
+ }
49
+ //# sourceMappingURL=claude-tools.js.map
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { ModelEnergyCoefficients, ModelFamily } from "../energy.js";
9
9
  import type { ModelPrice } from "../routing.js";
10
+ import type { RegionCatalogEntry } from "../region.js";
10
11
  import type { GridForecastEntry } from "../types.js";
11
12
  /** Industry-average Power Usage Effectiveness for hyperscaler data centres. */
12
13
  export declare const DEFAULT_PUE = 1.15;
@@ -47,6 +48,11 @@ export declare const DEFAULT_REGION_FLOOR = 380;
47
48
  export declare const SYNTHETIC_AMPLITUDE = 220;
48
49
  /** Per-region UTC-hour offset applied to the synthetic curve's local trough. */
49
50
  export declare const REGION_UTC_OFFSETS: Readonly<Record<string, number>>;
51
+ /**
52
+ * Supported grid zones for people: name, ISO country code, country name and
53
+ * grid operator. Keys equal REGION_FLOORS and the website's zone list.
54
+ */
55
+ export declare const REGION_CATALOG: Readonly<Record<string, RegionCatalogEntry>>;
50
56
  /** Band thresholds (ascending). A value maps to the first band it is below. */
51
57
  export declare const BAND_THRESHOLDS: readonly {
52
58
  maxExclusive: number;
@@ -179,6 +179,43 @@ export const REGION_UTC_OFFSETS = Object.freeze({
179
179
  "AE": 4,
180
180
  "NZ": 12,
181
181
  });
182
+ /**
183
+ * Supported grid zones for people: name, ISO country code, country name and
184
+ * grid operator. Keys equal REGION_FLOORS and the website's zone list.
185
+ */
186
+ export const REGION_CATALOG = Object.freeze({
187
+ "US-CAL-CISO": { name: "California", country: "US", countryName: "United States", operator: "California ISO (CAISO)" },
188
+ "US-TEX-ERCO": { name: "Texas", country: "US", countryName: "United States", operator: "ERCOT" },
189
+ "US-NE-ISNE": { name: "New England", country: "US", countryName: "United States", operator: "ISO New England" },
190
+ "US-MIDA-PJM": { name: "PJM Mid-Atlantic", country: "US", countryName: "United States", operator: "PJM Interconnection" },
191
+ "GB": { name: "Great Britain", country: "GB", countryName: "United Kingdom", operator: "National Energy System Operator (NESO)" },
192
+ "FR": { name: "France", country: "FR", countryName: "France", operator: "RTE" },
193
+ "DE": { name: "Germany", country: "DE", countryName: "Germany", operator: "50Hertz, Amprion, TenneT, TransnetBW" },
194
+ "IE": { name: "Ireland", country: "IE", countryName: "Ireland", operator: "EirGrid" },
195
+ "NL": { name: "Netherlands", country: "NL", countryName: "Netherlands", operator: "TenneT" },
196
+ "ES": { name: "Spain", country: "ES", countryName: "Spain", operator: "Red Eléctrica (REE)" },
197
+ "BE": { name: "Belgium", country: "BE", countryName: "Belgium", operator: "Elia" },
198
+ "AT": { name: "Austria", country: "AT", countryName: "Austria", operator: "Austrian Power Grid (APG)" },
199
+ "PL": { name: "Poland", country: "PL", countryName: "Poland", operator: "PSE" },
200
+ "JP-TK": { name: "Tokyo", country: "JP", countryName: "Japan", operator: "TEPCO Power Grid" },
201
+ "KR": { name: "South Korea", country: "KR", countryName: "South Korea", operator: "Korea Power Exchange (KPX)" },
202
+ "SG": { name: "Singapore", country: "SG", countryName: "Singapore", operator: "Energy Market Authority (EMA)" },
203
+ "AU-NSW": { name: "New South Wales", country: "AU", countryName: "Australia", operator: "AEMO" },
204
+ "CA-ON": { name: "Ontario", country: "CA", countryName: "Canada", operator: "IESO" },
205
+ "US-NY-NYIS": { name: "New York", country: "US", countryName: "United States", operator: "NYISO" },
206
+ "US-MIDW-MISO": { name: "Midcontinent", country: "US", countryName: "United States", operator: "MISO" },
207
+ "US-NW-BPAT": { name: "Pacific Northwest", country: "US", countryName: "United States", operator: "Bonneville Power Administration (BPA)" },
208
+ "US-FLA-FPL": { name: "Florida", country: "US", countryName: "United States", operator: "Florida Power & Light (FPL)" },
209
+ "IT-NO": { name: "Northern Italy", country: "IT", countryName: "Italy", operator: "Terna" },
210
+ "SE-SE3": { name: "Central Sweden (SE3)", country: "SE", countryName: "Sweden", operator: "Svenska kraftnät" },
211
+ "NO-NO1": { name: "Southeast Norway (NO1)", country: "NO", countryName: "Norway", operator: "Statnett" },
212
+ "FI": { name: "Finland", country: "FI", countryName: "Finland", operator: "Fingrid" },
213
+ "DK-DK1": { name: "West Denmark (DK1)", country: "DK", countryName: "Denmark", operator: "Energinet" },
214
+ "IN-WE": { name: "Western India", country: "IN", countryName: "India", operator: "Grid Controller of India" },
215
+ "ZA": { name: "South Africa", country: "ZA", countryName: "South Africa", operator: "Eskom" },
216
+ "AE": { name: "United Arab Emirates", country: "AE", countryName: "United Arab Emirates", operator: "EWEC and DEWA" },
217
+ "NZ": { name: "New Zealand", country: "NZ", countryName: "New Zealand", operator: "Transpower" },
218
+ });
182
219
  /** Band thresholds (ascending). A value maps to the first band it is below. */
183
220
  export const BAND_THRESHOLDS = Object.freeze([
184
221
  { maxExclusive: 100, band: "very_clean" },
package/dist/energy.d.ts CHANGED
@@ -39,6 +39,8 @@
39
39
  * `DEFAULT_PUE = 1.15` (industry average for hyperscalers; Google
40
40
  * reports 1.10, AWS ~1.15, Azure ~1.18). Callers can override.
41
41
  */
42
+ import type { ModelUsage } from "./providers/base.js";
43
+ import type { ReceiptModelEntry, TokenCounts } from "./types.js";
42
44
  /** Confidence tier for a coefficient entry. */
43
45
  export type EnergySourceTier = "measured" | "estimated" | "fallback";
44
46
  /**
@@ -169,4 +171,86 @@ export declare function estimateEnergyKwh(opts?: EstimateEnergyOpts): number;
169
171
  * @param opts Per-model + token args, same shape as `estimateEnergyKwh`.
170
172
  */
171
173
  export declare function gramsForIntensity(gCo2PerKwh: number, opts?: EstimateEnergyOpts): number;
174
+ /** The bill of a run with two or more billed models (KTD7). */
175
+ export interface ModelUsageBill {
176
+ /** Unrounded grams over every entry; undefined without an intensity. */
177
+ carbonGCo2?: number;
178
+ /**
179
+ * The billed entries: reported output tokens descending (an unreported
180
+ * output counts as 0), then model id ascending. An entry leaves out a
181
+ * count its model did not report.
182
+ */
183
+ models: ReceiptModelEntry[];
184
+ /** The first entry's model: the one with the most reported output tokens. */
185
+ model: string;
186
+ /**
187
+ * The reported input and output tokens over every entry; undefined when
188
+ * no entry reported a count, as the single-model path leaves it out.
189
+ */
190
+ totalTokens?: number;
191
+ /** The weakest `energySource` across the entries. */
192
+ energySource: EnergySourceTier;
193
+ /** The weakest `energyResolution` across the entries. */
194
+ energyResolution: EnergyResolutionTier;
195
+ /** The receipt's `tokenCounts` over every billed count; absent when each was reported. */
196
+ tokenCounts?: TokenCounts;
197
+ }
198
+ /**
199
+ * The words every surface prints for a receipt's `tokenCounts` (batch 27, R6):
200
+ * `tidegap verify`, the MCP receipt text and the page (`ui/detail.js`, which
201
+ * cannot import the core; a CLI test holds its copy to these).
202
+ */
203
+ export declare const TOKEN_COUNTS_PARTIAL_TEXT = "partial (a token count was not reported; billed at the typical count)";
204
+ export declare const TOKEN_COUNTS_TYPICAL_TEXT = "typical (no token count reported; billed as a typical call)";
205
+ /** A single-model run's raw counts, as an adapter or a Batch result reports them. */
206
+ export interface RunUsage {
207
+ inputTokens?: unknown;
208
+ outputTokens?: unknown;
209
+ totalTokens?: unknown;
210
+ partialInputTokens?: unknown;
211
+ }
212
+ /** What a single-model receipt bills and shows (KTD2). */
213
+ export interface SingleModelCounts {
214
+ /** Input tokens to bill; absent bills the typical count. */
215
+ inputTokens?: number;
216
+ /** Output tokens to bill; absent bills the typical count. */
217
+ outputTokens?: number;
218
+ /**
219
+ * The total the receipt shows: the provider's total, when it is a count
220
+ * and both counts were reported. Beside `tokenCounts` it is left out: an
221
+ * adapter's total there sums a count the bill did not use.
222
+ */
223
+ totalTokens?: number;
224
+ /** The receipt's `tokenCounts`; absent when both counts were reported. */
225
+ tokenCounts?: TokenCounts;
226
+ }
227
+ /**
228
+ * Turn a single-model run's raw counts into the counts to bill, the total
229
+ * to show and the marker (KTD1-KTD3). A count that is absent, not a number,
230
+ * negative or not finite is unreported: it is billed at the typical count
231
+ * and the receipt leaves it out. An input reported in part
232
+ * (`partialInputTokens`) is billed at the larger of its parts and the
233
+ * typical input count. The total is kept only when both counts were
234
+ * reported: an adapter that adds a `null` or negative input to its output
235
+ * would otherwise sign a total that includes a count the bill left out.
236
+ * Pass the result's `inputTokens` and `outputTokens` to
237
+ * `gramsForIntensity`. The Python twin (`single_model_counts`) sums input
238
+ * and output when the run gives no total.
239
+ */
240
+ export declare function singleModelCounts(usage: RunUsage | undefined): SingleModelCounts;
241
+ /**
242
+ * Bill each model of a run with its own coefficients at one grid intensity
243
+ * (KTD7). A count that is absent, not a number, negative or not finite is
244
+ * unreported: it is billed at the typical count, as `estimateEnergyKwh`
245
+ * does on the single-model path, and the entry and `totalTokens` leave it
246
+ * out. An input reported in part (`partialInputTokens`) is billed at the
247
+ * larger of its parts and the typical input count, and the entry and
248
+ * `totalTokens` leave it out too. When no entry reports a count, the bill
249
+ * has no `totalTokens`. `tokenCounts` covers every billed count. An entry
250
+ * that reports both counts as 0 is not billed. Returns undefined when fewer
251
+ * than two entries are left: the caller then bills the run as one model.
252
+ * Each entry's grams are rounded half up to 0.01 g; the total stays
253
+ * unrounded.
254
+ */
255
+ export declare function billModelUsage(intensityGCo2PerKwh: number | undefined, usage: readonly ModelUsage[]): ModelUsageBill | undefined;
172
256
  //# sourceMappingURL=energy.d.ts.map
package/dist/energy.js CHANGED
@@ -185,4 +185,142 @@ export function estimateEnergyKwh(opts = {}) {
185
185
  export function gramsForIntensity(gCo2PerKwh, opts = {}) {
186
186
  return estimateEnergyKwh(opts) * gCo2PerKwh;
187
187
  }
188
+ /** Strongest last, so a lower rank is weaker. */
189
+ const SOURCE_RANK = { fallback: 0, estimated: 1, measured: 2 };
190
+ const RESOLUTION_RANK = {
191
+ default: 0,
192
+ "family-fallback": 1,
193
+ normalized: 2,
194
+ exact: 3,
195
+ };
196
+ /** A token count the bill can use: `canonicalize` throws on a non-finite number. */
197
+ const isCount = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
198
+ /** The count when the model reported a usable one; otherwise undefined, an unreported count. */
199
+ const reported = (n) => (isCount(n) ? n : undefined);
200
+ /**
201
+ * Apply the count rule to one model's raw counts (KTD2). A partial input is
202
+ * kept only when the input itself is unreported and the partial value is a
203
+ * count.
204
+ */
205
+ function counted(u) {
206
+ const inputTokens = reported(u.inputTokens);
207
+ return {
208
+ inputTokens,
209
+ outputTokens: reported(u.outputTokens),
210
+ partialInputTokens: inputTokens === undefined ? reported(u.partialInputTokens) : undefined,
211
+ };
212
+ }
213
+ /**
214
+ * The input tokens to bill (KTD3): the reported count; for an input reported
215
+ * in part, the larger of its reported parts and the typical input count;
216
+ * otherwise undefined, which `estimateEnergyKwh` bills at the typical count.
217
+ */
218
+ const billedInput = (c) => c.inputTokens ?? (c.partialInputTokens !== undefined ? Math.max(c.partialInputTokens, TYPICAL_INPUT_TOKENS) : undefined);
219
+ /**
220
+ * The words every surface prints for a receipt's `tokenCounts` (batch 27, R6):
221
+ * `tidegap verify`, the MCP receipt text and the page (`ui/detail.js`, which
222
+ * cannot import the core; a CLI test holds its copy to these).
223
+ */
224
+ export const TOKEN_COUNTS_PARTIAL_TEXT = "partial (a token count was not reported; billed at the typical count)";
225
+ export const TOKEN_COUNTS_TYPICAL_TEXT = "typical (no token count reported; billed as a typical call)";
226
+ /**
227
+ * The receipt's `tokenCounts` over the counts a bill used (KTD1): undefined
228
+ * when every count was reported in full, "typical" when no count and no
229
+ * input part was reported, otherwise "partial".
230
+ */
231
+ function tokenCountsOf(counts) {
232
+ if (counts.every((c) => c.inputTokens !== undefined && c.outputTokens !== undefined))
233
+ return undefined;
234
+ const anyReported = counts.some((c) => c.inputTokens !== undefined || c.outputTokens !== undefined || c.partialInputTokens !== undefined);
235
+ return anyReported ? "partial" : "typical";
236
+ }
237
+ /**
238
+ * Turn a single-model run's raw counts into the counts to bill, the total
239
+ * to show and the marker (KTD1-KTD3). A count that is absent, not a number,
240
+ * negative or not finite is unreported: it is billed at the typical count
241
+ * and the receipt leaves it out. An input reported in part
242
+ * (`partialInputTokens`) is billed at the larger of its parts and the
243
+ * typical input count. The total is kept only when both counts were
244
+ * reported: an adapter that adds a `null` or negative input to its output
245
+ * would otherwise sign a total that includes a count the bill left out.
246
+ * Pass the result's `inputTokens` and `outputTokens` to
247
+ * `gramsForIntensity`. The Python twin (`single_model_counts`) sums input
248
+ * and output when the run gives no total.
249
+ */
250
+ export function singleModelCounts(usage) {
251
+ const c = counted(usage ?? {});
252
+ const inputTokens = billedInput(c);
253
+ const tokenCounts = tokenCountsOf([c]);
254
+ const totalTokens = tokenCounts === undefined ? reported(usage?.totalTokens) : undefined;
255
+ return {
256
+ ...(inputTokens !== undefined ? { inputTokens } : {}),
257
+ ...(c.outputTokens !== undefined ? { outputTokens: c.outputTokens } : {}),
258
+ ...(totalTokens !== undefined ? { totalTokens } : {}),
259
+ ...(tokenCounts !== undefined ? { tokenCounts } : {}),
260
+ };
261
+ }
262
+ /**
263
+ * Bill each model of a run with its own coefficients at one grid intensity
264
+ * (KTD7). A count that is absent, not a number, negative or not finite is
265
+ * unreported: it is billed at the typical count, as `estimateEnergyKwh`
266
+ * does on the single-model path, and the entry and `totalTokens` leave it
267
+ * out. An input reported in part (`partialInputTokens`) is billed at the
268
+ * larger of its parts and the typical input count, and the entry and
269
+ * `totalTokens` leave it out too. When no entry reports a count, the bill
270
+ * has no `totalTokens`. `tokenCounts` covers every billed count. An entry
271
+ * that reports both counts as 0 is not billed. Returns undefined when fewer
272
+ * than two entries are left: the caller then bills the run as one model.
273
+ * Each entry's grams are rounded half up to 0.01 g; the total stays
274
+ * unrounded.
275
+ */
276
+ export function billModelUsage(intensityGCo2PerKwh, usage) {
277
+ const billed = usage
278
+ .map((u) => ({ model: u.model, ...counted(u) }))
279
+ .filter((u) => !(u.inputTokens === 0 && u.outputTokens === 0))
280
+ .sort((a, b) => (b.outputTokens ?? 0) - (a.outputTokens ?? 0) || (a.model < b.model ? -1 : a.model > b.model ? 1 : 0));
281
+ if (billed.length < 2)
282
+ return undefined;
283
+ let carbonGCo2;
284
+ let totalTokens;
285
+ let energySource = "measured";
286
+ let energyResolution = "exact";
287
+ const models = billed.map((c) => {
288
+ const { model, inputTokens, outputTokens } = c;
289
+ const { coeffs, tier } = resolveModelEnergy(model);
290
+ if (inputTokens !== undefined || outputTokens !== undefined) {
291
+ totalTokens = (totalTokens ?? 0) + (inputTokens ?? 0) + (outputTokens ?? 0);
292
+ }
293
+ if (SOURCE_RANK[coeffs.source] < SOURCE_RANK[energySource])
294
+ energySource = coeffs.source;
295
+ if (RESOLUTION_RANK[tier] < RESOLUTION_RANK[energyResolution])
296
+ energyResolution = tier;
297
+ const grams = intensityGCo2PerKwh === undefined
298
+ ? undefined
299
+ : gramsForIntensity(intensityGCo2PerKwh, { model, inputTokens: billedInput(c), outputTokens });
300
+ if (grams !== undefined)
301
+ carbonGCo2 = (carbonGCo2 ?? 0) + grams;
302
+ return {
303
+ model,
304
+ ...(inputTokens !== undefined ? { inputTokens } : {}),
305
+ ...(outputTokens !== undefined ? { outputTokens } : {}),
306
+ ...(grams !== undefined ? { carbonGCo2: Math.round(grams * 100) / 100 } : {}),
307
+ energySource: coeffs.source,
308
+ energyResolution: tier,
309
+ };
310
+ });
311
+ const tokenCounts = tokenCountsOf(billed);
312
+ // A sum of counts can still overflow to Infinity, which `canonicalize`
313
+ // refuses: the count rule applies to the total too.
314
+ if (!isCount(totalTokens))
315
+ totalTokens = undefined;
316
+ return {
317
+ ...(carbonGCo2 !== undefined ? { carbonGCo2 } : {}),
318
+ models,
319
+ model: billed[0].model,
320
+ ...(totalTokens !== undefined ? { totalTokens } : {}),
321
+ energySource,
322
+ energyResolution,
323
+ ...(tokenCounts !== undefined ? { tokenCounts } : {}),
324
+ };
325
+ }
188
326
  //# sourceMappingURL=energy.js.map
package/dist/grid.d.ts CHANGED
@@ -77,8 +77,8 @@ export declare function electricityMapsFeed(apiKey?: string): GridFeed;
77
77
  export declare function ukCarbonIntensityFeed(): GridFeed;
78
78
  /**
79
79
  * Carbon-intensity feed backed by the US Energy Information Administration's
80
- * v2 Open Data API. Returns a synthesized hourly forecast from the last
81
- * 24 hours of realized fuel mix.
80
+ * v2 Open Data API. Returns a synthesized hourly forecast from the most
81
+ * recent 24 hours-of-day of realized fuel mix.
82
82
  *
83
83
  * The key is always passed in by the host (CLI/MCP read `TIDEGAP_EIA_API_KEY`;
84
84
  * the OpenClaw plugin reads `eiaApiKey` from plugin config).
@@ -204,6 +204,21 @@ export interface GridFeedCredentials {
204
204
  /** WattTime account password. CLI/MCP env: `WATTTIME_PASSWORD`. */
205
205
  wattTimePassword?: string;
206
206
  }
207
+ /** Which feed serves a zone, for display (Settings card, `tidegap region`). */
208
+ export interface RegionDataSource {
209
+ id: "neso" | "entsoe" | "watttime-eia" | "electricitymaps";
210
+ label: string;
211
+ /** Env variable that turns the feed live; absent for key-less feeds. */
212
+ keyVar?: string;
213
+ /** True when the credentials passed in make the feed live (else sample curve). */
214
+ live: boolean;
215
+ }
216
+ /**
217
+ * The feed `buildDefaultGridFeed` routes `zone` to, derived from the same
218
+ * zone maps so the label cannot drift from routing. `live` reflects the
219
+ * credentials the host passes in (none → only GB is live).
220
+ */
221
+ export declare function regionDataSource(zone: string, credentials?: GridFeedCredentials): RegionDataSource;
207
222
  /**
208
223
  * Auto-build the best free grid feed for every supported zone.
209
224
  *
package/dist/grid.js CHANGED
@@ -373,10 +373,17 @@ const EIA_FUEL_FACTORS = {
373
373
  WAT: EMISSION_FACTORS_G_CO2_PER_KWH.hydro,
374
374
  OTH: EMISSION_FACTORS_G_CO2_PER_KWH.other,
375
375
  };
376
+ /**
377
+ * How far back the EIA request reaches. EIA-930 fuel-type data is published
378
+ * with a lag of up to a day (19h observed on 2026-10-17), and the feed needs
379
+ * all 24 hours-of-day, so the window must be 24h plus the worst lag. A 30h
380
+ * window left 11–15 hours-of-day and sent every US ISO to the mock.
381
+ */
382
+ const EIA_HISTORY_HOURS = 72;
376
383
  /**
377
384
  * Carbon-intensity feed backed by the US Energy Information Administration's
378
- * v2 Open Data API. Returns a synthesized hourly forecast from the last
379
- * 24 hours of realized fuel mix.
385
+ * v2 Open Data API. Returns a synthesized hourly forecast from the most
386
+ * recent 24 hours-of-day of realized fuel mix.
380
387
  *
381
388
  * The key is always passed in by the host (CLI/MCP read `TIDEGAP_EIA_API_KEY`;
382
389
  * the OpenClaw plugin reads `eiaApiKey` from plugin config).
@@ -404,11 +411,10 @@ export function eiaFeed(apiKey) {
404
411
  return mock.fetchForecast(region, hours);
405
412
  }
406
413
  try {
407
- // Pull the last 30 hours so we have a buffer of completed hours.
408
414
  // EIA timestamps are UTC, no offset; the "period" field is "YYYY-MM-DDTHH".
409
415
  const now = new Date();
410
416
  const endHour = floorToUtcHour(now);
411
- const startHour = new Date(endHour.getTime() - 30 * 60 * 60 * 1000);
417
+ const startHour = new Date(endHour.getTime() - EIA_HISTORY_HOURS * 60 * 60 * 1000);
412
418
  const fmt = (d) => d.toISOString().slice(0, 13); // "YYYY-MM-DDTHH"
413
419
  const params = new URLSearchParams({
414
420
  api_key: key,
@@ -995,6 +1001,39 @@ export function multiSourceGridFeed(options) {
995
1001
  },
996
1002
  };
997
1003
  }
1004
+ /**
1005
+ * The feed `buildDefaultGridFeed` routes `zone` to, derived from the same
1006
+ * zone maps so the label cannot drift from routing. `live` reflects the
1007
+ * credentials the host passes in (none → only GB is live).
1008
+ */
1009
+ export function regionDataSource(zone, credentials = {}) {
1010
+ if (zone === "GB") {
1011
+ return { id: "neso", label: "NESO Carbon Intensity API", live: true };
1012
+ }
1013
+ if (Object.hasOwn(EIA_RESPONDENT_BY_ZONE, zone)) {
1014
+ const wattTime = Boolean(credentials.wattTimeUsername && credentials.wattTimePassword);
1015
+ return {
1016
+ id: "watttime-eia",
1017
+ label: "WattTime or US EIA",
1018
+ keyVar: "TIDEGAP_EIA_API_KEY",
1019
+ live: wattTime || Boolean(credentials.eiaApiKey),
1020
+ };
1021
+ }
1022
+ if (Object.hasOwn(ENTSOE_BIDDING_ZONE_BY_REGION, zone)) {
1023
+ return {
1024
+ id: "entsoe",
1025
+ label: "ENTSO-E",
1026
+ keyVar: "TIDEGAP_ENTSOE_SECURITY_TOKEN",
1027
+ live: Boolean(credentials.entsoeSecurityToken),
1028
+ };
1029
+ }
1030
+ return {
1031
+ id: "electricitymaps",
1032
+ label: "Electricity Maps",
1033
+ keyVar: "TIDEGAP_ELECTRICITY_MAPS_API_KEY",
1034
+ live: Boolean(credentials.electricityMapsApiKey),
1035
+ };
1036
+ }
998
1037
  /**
999
1038
  * Auto-build the best free grid feed for every supported zone.
1000
1039
  *