@tidegap/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +138 -0
  11. package/dist/channels/format.js +425 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
package/dist/redact.d.ts CHANGED
@@ -13,6 +13,21 @@
13
13
  * while missing every real vendor key shape below.
14
14
  */
15
15
  export declare const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp>;
16
+ /**
17
+ * The token prefixes {@link DEFAULT_REDACTION_PATTERNS} match, each with the
18
+ * characters its key body is made of (KTD13). {@link scrubCutEdges} drops a
19
+ * token that starts with one of them at a cut end: the cut key is too short
20
+ * for its full pattern. `prefix` is a regex source (`Bearer` takes any
21
+ * whitespace after it). `boundary` is true where the pattern starts at a word
22
+ * boundary; `sk-` has none, so it is found inside a word too. A new pattern
23
+ * adds its prefix here.
24
+ */
25
+ export declare const VENDOR_KEY_PREFIXES: ReadonlyArray<{
26
+ prefix: string;
27
+ body: string;
28
+ boundary: boolean;
29
+ ignoreCase?: boolean;
30
+ }>;
16
31
  /**
17
32
  * Apply the spec's redaction patterns (or the default set) to the
18
33
  * prompt before storing it on the receipt. Original prompt is left
@@ -29,4 +44,31 @@ export declare function redactPrompt(prompt: string, patterns: string[] | undefi
29
44
  * prompt until it either succeeds (redacted then) or is cancelled.
30
45
  */
31
46
  export declare function redactBodyJson(bodyJson: string | undefined): string | undefined;
47
+ /** Shortest secret value {@link scrubValues} replaces; shorter ones would mangle ordinary text. */
48
+ export declare const SCRUB_MIN_LENGTH = 4;
49
+ /**
50
+ * Replace every exact occurrence of each value with `[redacted]` (job
51
+ * secrets, KTD12). Longest value first, so a value that contains another is
52
+ * replaced whole. Values shorter than {@link SCRUB_MIN_LENGTH} are left
53
+ * alone. Literal matching only: no regex is built from a value. Transformed
54
+ * forms (base64, URL-encoding) are not caught.
55
+ */
56
+ export declare function scrubValues(text: string, values: readonly string[]): string;
57
+ /**
58
+ * Scrub the edges of a text that was cut by bytes (an output cap, a tail
59
+ * window). A cut can leave the head of a secret value at the end of the
60
+ * text, or its tail at the start, which {@link scrubValues} cannot match.
61
+ * At each cut edge the longest such fragment, of any length, becomes
62
+ * `[redacted]`; the U+FFFD left by a cut inside a UTF-8 sequence goes with
63
+ * it. Vendor key shapes are cut too, which the redaction patterns cannot
64
+ * match (KTD13): at a cut end, a trailing token that starts with a prefix of
65
+ * {@link VENDOR_KEY_PREFIXES}; at a cut start, a leading token of 16 or
66
+ * more token characters, or the value fragment when that is longer. Part of an ordinary word at
67
+ * a cut may go with them. Call it after `scrubValues`, and only for an edge
68
+ * that was cut.
69
+ */
70
+ export declare function scrubCutEdges(text: string, values: readonly string[], cut: {
71
+ start?: boolean;
72
+ end?: boolean;
73
+ }): string;
32
74
  //# sourceMappingURL=redact.d.ts.map
package/dist/redact.js CHANGED
@@ -23,6 +23,31 @@ export const DEFAULT_REDACTION_PATTERNS = [
23
23
  /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, // Slack tokens
24
24
  /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, // JWT
25
25
  ];
26
+ /**
27
+ * The token prefixes {@link DEFAULT_REDACTION_PATTERNS} match, each with the
28
+ * characters its key body is made of (KTD13). {@link scrubCutEdges} drops a
29
+ * token that starts with one of them at a cut end: the cut key is too short
30
+ * for its full pattern. `prefix` is a regex source (`Bearer` takes any
31
+ * whitespace after it). `boundary` is true where the pattern starts at a word
32
+ * boundary; `sk-` has none, so it is found inside a word too. A new pattern
33
+ * adds its prefix here.
34
+ */
35
+ export const VENDOR_KEY_PREFIXES = [
36
+ { prefix: "sk-", body: "A-Za-z0-9_\\-", boundary: false },
37
+ { prefix: "Bearer\\s+", body: "A-Za-z0-9_\\-.", boundary: true, ignoreCase: true },
38
+ { prefix: "AKIA", body: "0-9A-Z", boundary: true },
39
+ { prefix: "gh[pousr]_", body: "A-Za-z0-9", boundary: true },
40
+ { prefix: "github_pat_", body: "A-Za-z0-9_", boundary: true },
41
+ { prefix: "AIza", body: "0-9A-Za-z_\\-", boundary: true },
42
+ { prefix: "xox", body: "A-Za-z0-9-", boundary: true },
43
+ { prefix: "eyJ", body: "A-Za-z0-9_\\-.", boundary: true },
44
+ ];
45
+ /** One regex per prefix: the prefix and at least one body character, up to the end of the text. */
46
+ const TRAILING_KEY = VENDOR_KEY_PREFIXES.map(({ prefix, body, boundary, ignoreCase }) => new RegExp(`${boundary ? "(?<![A-Za-z0-9_])" : ""}${prefix}[${body}]+$`, ignoreCase ? "i" : ""));
47
+ /** The end of a cut text the trailing-key search reads; no key shape is longer. */
48
+ const TRAILING_WINDOW = 8 * 1024;
49
+ /** A leading token this long at a cut start may be the tail of a key; it is dropped. */
50
+ const LEADING_TOKEN = /^[A-Za-z0-9_\-.]{16,}/;
26
51
  /**
27
52
  * Apply the spec's redaction patterns (or the default set) to the
28
53
  * prompt before storing it on the receipt. Original prompt is left
@@ -71,6 +96,13 @@ export function redactBodyJson(bodyJson) {
71
96
  if (typeof spec.systemPrompt === "string") {
72
97
  spec.systemPrompt = redactPrompt(spec.systemPrompt, spec.redactInReceipt);
73
98
  }
99
+ // A one-off command (`queue add --runner command`) is this task's prompt:
100
+ // it is never retried, so its stored text follows the prompt rule. A
101
+ // command job run keeps its text; the job holds it anyway.
102
+ const command = spec.command;
103
+ if (spec.provider === "command" && command && command.origin === "cli" && typeof command.run === "string") {
104
+ spec.command = { ...spec.command, run: redactPrompt(command.run, spec.redactInReceipt) };
105
+ }
74
106
  // Prior conversation turns (v0.17) carry the same kind of secrets as
75
107
  // the prompt, so they follow the same rule.
76
108
  if (Array.isArray(spec.messages)) {
@@ -85,4 +117,82 @@ export function redactBodyJson(bodyJson) {
85
117
  return bodyJson;
86
118
  }
87
119
  }
120
+ /** Shortest secret value {@link scrubValues} replaces; shorter ones would mangle ordinary text. */
121
+ export const SCRUB_MIN_LENGTH = 4;
122
+ /**
123
+ * Replace every exact occurrence of each value with `[redacted]` (job
124
+ * secrets, KTD12). Longest value first, so a value that contains another is
125
+ * replaced whole. Values shorter than {@link SCRUB_MIN_LENGTH} are left
126
+ * alone. Literal matching only: no regex is built from a value. Transformed
127
+ * forms (base64, URL-encoding) are not caught.
128
+ */
129
+ export function scrubValues(text, values) {
130
+ const sorted = [...new Set(values)].filter((v) => v.length >= SCRUB_MIN_LENGTH).sort((a, b) => b.length - a.length);
131
+ let out = text;
132
+ for (const v of sorted)
133
+ out = out.split(v).join("[redacted]");
134
+ return out;
135
+ }
136
+ /**
137
+ * Scrub the edges of a text that was cut by bytes (an output cap, a tail
138
+ * window). A cut can leave the head of a secret value at the end of the
139
+ * text, or its tail at the start, which {@link scrubValues} cannot match.
140
+ * At each cut edge the longest such fragment, of any length, becomes
141
+ * `[redacted]`; the U+FFFD left by a cut inside a UTF-8 sequence goes with
142
+ * it. Vendor key shapes are cut too, which the redaction patterns cannot
143
+ * match (KTD13): at a cut end, a trailing token that starts with a prefix of
144
+ * {@link VENDOR_KEY_PREFIXES}; at a cut start, a leading token of 16 or
145
+ * more token characters, or the value fragment when that is longer. Part of an ordinary word at
146
+ * a cut may go with them. Call it after `scrubValues`, and only for an edge
147
+ * that was cut.
148
+ */
149
+ export function scrubCutEdges(text, values, cut) {
150
+ const vals = [...new Set(values)].filter((v) => v.length >= SCRUB_MIN_LENGTH);
151
+ let out = text;
152
+ if (cut.end) {
153
+ // A loop, not a `+$` regex: that is quadratic on a long run of U+FFFD.
154
+ let end = out.length;
155
+ while (end > 0 && out.charCodeAt(end - 1) === 0xfffd)
156
+ end--;
157
+ const body = out.slice(0, end);
158
+ let longest = 0;
159
+ for (const v of vals) {
160
+ for (let n = Math.min(v.length - 1, body.length); n > longest; n--) {
161
+ if (body.endsWith(v.slice(0, n))) {
162
+ longest = n;
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ // A window keeps the search linear on a long run of prefixes ("sk-sk-...").
168
+ const tail = body.slice(-TRAILING_WINDOW);
169
+ for (const re of TRAILING_KEY) {
170
+ const m = re.exec(tail);
171
+ if (m)
172
+ longest = Math.max(longest, m[0].length);
173
+ }
174
+ if (longest > 0)
175
+ out = `${body.slice(0, body.length - longest)}[redacted]`;
176
+ }
177
+ if (cut.start) {
178
+ let start = 0;
179
+ while (start < out.length && out.charCodeAt(start) === 0xfffd)
180
+ start++;
181
+ const body = out.slice(start);
182
+ let longest = 0;
183
+ for (const v of vals) {
184
+ for (let n = Math.min(v.length - 1, body.length); n > longest; n--) {
185
+ if (body.startsWith(v.slice(v.length - n))) {
186
+ longest = n;
187
+ break;
188
+ }
189
+ }
190
+ }
191
+ // A long leading token may be a key's tail, whatever value fragment it starts with.
192
+ longest = Math.max(longest, LEADING_TOKEN.exec(body)?.[0].length ?? 0);
193
+ if (longest > 0)
194
+ out = `[redacted]${body.slice(longest)}`;
195
+ }
196
+ return out;
197
+ }
88
198
  //# sourceMappingURL=redact.js.map
@@ -0,0 +1,30 @@
1
+ import { type GridFeedCredentials } from "./grid.js";
2
+ import { type RegionResolution } from "./region.js";
3
+ /** New-issue link for a region request, prefilled with `subject` in the title. */
4
+ export declare function regionRequestUrl(subject?: string): string;
5
+ /** "Unknown zone X. Closest: A, B. Request a region: <link>" (no "Closest" when none). */
6
+ export declare function unknownRegionMessage(input: string): string;
7
+ /**
8
+ * Check a region tool argument (source `flag`). A catalog zone (any case)
9
+ * returns its code. Another zone passes as typed when the host's
10
+ * `credentials` give it a live feed (an Electricity Maps key serves zones
11
+ * beyond the catalog; an ENTSO-E token serves `IT`); else it is an error
12
+ * naming the closest zones.
13
+ */
14
+ export declare function checkRequestedRegion(input: string, credentials?: GridFeedCredentials): RegionResolution | {
15
+ error: string;
16
+ };
17
+ export interface RegionSettingReaderOptions {
18
+ /** Config file path; read on each call. Defaults to `~/.tidegap/config`. */
19
+ path?: () => string;
20
+ /** Receives the ignored-setting warning once per file change. */
21
+ warn?: (message: string) => void;
22
+ }
23
+ /**
24
+ * A reader of the stored region setting for a long-lived process. Each call
25
+ * stats the file and re-reads it only when `(ino, mtimeMs, size)` changed, so a
26
+ * new setting applies on the next call without a restart. A stored value
27
+ * that is not a catalog zone is warned about once per file change.
28
+ */
29
+ export declare function regionSettingReader(opts?: RegionSettingReaderOptions): () => string | undefined;
30
+ //# sourceMappingURL=region-host.d.ts.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Region helpers for long-lived hosts (the MCP server, the OpenClaw plugin):
3
+ * a cached reader of the stored setting and the check of a tool argument.
4
+ */
5
+ import { statSync } from "node:fs";
6
+ import { carbonBudgetConfigPath } from "./budget.js";
7
+ import { regionDataSource } from "./grid.js";
8
+ import { catalogZone, closestRegions, ignoredRegionMessage, loadRegionSetting, } from "./region.js";
9
+ /** New-issue link for a region request, prefilled with `subject` in the title. */
10
+ export function regionRequestUrl(subject) {
11
+ const base = "https://github.com/tidegap/tidegap/issues/new?template=region_request.md";
12
+ const title = subject?.trim();
13
+ return title ? `${base}&title=${encodeURIComponent(`Region request: ${title}`).replace(/%20/g, "+").replace(/%3A/g, ":")}` : base;
14
+ }
15
+ /** "Unknown zone X. Closest: A, B. Request a region: <link>" (no "Closest" when none). */
16
+ export function unknownRegionMessage(input) {
17
+ const zone = input.trim();
18
+ const closest = closestRegions(zone);
19
+ const hint = closest.length > 0 ? ` Closest: ${closest.join(", ")}.` : "";
20
+ return `Unknown zone ${zone}.${hint} Request a region: ${regionRequestUrl(zone)}`;
21
+ }
22
+ /**
23
+ * Check a region tool argument (source `flag`). A catalog zone (any case)
24
+ * returns its code. Another zone passes as typed when the host's
25
+ * `credentials` give it a live feed (an Electricity Maps key serves zones
26
+ * beyond the catalog; an ENTSO-E token serves `IT`); else it is an error
27
+ * naming the closest zones.
28
+ */
29
+ export function checkRequestedRegion(input, credentials = {}) {
30
+ const zone = catalogZone(input);
31
+ if (zone)
32
+ return { region: zone, source: "flag" };
33
+ const typed = input.trim();
34
+ if (regionDataSource(typed, credentials).live)
35
+ return { region: typed, source: "flag" };
36
+ return { error: unknownRegionMessage(input) };
37
+ }
38
+ /**
39
+ * A reader of the stored region setting for a long-lived process. Each call
40
+ * stats the file and re-reads it only when `(ino, mtimeMs, size)` changed, so a
41
+ * new setting applies on the next call without a restart. A stored value
42
+ * that is not a catalog zone is warned about once per file change.
43
+ */
44
+ export function regionSettingReader(opts = {}) {
45
+ const pathOf = opts.path ?? carbonBudgetConfigPath;
46
+ let key;
47
+ let value;
48
+ return () => {
49
+ const path = pathOf();
50
+ let stamp;
51
+ try {
52
+ const st = statSync(path);
53
+ // The inode too: an atomic rewrite renames a new file in, so two writes
54
+ // inside one coarse mtime tick with equal sizes still change the stamp.
55
+ stamp = `${path}\0${st.ino}\0${st.mtimeMs}\0${st.size}`;
56
+ }
57
+ catch {
58
+ stamp = `${path}\0missing`;
59
+ }
60
+ if (stamp === key)
61
+ return value;
62
+ key = stamp;
63
+ value = loadRegionSetting(path);
64
+ if (value && !catalogZone(value))
65
+ opts.warn?.(ignoredRegionMessage(value));
66
+ return value;
67
+ };
68
+ }
69
+ //# sourceMappingURL=region-host.js.map
package/dist/region.d.ts CHANGED
@@ -1,36 +1,118 @@
1
- /**
2
- * Grid-region resolution shared by every Tidegap integration — the CLI,
3
- * the MCP server and the OpenClaw plugin.
4
- *
5
- * When no region is given explicitly, Tidegap guesses one from the host
6
- * machine's IANA timezone, so a user gets carbon data for their own grid
7
- * instead of a hard-coded default. An explicit region (a tool argument or
8
- * a configured default) always takes precedence.
9
- */
1
+ import { REGION_CATALOG } from "./data/tables.generated.js";
10
2
  /** Fallback when nothing else resolves — GB has key-less live data. */
11
3
  export declare const FALLBACK_REGION = "GB";
4
+ /** Key of the region setting in `~/.tidegap/config` (and the env override). */
5
+ export declare const REGION_SETTING_KEY = "TIDEGAP_DEFAULT_REGION";
6
+ /** One supported grid zone, described for people. */
7
+ export interface RegionCatalogEntry {
8
+ /** Zone name, e.g. "France" or "California". */
9
+ name: string;
10
+ /** ISO 3166-1 alpha-2 country code. */
11
+ country: string;
12
+ /** Country name, e.g. "United States". */
13
+ countryName: string;
14
+ /** Grid operator, e.g. "RTE". */
15
+ operator: string;
16
+ }
17
+ export { REGION_CATALOG };
12
18
  /**
13
19
  * Best-effort IANA-timezone → grid-region map. Only timezones whose
14
- * dominant grid is unambiguous are listed; anything else resolves to
15
- * FALLBACK_REGION. Users in other regions set the region explicitly.
20
+ * dominant grid is unambiguous are listed; a time zone that spans several
21
+ * grids (Oslo, Stockholm, Copenhagen, Rome, Tokyo, Kolkata, Toronto,
22
+ * Chicago) resolves to FALLBACK_REGION and the user sets the region.
16
23
  */
17
24
  export declare const TIMEZONE_REGION: Readonly<Record<string, string>>;
18
- /** How a resolved region was chosen. */
19
- export type RegionSource = "request" | "config" | "timezone" | "default";
20
- export type RegionResolution = {
25
+ /** Why a time-zone guess is only approximate. */
26
+ export interface RegionApproximation {
27
+ /** ISO country code of the time zone's own (unsupported) grid. */
28
+ country: string;
29
+ note: string;
30
+ }
31
+ /**
32
+ * Time zones whose own grid is not in the catalog, mapped to the nearest
33
+ * catalog zone. PL is the only catalog zone that borders Ukraine and shares
34
+ * its synchronous area (Continental Europe, since March 2022): hour-of-day
35
+ * timing carries over, absolute grams do not.
36
+ */
37
+ export declare const APPROXIMATE_TIMEZONE_REGION: Readonly<Record<string, {
38
+ region: string;
39
+ approximate: RegionApproximation;
40
+ }>>;
41
+ /**
42
+ * How a resolved region was chosen: `flag` (request / tool argument), `env`
43
+ * (`TIDEGAP_DEFAULT_REGION` in the environment), `config` (a host's own
44
+ * config, e.g. OpenClaw `defaultRegion`), `setting` (`~/.tidegap/config`),
45
+ * `timezone` (guess) or `fallback` (GB).
46
+ */
47
+ export type RegionSource = "flag" | "env" | "config" | "setting" | "timezone" | "fallback";
48
+ export interface RegionResolution {
21
49
  region: string;
22
50
  source: RegionSource;
23
- };
51
+ /** The IANA time zone consulted; set when source is `timezone` or `fallback`. */
52
+ timeZone?: string;
53
+ /** Set when the time-zone guess stands in for an unsupported grid. */
54
+ approximate?: RegionApproximation;
55
+ /** A stored setting that is not a catalog zone and was skipped. */
56
+ ignored?: string;
57
+ }
58
+ export interface ResolveRegionInput {
59
+ /** `--region` flag or tool argument. */
60
+ requested?: string;
61
+ /** Host default: the env variable (`env`) or the host's own config (`config`). */
62
+ configured?: {
63
+ value?: string;
64
+ source: "env" | "config";
65
+ };
66
+ /** Raw stored setting (see loadRegionSetting). Ignored unless a catalog zone. */
67
+ setting?: string;
68
+ /**
69
+ * IANA time zone to guess from. Defaults to the host machine's when the
70
+ * key is absent; an explicit `undefined` skips the guess.
71
+ */
72
+ timeZone?: string;
73
+ }
74
+ /** The catalog zone for `input` (case-insensitive), or undefined. */
75
+ export declare function catalogZone(input: string | undefined): string | undefined;
24
76
  /** Map an IANA timezone to a supported grid region, or undefined. */
25
77
  export declare function regionForTimezone(timeZone: string): string | undefined;
78
+ /** The host machine's IANA time zone, or undefined when it cannot be read. */
79
+ export declare function hostTimeZone(): string | undefined;
80
+ /**
81
+ * Guess a catalog zone from an IANA time zone: an exact map entry, else an
82
+ * approximate one (with the reason), else undefined.
83
+ */
84
+ export declare function guessRegionFromTimeZone(timeZone: string | undefined): {
85
+ region: string;
86
+ approximate?: RegionApproximation;
87
+ } | undefined;
26
88
  /** Guess the grid region from the host machine's IANA timezone. */
27
89
  export declare function detectRegionFromTimezone(): string | undefined;
90
+ /** Warning text for a stored region that is not a catalog zone. */
91
+ export declare function ignoredRegionMessage(value: string): string;
28
92
  /**
29
- * Resolve a grid region. Precedence:
30
- * 1. an explicit request region (a tool argument / CLI flag),
31
- * 2. a configured default (plugin config / TIDEGAP_DEFAULT_REGION),
32
- * 3. a guess from the host machine's timezone,
33
- * 4. FALLBACK_REGION.
93
+ * Resolve a grid region with the precedence in the module comment.
94
+ *
95
+ * The positional form `(requested, configuredDefault)` is kept for existing
96
+ * callers; it reports a configured default as `config` and reads no setting.
34
97
  */
98
+ export declare function resolveRegion(input: ResolveRegionInput): RegionResolution;
35
99
  export declare function resolveRegion(requested?: string, configuredDefault?: string): RegionResolution;
100
+ /**
101
+ * The raw region setting from `~/.tidegap/config` (or `path`), or undefined
102
+ * when the file or the key is missing, empty or unreadable. Not validated:
103
+ * resolveRegion skips a value that is not a catalog zone.
104
+ */
105
+ export declare function loadRegionSetting(path?: string): string | undefined;
106
+ /** Common codes that are not the ISO code of their catalog zone. */
107
+ export declare const COUNTRY_ALIASES: Readonly<Record<string, string>>;
108
+ /**
109
+ * Up to `limit` catalog zones closest to an unknown input, in catalog order
110
+ * within each rule. The first rule with a result decides:
111
+ * 1. the zone of a common alias (UK → GB), or the approximate-map
112
+ * target of a typed country code (UA → PL),
113
+ * 2. zones whose code, name, country code or country name starts with it,
114
+ * 3. zones whose code is within edit distance 2 (1 for inputs of up to
115
+ * 3 characters), nearest first.
116
+ */
117
+ export declare function closestRegions(input: string, limit?: number): string[];
36
118
  //# sourceMappingURL=region.d.ts.map
package/dist/region.js CHANGED
@@ -2,56 +2,208 @@
2
2
  * Grid-region resolution shared by every Tidegap integration — the CLI,
3
3
  * the MCP server and the OpenClaw plugin.
4
4
  *
5
- * When no region is given explicitly, Tidegap guesses one from the host
6
- * machine's IANA timezone, so a user gets carbon data for their own grid
7
- * instead of a hard-coded default. An explicit region (a tool argument or
8
- * a configured default) always takes precedence.
5
+ * Precedence (first match wins):
6
+ * 1. an explicit request region (a `--region` flag or a tool argument),
7
+ * 2. a host-configured default (`TIDEGAP_DEFAULT_REGION` in the
8
+ * environment, or OpenClaw's plugin `defaultRegion`),
9
+ * 3. the stored setting (`TIDEGAP_DEFAULT_REGION` in `~/.tidegap/config`),
10
+ * 4. a guess from the host machine's IANA time zone,
11
+ * 5. FALLBACK_REGION.
12
+ *
13
+ * Core stays environment-pure: hosts read their own environment and pass
14
+ * the configured value and the stored setting in.
9
15
  */
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import { carbonBudgetConfigPath, parseKeyValues } from "./budget.js";
18
+ import { REGION_CATALOG } from "./data/tables.generated.js";
10
19
  /** Fallback when nothing else resolves — GB has key-less live data. */
11
20
  export const FALLBACK_REGION = "GB";
21
+ /** Key of the region setting in `~/.tidegap/config` (and the env override). */
22
+ export const REGION_SETTING_KEY = "TIDEGAP_DEFAULT_REGION";
23
+ export { REGION_CATALOG };
12
24
  /**
13
25
  * Best-effort IANA-timezone → grid-region map. Only timezones whose
14
- * dominant grid is unambiguous are listed; anything else resolves to
15
- * FALLBACK_REGION. Users in other regions set the region explicitly.
26
+ * dominant grid is unambiguous are listed; a time zone that spans several
27
+ * grids (Oslo, Stockholm, Copenhagen, Rome, Tokyo, Kolkata, Toronto,
28
+ * Chicago) resolves to FALLBACK_REGION and the user sets the region.
16
29
  */
17
30
  export const TIMEZONE_REGION = {
18
31
  "Europe/London": "GB",
19
32
  "Europe/Paris": "FR",
20
33
  "Europe/Berlin": "DE",
21
34
  "Europe/Busingen": "DE",
35
+ "Europe/Warsaw": "PL",
36
+ "Europe/Vienna": "AT",
37
+ "Europe/Madrid": "ES",
38
+ "Europe/Amsterdam": "NL",
39
+ "Europe/Brussels": "BE",
40
+ "Europe/Dublin": "IE",
41
+ "Europe/Helsinki": "FI",
22
42
  "America/Los_Angeles": "US-CAL-CISO",
23
43
  "America/New_York": "US-MIDA-PJM",
24
44
  "America/Detroit": "US-MIDA-PJM",
45
+ "Asia/Seoul": "KR",
46
+ "Asia/Singapore": "SG",
47
+ "Asia/Dubai": "AE",
48
+ "Australia/Sydney": "AU-NSW",
49
+ "Africa/Johannesburg": "ZA",
50
+ "Pacific/Auckland": "NZ",
51
+ };
52
+ const UA_NOTE = "No Ukrainian grid data yet; using Poland (PL), the nearest grid in the same synchronous area.";
53
+ const UA_APPROXIMATION = Object.freeze({
54
+ region: "PL",
55
+ approximate: Object.freeze({ country: "UA", note: UA_NOTE }),
56
+ });
57
+ /**
58
+ * Time zones whose own grid is not in the catalog, mapped to the nearest
59
+ * catalog zone. PL is the only catalog zone that borders Ukraine and shares
60
+ * its synchronous area (Continental Europe, since March 2022): hour-of-day
61
+ * timing carries over, absolute grams do not.
62
+ */
63
+ export const APPROXIMATE_TIMEZONE_REGION = {
64
+ "Europe/Kyiv": UA_APPROXIMATION,
65
+ "Europe/Kiev": UA_APPROXIMATION,
66
+ "Europe/Uzhgorod": UA_APPROXIMATION,
67
+ "Europe/Zaporozhye": UA_APPROXIMATION,
25
68
  };
69
+ /** The catalog zone for `input` (case-insensitive), or undefined. */
70
+ export function catalogZone(input) {
71
+ if (!input)
72
+ return undefined;
73
+ const zone = input.trim().toUpperCase();
74
+ return Object.hasOwn(REGION_CATALOG, zone) ? zone : undefined;
75
+ }
26
76
  /** Map an IANA timezone to a supported grid region, or undefined. */
27
77
  export function regionForTimezone(timeZone) {
28
- return TIMEZONE_REGION[timeZone];
78
+ return guessRegionFromTimeZone(timeZone)?.region;
79
+ }
80
+ /** The host machine's IANA time zone, or undefined when it cannot be read. */
81
+ export function hostTimeZone() {
82
+ try {
83
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /**
90
+ * Guess a catalog zone from an IANA time zone: an exact map entry, else an
91
+ * approximate one (with the reason), else undefined.
92
+ */
93
+ export function guessRegionFromTimeZone(timeZone) {
94
+ if (!timeZone)
95
+ return undefined;
96
+ const exact = Object.hasOwn(TIMEZONE_REGION, timeZone) ? TIMEZONE_REGION[timeZone] : undefined;
97
+ if (exact)
98
+ return { region: exact };
99
+ return Object.hasOwn(APPROXIMATE_TIMEZONE_REGION, timeZone)
100
+ ? APPROXIMATE_TIMEZONE_REGION[timeZone]
101
+ : undefined;
29
102
  }
30
103
  /** Guess the grid region from the host machine's IANA timezone. */
31
104
  export function detectRegionFromTimezone() {
105
+ return regionForTimezone(hostTimeZone() ?? "");
106
+ }
107
+ /** Warning text for a stored region that is not a catalog zone. */
108
+ export function ignoredRegionMessage(value) {
109
+ return `Stored region ${value} is not supported; ignored.`;
110
+ }
111
+ export function resolveRegion(inputOrRequested, configuredDefault) {
112
+ const input = typeof inputOrRequested === "object" && inputOrRequested !== null
113
+ ? inputOrRequested
114
+ : {
115
+ requested: inputOrRequested,
116
+ configured: { value: configuredDefault, source: "config" },
117
+ };
118
+ if (input.requested)
119
+ return { region: input.requested, source: "flag" };
120
+ const configured = input.configured;
121
+ if (configured?.value)
122
+ return { region: configured.value, source: configured.source };
123
+ const raw = input.setting?.trim();
124
+ const stored = catalogZone(raw);
125
+ if (stored)
126
+ return { region: stored, source: "setting" };
127
+ const ignored = raw ? { ignored: raw } : {};
128
+ const timeZone = "timeZone" in input ? input.timeZone : hostTimeZone();
129
+ const zoneInfo = timeZone ? { timeZone } : {};
130
+ const guess = guessRegionFromTimeZone(timeZone);
131
+ if (guess)
132
+ return { ...guess, source: "timezone", ...zoneInfo, ...ignored };
133
+ return { region: FALLBACK_REGION, source: "fallback", ...zoneInfo, ...ignored };
134
+ }
135
+ /**
136
+ * The raw region setting from `~/.tidegap/config` (or `path`), or undefined
137
+ * when the file or the key is missing, empty or unreadable. Not validated:
138
+ * resolveRegion skips a value that is not a catalog zone.
139
+ */
140
+ export function loadRegionSetting(path = carbonBudgetConfigPath()) {
141
+ if (!existsSync(path))
142
+ return undefined;
32
143
  try {
33
- return regionForTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);
144
+ const value = parseKeyValues(readFileSync(path, "utf8"))[REGION_SETTING_KEY]?.trim();
145
+ return value || undefined;
34
146
  }
35
147
  catch {
36
148
  return undefined;
37
149
  }
38
150
  }
151
+ /** Edit distance (Levenshtein) between two short strings. */
152
+ function editDistance(a, b) {
153
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
154
+ for (let i = 1; i <= a.length; i++) {
155
+ const cur = [i];
156
+ for (let j = 1; j <= b.length; j++) {
157
+ cur[j] = Math.min((prev[j] ?? 0) + 1, (cur[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1));
158
+ }
159
+ prev = cur;
160
+ }
161
+ return prev[b.length] ?? 0;
162
+ }
39
163
  /**
40
- * Resolve a grid region. Precedence:
41
- * 1. an explicit request region (a tool argument / CLI flag),
42
- * 2. a configured default (plugin config / TIDEGAP_DEFAULT_REGION),
43
- * 3. a guess from the host machine's timezone,
44
- * 4. FALLBACK_REGION.
164
+ * Largest edit distance still offered as a closest match: 1 for inputs of up
165
+ * to 3 characters (any two 2-letter codes are within distance 2, so a wider
166
+ * bound would suggest unrelated zones), else 2.
45
167
  */
46
- export function resolveRegion(requested, configuredDefault) {
47
- if (requested)
48
- return { region: requested, source: "request" };
49
- if (configuredDefault) {
50
- return { region: configuredDefault, source: "config" };
51
- }
52
- const detected = detectRegionFromTimezone();
53
- if (detected)
54
- return { region: detected, source: "timezone" };
55
- return { region: FALLBACK_REGION, source: "default" };
168
+ function maxSuggestDistance(text) {
169
+ return text.length <= 3 ? 1 : 2;
170
+ }
171
+ /** Common codes that are not the ISO code of their catalog zone. */
172
+ export const COUNTRY_ALIASES = { UK: "GB" };
173
+ /**
174
+ * Up to `limit` catalog zones closest to an unknown input, in catalog order
175
+ * within each rule. The first rule with a result decides:
176
+ * 1. the zone of a common alias (UK → GB), or the approximate-map
177
+ * target of a typed country code (UA → PL),
178
+ * 2. zones whose code, name, country code or country name starts with it,
179
+ * 3. zones whose code is within edit distance 2 (1 for inputs of up to
180
+ * 3 characters), nearest first.
181
+ */
182
+ export function closestRegions(input, limit = 3) {
183
+ const text = input.trim().toUpperCase();
184
+ if (!text)
185
+ return [];
186
+ const zones = Object.keys(REGION_CATALOG);
187
+ if (Object.hasOwn(COUNTRY_ALIASES, text))
188
+ return [COUNTRY_ALIASES[text]];
189
+ const approximate = [
190
+ ...new Set(Object.values(APPROXIMATE_TIMEZONE_REGION)
191
+ .filter((a) => a.approximate.country === text)
192
+ .map((a) => a.region)),
193
+ ];
194
+ if (approximate.length > 0)
195
+ return approximate.slice(0, limit);
196
+ const prefixed = Object.entries(REGION_CATALOG)
197
+ .filter(([zone, e]) => [zone, e.name, e.country, e.countryName].some((f) => f.toUpperCase().startsWith(text)))
198
+ .map(([zone]) => zone);
199
+ if (prefixed.length > 0)
200
+ return prefixed.slice(0, limit);
201
+ const maxDistance = maxSuggestDistance(text);
202
+ return zones
203
+ .map((zone, order) => ({ zone, order, d: editDistance(text, zone) }))
204
+ .filter((m) => m.d <= maxDistance)
205
+ .sort((x, y) => x.d - y.d || x.order - y.order)
206
+ .slice(0, limit)
207
+ .map((m) => m.zone);
56
208
  }
57
209
  //# sourceMappingURL=region.js.map