@tidegap/core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +3 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/budget.d.ts +0 -12
  5. package/dist/budget.js +2 -24
  6. package/dist/channels/commands.d.ts +137 -0
  7. package/dist/channels/commands.js +377 -0
  8. package/dist/channels/delivery-codes.d.ts +9 -0
  9. package/dist/channels/delivery-codes.js +53 -0
  10. package/dist/channels/digest.d.ts +102 -0
  11. package/dist/channels/digest.js +146 -0
  12. package/dist/channels/format.d.ts +127 -0
  13. package/dist/channels/format.js +407 -0
  14. package/dist/channels/index.d.ts +15 -0
  15. package/dist/channels/index.js +15 -0
  16. package/dist/channels/kinds/command.d.ts +13 -0
  17. package/dist/channels/kinds/command.js +65 -0
  18. package/dist/channels/kinds/discord.d.ts +16 -0
  19. package/dist/channels/kinds/discord.js +67 -0
  20. package/dist/channels/kinds/email.d.ts +20 -0
  21. package/dist/channels/kinds/email.js +162 -0
  22. package/dist/channels/kinds/index.d.ts +8 -0
  23. package/dist/channels/kinds/index.js +17 -0
  24. package/dist/channels/kinds/ntfy.d.ts +25 -0
  25. package/dist/channels/kinds/ntfy.js +163 -0
  26. package/dist/channels/kinds/pushover.d.ts +11 -0
  27. package/dist/channels/kinds/pushover.js +77 -0
  28. package/dist/channels/kinds/shared.d.ts +25 -0
  29. package/dist/channels/kinds/shared.js +39 -0
  30. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  31. package/dist/channels/kinds/shortcuts.js +45 -0
  32. package/dist/channels/kinds/slack.d.ts +8 -0
  33. package/dist/channels/kinds/slack.js +57 -0
  34. package/dist/channels/kinds/telegram.d.ts +4 -0
  35. package/dist/channels/kinds/telegram.js +26 -0
  36. package/dist/channels/kinds/webhook.d.ts +30 -0
  37. package/dist/channels/kinds/webhook.js +177 -0
  38. package/dist/channels/payload.d.ts +36 -0
  39. package/dist/channels/payload.js +61 -0
  40. package/dist/channels/plan.d.ts +24 -0
  41. package/dist/channels/plan.js +66 -0
  42. package/dist/channels/registry.d.ts +191 -0
  43. package/dist/channels/registry.js +125 -0
  44. package/dist/channels/telegram.d.ts +110 -0
  45. package/dist/channels/telegram.js +168 -0
  46. package/dist/channels/types.d.ts +107 -0
  47. package/dist/channels/types.js +26 -0
  48. package/dist/claude-tools.d.ts +29 -0
  49. package/dist/claude-tools.js +49 -0
  50. package/dist/data/tables.generated.d.ts +6 -0
  51. package/dist/data/tables.generated.js +37 -0
  52. package/dist/energy.d.ts +77 -0
  53. package/dist/energy.js +131 -0
  54. package/dist/grid.d.ts +19 -2
  55. package/dist/grid.js +84 -28
  56. package/dist/handoff.d.ts +152 -0
  57. package/dist/handoff.js +430 -0
  58. package/dist/history.d.ts +2 -0
  59. package/dist/history.js +3 -1
  60. package/dist/index.d.ts +46 -16
  61. package/dist/index.js +34 -8
  62. package/dist/job-cadence.d.ts +76 -0
  63. package/dist/job-cadence.js +240 -0
  64. package/dist/jobs.d.ts +173 -0
  65. package/dist/jobs.js +794 -0
  66. package/dist/notify.d.ts +2 -0
  67. package/dist/notify.js +2 -1
  68. package/dist/paths.d.ts +13 -46
  69. package/dist/paths.js +51 -219
  70. package/dist/postpone.d.ts +113 -0
  71. package/dist/postpone.js +185 -0
  72. package/dist/providers/anthropic.js +7 -3
  73. package/dist/providers/base.d.ts +113 -1
  74. package/dist/providers/base.js +15 -0
  75. package/dist/providers/budget.d.ts +25 -0
  76. package/dist/providers/budget.js +57 -0
  77. package/dist/providers/defaults.js +4 -0
  78. package/dist/providers/defer.d.ts +16 -0
  79. package/dist/providers/defer.js +31 -0
  80. package/dist/providers/gemini.d.ts +1 -0
  81. package/dist/providers/gemini.js +27 -20
  82. package/dist/providers/index.d.ts +2 -2
  83. package/dist/providers/index.js +1 -1
  84. package/dist/providers/ollama.d.ts +1 -0
  85. package/dist/providers/ollama.js +26 -22
  86. package/dist/providers/openai.js +5 -5
  87. package/dist/providers/timeout.d.ts +18 -0
  88. package/dist/providers/timeout.js +33 -0
  89. package/dist/quota.d.ts +7 -2
  90. package/dist/quota.js +13 -29
  91. package/dist/readiness.d.ts +169 -0
  92. package/dist/readiness.js +254 -0
  93. package/dist/redact.d.ts +42 -0
  94. package/dist/redact.js +110 -0
  95. package/dist/region-host.d.ts +30 -0
  96. package/dist/region-host.js +69 -0
  97. package/dist/region.d.ts +102 -20
  98. package/dist/region.js +175 -23
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +95 -0
  102. package/dist/schedule-job.js +195 -0
  103. package/dist/scheduler.d.ts +245 -14
  104. package/dist/scheduler.js +925 -110
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +157 -5
  108. package/dist/storage/sqlite.js +661 -20
  109. package/dist/task-events.d.ts +102 -0
  110. package/dist/task-events.js +308 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +359 -65
  113. package/dist/types.d.ts +246 -3
  114. package/dist/types.js +8 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +11 -6
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Readiness (coherence KTD1 to KTD3): one answer to "will queued tasks
3
+ * run?" from two facts, a ticker runs and each pending task's provider has
4
+ * a runner. Pure over facts the host gathers; core spawns nothing.
5
+ * A fact nobody can observe is "unknown" and raises no problem (R2).
6
+ */
7
+ /** Ledger meta key of the {@link SleepReading} the last CLI tick took. */
8
+ export const TICK_SLEEP_META_KEY = "last_tick_sleep";
9
+ /**
10
+ * Ledger meta key: who started the last CLI tick. `unit` is the launchd or
11
+ * systemd unit or a `tick --daemon` loop; `manual` is a one-off
12
+ * `tidegap tick --once` from a shell, which proves nothing about the unit.
13
+ */
14
+ export const TICK_BY_META_KEY = "last_tick_by";
15
+ /** Two readings this far apart in boot time belong to different boots. */
16
+ const BOOT_TOLERANCE_MS = 120_000;
17
+ /** Sleep shorter than this explains nothing and is not shown. */
18
+ const SLEEP_MIN_MS = 60_000;
19
+ /**
20
+ * Ms asleep between two readings; 0 when they cannot be compared (missing,
21
+ * another boot, a counter that went back). Never more than `wallGapMs`.
22
+ */
23
+ export function sleptBetween(then, now, wallGapMs) {
24
+ if (!then || !now || Math.abs(then.boot_at - now.boot_at) > BOOT_TOLERANCE_MS)
25
+ return 0;
26
+ const slept = now.slept_ms - then.slept_ms;
27
+ return Number.isFinite(slept) && slept > 0 ? Math.min(slept, Math.max(0, wallGapMs)) : 0;
28
+ }
29
+ /**
30
+ * True when the sleep counter is worth reading now: a stored reading exists
31
+ * and the wall gap since the last tick is over two intervals (shorter gaps
32
+ * raise no problem, so the read is skipped). Shared by every host.
33
+ */
34
+ export function sleepReadNeeded(lastTickSleep, lastTickAt, now, intervalS) {
35
+ return !!lastTickSleep && now.getTime() - Date.parse(lastTickAt ?? "") > 2 * intervalS * 1000;
36
+ }
37
+ /** Read the {@link TICK_SLEEP_META_KEY} reading with its tick time; null when absent or malformed. */
38
+ export function readTickSleep(store) {
39
+ const raw = store.getMeta(TICK_SLEEP_META_KEY);
40
+ if (!raw)
41
+ return null;
42
+ try {
43
+ const v = JSON.parse(raw);
44
+ if (!Number.isFinite(v.boot_at) || !Number.isFinite(v.slept_ms) || !Number.isFinite(v.at))
45
+ return null;
46
+ return { boot_at: v.boot_at, slept_ms: v.slept_ms, at: v.at };
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Write the reading of the tick at `at`; null removes it. The tick time is
54
+ * stored with it: another ticker (the OpenClaw loop) can move `last_tick_at`
55
+ * without a reading, and an old reading must never pair with a newer tick.
56
+ */
57
+ export function writeTickSleep(store, reading, at) {
58
+ if (reading)
59
+ store.setMeta(TICK_SLEEP_META_KEY, JSON.stringify({ boot_at: reading.boot_at, slept_ms: reading.slept_ms, at: at.getTime() }));
60
+ else
61
+ store.deleteMeta(TICK_SLEEP_META_KEY);
62
+ }
63
+ /** Problems of the ticker, not of the runners: only a process outside the tick can see them (KTD11). */
64
+ export const TICKER_CODES = ["no_daemon", "daemon_not_loaded", "daemon_stale"];
65
+ /** Ledger meta key of the {@link TickRunnersSnapshot}. */
66
+ export const TICK_RUNNERS_META_KEY = "tick_runners";
67
+ const DAEMON_INTERVAL_S = 300;
68
+ const NO_DAEMON_INTERVAL_S = 60;
69
+ const ENV_FILE = "~/.config/tidegap/env";
70
+ const INSTALL = "tidegap install";
71
+ const TICK_ONCE = "tidegap tick --once";
72
+ const ORDER = ["no_daemon", "daemon_not_loaded", "daemon_stale", "no_runner"];
73
+ const PENDING = ["queued", "scheduled", "submitted"];
74
+ /** The fix for a provider with no runner. */
75
+ const RUNNER_FIX = {
76
+ anthropic: `install Claude Code, or add ANTHROPIC_API_KEY to ${ENV_FILE}`,
77
+ "claude-code": `install Claude Code, or set TIDEGAP_CLAUDE_BIN in ${ENV_FILE}`,
78
+ openai: `add OPENAI_API_KEY to ${ENV_FILE}`,
79
+ gemini: `add GEMINI_API_KEY to ${ENV_FILE}`,
80
+ ollama: `set OLLAMA_HOST in ${ENV_FILE}`,
81
+ // Only the CLI tick runs a command job's shell step.
82
+ command: INSTALL,
83
+ };
84
+ function daemonOnDisk(d) {
85
+ return d === "loaded" || d === "installed" || d === "installed_not_loaded";
86
+ }
87
+ /** The default tick interval for a daemon fact (as `DispatcherControl` uses). */
88
+ export function tickIntervalFor(daemon) {
89
+ return daemonOnDisk(daemon) ? DAEMON_INTERVAL_S : NO_DAEMON_INTERVAL_S;
90
+ }
91
+ /** Line text: a command fix reads "Run `cmd`."; an instruction reads "Fix: ...". */
92
+ export function problemLine(p) {
93
+ if (p.fix === TICK_ONCE)
94
+ return `${p.message} Run \`${p.fix}\` and check the error.`;
95
+ return p.fix.startsWith("tidegap ") ? `${p.message} Run \`${p.fix}\`.` : `${p.message} Fix: ${p.fix}.`;
96
+ }
97
+ /** Local HH:MM. */
98
+ function hhmm(ms) {
99
+ const d = new Date(ms);
100
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
101
+ }
102
+ /**
103
+ * "paused while the Mac slept (11:05–11:24)". The clock window needs the
104
+ * wake time and fits only one sleep after the last tick; else the length.
105
+ */
106
+ function sleepNote(sleptMs, lastMs, nowMs, wokeAt, platform) {
107
+ const machine = platform === "darwin" ? "the Mac" : "the computer";
108
+ const when = wokeAt !== undefined && wokeAt - sleptMs >= lastMs && wokeAt <= nowMs
109
+ ? `${hhmm(wokeAt - sleptMs)}–${hhmm(wokeAt)}`
110
+ : `about ${Math.round(sleptMs / 60_000)} minutes`;
111
+ return `the tick daemon paused while ${machine} slept (${when})`;
112
+ }
113
+ /** Assess readiness from gathered facts (KTD1, KTD3). */
114
+ export function assessReadiness(facts) {
115
+ const now = facts.now ?? new Date();
116
+ const intervalS = facts.tickIntervalS ?? tickIntervalFor(facts.daemon);
117
+ const last = facts.lastTickAt ? new Date(facts.lastTickAt) : null;
118
+ const lastMs = last && Number.isFinite(last.getTime()) ? last.getTime() : null;
119
+ const wallGap = lastMs === null ? 0 : now.getTime() - lastMs;
120
+ const then = facts.lastTickSleep;
121
+ const paired = then?.at !== undefined && lastMs !== null && Math.abs(then.at - lastMs) <= intervalS * 1000 ? then : null;
122
+ const slept = sleptBetween(paired, facts.sleepNow, wallGap);
123
+ const asleep = slept >= SLEEP_MIN_MS;
124
+ // Missed ticks are counted on awake time only. After a sleep, launchd may
125
+ // start a new interval at the wake, so one more interval is allowed.
126
+ const recent = lastMs !== null && wallGap - slept <= (asleep ? 3 : 2) * intervalS * 1000;
127
+ const lastExit = typeof facts.daemonLastExit === "number" ? facts.daemonLastExit : null;
128
+ const problems = [];
129
+ const notes = [];
130
+ if (recent && asleep && wallGap > 2 * intervalS * 1000) {
131
+ notes.push(sleepNote(slept, lastMs, now.getTime(), facts.sleepNow?.woke_at, facts.platform));
132
+ }
133
+ if (!recent) {
134
+ const d = facts.daemon;
135
+ if (d === "installed_not_loaded") {
136
+ problems.push({
137
+ code: "daemon_not_loaded",
138
+ message: "Tasks will not run: the tick daemon is installed but not loaded.",
139
+ fix: INSTALL,
140
+ });
141
+ }
142
+ else if (d === "loaded" || d === "installed") {
143
+ if (lastMs === null) {
144
+ notes.push("first tick within 5 minutes");
145
+ }
146
+ else {
147
+ // A loaded unit that stopped ticking needs the tick's own error, not a reinstall.
148
+ const min = Math.round(wallGap / 60_000);
149
+ const exited = d === "loaded" && lastExit !== null && lastExit !== 0 ? ` and exited with code ${lastExit}` : "";
150
+ problems.push({
151
+ code: "daemon_stale",
152
+ message: `Tasks may not run: the tick daemon last ran ${min} minutes ago${exited}.`,
153
+ fix: d === "loaded" ? TICK_ONCE : INSTALL,
154
+ });
155
+ }
156
+ }
157
+ else {
158
+ problems.push({ code: "no_daemon", message: "Tasks will not run: no tick daemon.", fix: INSTALL });
159
+ }
160
+ }
161
+ const runners = facts.runners;
162
+ if (runners?.notes)
163
+ notes.push(...runners.notes);
164
+ if (runners) {
165
+ for (const [provider, count] of Object.entries(facts.pendingByProvider).sort(([a], [b]) => a.localeCompare(b))) {
166
+ if (count <= 0 || runners.providers.includes(provider) || runners.unknown.includes(provider))
167
+ continue;
168
+ // Only a CLI tick runs the shell step and its snapshot names `command`; a
169
+ // probe cannot see it, and a tick that is not running is a ticker problem.
170
+ if (provider === "command" && runners.source !== "snapshot")
171
+ continue;
172
+ problems.push({
173
+ code: "no_runner",
174
+ message: `Tasks will not run: ${count} ${provider} ${count === 1 ? "task has" : "tasks have"} no runner.`,
175
+ fix: RUNNER_FIX[provider] ?? `configure the ${provider} provider in ${ENV_FILE}`,
176
+ provider,
177
+ tasks: count,
178
+ });
179
+ }
180
+ }
181
+ problems.sort((a, b) => ORDER.indexOf(a.code) - ORDER.indexOf(b.code));
182
+ return {
183
+ ready: problems.length === 0,
184
+ problems,
185
+ line: problems[0] ? problemLine(problems[0]) : null,
186
+ notes,
187
+ ticker: { daemon: facts.daemon, last_tick_at: lastMs === null ? null : new Date(lastMs).toISOString(), interval_s: intervalS, recent, slept_s: Math.round(slept / 1000), last_exit: lastExit },
188
+ runners: runners
189
+ ? { source: runners.source, providers: [...runners.providers], unknown: [...runners.unknown] }
190
+ : { source: "unknown", providers: [], unknown: [] },
191
+ };
192
+ }
193
+ /** The runner fact of a snapshot: a skipped lookup leaves `claude-code` and key-less `anthropic` unknown. */
194
+ export function runnersFromSnapshot(snapshot) {
195
+ const providers = [...snapshot.providers];
196
+ const unknown = snapshot.claude_lookup === "skipped" ? ["claude-code", "anthropic"].filter((p) => !providers.includes(p)) : [];
197
+ return { providers, unknown, source: "snapshot" };
198
+ }
199
+ /** True when `snapshot` is at most two tick intervals old (KTD2: then it wins over live probes). */
200
+ export function snapshotIsFresh(snapshot, now, intervalS) {
201
+ const at = Date.parse(snapshot.at);
202
+ return Number.isFinite(at) && now.getTime() - at <= 2 * intervalS * 1000;
203
+ }
204
+ /** Read the `tick_runners` snapshot; null when absent or malformed. */
205
+ export function readTickRunners(store) {
206
+ const raw = store.getMeta(TICK_RUNNERS_META_KEY);
207
+ if (!raw)
208
+ return null;
209
+ try {
210
+ const v = JSON.parse(raw);
211
+ if (typeof v.at !== "string" || !Array.isArray(v.providers))
212
+ return null;
213
+ return {
214
+ at: v.at,
215
+ providers: v.providers.filter((p) => typeof p === "string"),
216
+ claude_lookup: v.claude_lookup === "skipped" ? "skipped" : "done",
217
+ };
218
+ }
219
+ catch {
220
+ return null;
221
+ }
222
+ }
223
+ /** Write the `tick_runners` snapshot (every CLI tick, KTD2). */
224
+ export function writeTickRunners(store, snapshot) {
225
+ store.setMeta(TICK_RUNNERS_META_KEY, JSON.stringify(snapshot));
226
+ }
227
+ /**
228
+ * Pending (queued, scheduled, submitted) provider-call tasks by provider. A
229
+ * command job occurrence counts for `command` (the CLI tick runs it) and for
230
+ * its summarize step's provider, which needs a runner too.
231
+ */
232
+ export function pendingProvidersFromStore(store) {
233
+ const out = {};
234
+ const add = (p) => {
235
+ if (typeof p === "string")
236
+ out[p] = (out[p] ?? 0) + 1;
237
+ };
238
+ for (const status of PENDING) {
239
+ for (const rec of store.list({ status })) {
240
+ let body;
241
+ try {
242
+ body = JSON.parse(rec.bodyJson ?? "");
243
+ }
244
+ catch {
245
+ continue;
246
+ }
247
+ add(body?.provider);
248
+ if (body?.provider === "command")
249
+ add(body.summarize?.provider);
250
+ }
251
+ }
252
+ return out;
253
+ }
254
+ //# sourceMappingURL=readiness.js.map
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