mercury-agent 0.16.0 → 0.16.2
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.
- package/README.md +6 -0
- package/container/Dockerfile +6 -1
- package/container/Dockerfile.base +6 -1
- package/docs/README.md +50 -0
- package/docs/authoring-profiles.md +8 -0
- package/docs/behavior-layers.md +193 -0
- package/docs/extensions.md +2 -0
- package/docs/goals/football-reporter-profile/decisions.md +479 -0
- package/docs/goals/football-reporter-profile/goal.md +91 -0
- package/docs/goals/football-reporter-profile/roadmap.md +196 -0
- package/docs/goals/whatsapp-bot-hardening/README.md +43 -0
- package/docs/goals/whatsapp-bot-hardening/archive/ambient-group-context.md +211 -0
- package/docs/goals/whatsapp-bot-hardening/archive/command-routing-consistency.md +210 -0
- package/docs/goals/whatsapp-bot-hardening/archive/destructive-command-guards.md +218 -0
- package/docs/goals/whatsapp-bot-hardening/archive/docs-extension.md +182 -0
- package/docs/goals/whatsapp-bot-hardening/archive/handoff-2026-08-09.md +588 -0
- package/docs/goals/whatsapp-bot-hardening/archive/media-size-and-silent-drop.md +178 -0
- package/docs/goals/whatsapp-bot-hardening/archive/member-memory.md +199 -0
- package/docs/goals/whatsapp-bot-hardening/archive/message-author-attribution.md +211 -0
- package/docs/goals/whatsapp-bot-hardening/archive/run-from-source-switchover.md +212 -0
- package/docs/goals/whatsapp-bot-hardening/archive/setup-plan-2026-08-06.md +1117 -0
- package/docs/goals/whatsapp-bot-hardening/decisions.md +200 -0
- package/docs/goals/whatsapp-bot-hardening/goal.md +75 -0
- package/docs/goals/whatsapp-bot-hardening/open-threads.md +396 -0
- package/docs/goals/whatsapp-bot-hardening/roadmap.md +245 -0
- package/docs/memory.md +30 -0
- package/docs/profile-guide.md +483 -0
- package/docs/refactor/.gitkeep +0 -0
- package/docs/refactor/archive/.gitkeep +0 -0
- package/docs/refactor/audits/.gitkeep +0 -0
- package/docs/refactor/backlog/.gitkeep +0 -0
- package/docs/skills-guide.md +154 -0
- package/examples/extensions/README.md +1 -0
- package/examples/extensions/feed-watch/config.ts +354 -0
- package/examples/extensions/feed-watch/digest.ts +344 -0
- package/examples/extensions/feed-watch/feeds.ts +341 -0
- package/examples/extensions/feed-watch/index.ts +302 -0
- package/examples/extensions/feed-watch/items.ts +171 -0
- package/examples/extensions/feed-watch/match.ts +107 -0
- package/examples/extensions/feed-watch/prompts/verify.md +35 -0
- package/examples/extensions/feed-watch/skill/SKILL.md +128 -0
- package/examples/extensions/feed-watch/watch.ts +548 -0
- package/examples/extensions/longview/hook.ts +179 -16
- package/examples/extensions/longview/index.ts +13 -2
- package/examples/extensions/longview/prompts/summarize.md +3 -2
- package/examples/extensions/longview/render/telegraph-nodes.ts +21 -1
- package/examples/extensions/longview/summarize.ts +57 -14
- package/examples/extensions/napkin/index.ts +334 -86
- package/examples/extensions/napkin/pi-spawn.ts +196 -0
- package/examples/extensions/pinchtab/index.ts +37 -4
- package/examples/extensions/pinchtab/lib/session-injector.ts +31 -9
- package/examples/extensions/pinchtab/skill/SKILL.md +29 -0
- package/examples/profiles/_template/AGENTS.md +138 -0
- package/examples/profiles/_template/README.md +65 -0
- package/examples/profiles/_template/config.yaml +57 -0
- package/examples/profiles/_template/tasks/daily.md +32 -0
- package/examples/profiles/football-reporter/AGENTS.md +219 -0
- package/examples/profiles/football-reporter/README.md +138 -0
- package/examples/profiles/football-reporter/config.yaml +174 -0
- package/examples/profiles/football-reporter/seed/MEMORY.md +42 -0
- package/examples/profiles/football-reporter/seed/episodes/barcelona-2026-27.md +25 -0
- package/examples/profiles/football-reporter/seed/episodes/beitar-jerusalem-2026-27.md +25 -0
- package/examples/profiles/football-reporter/seed/episodes/maccabi-haifa-2026-27.md +24 -0
- package/examples/profiles/football-reporter/seed/episodes/man-united-2026-27.md +26 -0
- package/examples/profiles/football-reporter/seed/episodes/real-madrid-2026-27.md +25 -0
- package/examples/profiles/football-reporter/seed/napkin-distill.md +55 -0
- package/examples/profiles/football-reporter/tasks/daily-article.md +142 -0
- package/package.json +8 -5
- package/src/adapters/whatsapp.ts +75 -13
- package/src/bridges/whatsapp.ts +6 -4
- package/src/cli/mrctl.ts +9 -1
- package/src/core/handler.ts +51 -6
- package/src/core/routes/dashboard.ts +106 -5
- package/src/core/routes/tasks.ts +28 -0
- package/src/core/runtime.ts +63 -2
- package/src/core/task-scheduler.ts +103 -12
- package/src/extensions/catalog.ts +9 -0
- package/src/profile/space-profile.ts +780 -0
- package/src/storage/db.ts +215 -0
- package/src/types.ts +56 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# Skills — how the agent finds them, and how to make it actually use them
|
|
2
|
+
|
|
3
|
+
A skill is a directory with a `SKILL.md` (frontmatter `name` + `description`,
|
|
4
|
+
then instructions) plus whatever scripts, references and assets the
|
|
5
|
+
instructions need. Mercury ships built-in skills for `mrctl` (tasks, prefs,
|
|
6
|
+
recall, …), extensions ship theirs via `mercury.skill("./skill")`, and a
|
|
7
|
+
space may carry its own. This page is about the part that keeps going wrong:
|
|
8
|
+
the agent *has* a skill and does not use it, or uses it from memory instead
|
|
9
|
+
of reading it.
|
|
10
|
+
|
|
11
|
+
Verified against pi 0.84.2 (`dist/core/skills.js`, `resource-loader.js`,
|
|
12
|
+
`system-prompt.js` inside `mercury-agent-ext`) and `src/extensions/skills.ts`
|
|
13
|
+
on 2026-08-21.
|
|
14
|
+
|
|
15
|
+
## 1. Discovery — exactly two roots
|
|
16
|
+
|
|
17
|
+
pi scans two trees for `SKILL.md` files (recursively, honouring
|
|
18
|
+
`.gitignore`/`.ignore`):
|
|
19
|
+
|
|
20
|
+
| Root inside the container | Host path | Who puts things there |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| `/home/mercury/.pi/agent/skills/**` | `.mercury/global/skills/<name>/` | Mercury at startup: built-in skills from `resources/skills/`, extension skills copied from each extension's `skill/` dir (`installExtensionSkills`). Stale dirs are removed; an extension whose `mercury.requires([...])` no leg satisfies is skipped |
|
|
23
|
+
| `/spaces/<space>/.pi/skills/**` | `.mercury/spaces/<space>/.pi/skills/<name>/` | you (a space profile, an operator). Read per run; no restart |
|
|
24
|
+
|
|
25
|
+
Nothing else is scanned. A `skills/` folder at the space root, a skill inside
|
|
26
|
+
`knowledge/`, a `SKILL.md` next to `AGENTS.md` — pi does not see them. The
|
|
27
|
+
tagula copywriter profile keeps its engines under `/spaces/<id>/skills/…`
|
|
28
|
+
and that works only because its `AGENTS.md` spells out every invocation by
|
|
29
|
+
absolute path; the skill descriptions there are never offered to the model.
|
|
30
|
+
|
|
31
|
+
## 2. What the model sees
|
|
32
|
+
|
|
33
|
+
Every discovered skill is listed **in the system prompt**, after the
|
|
34
|
+
`AGENTS.md` files, as:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
<available_skills>
|
|
38
|
+
<skill>
|
|
39
|
+
<name>tasks</name>
|
|
40
|
+
<description>Manage scheduled tasks — create cron jobs or one-shot reminders…</description>
|
|
41
|
+
<location>/home/mercury/.pi/agent/skills/tasks/SKILL.md</location>
|
|
42
|
+
</skill>
|
|
43
|
+
…
|
|
44
|
+
</available_skills>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
preceded by: *"Use the read tool to load a skill's file when the task matches
|
|
48
|
+
its description."* That is the entire mechanism. The body of `SKILL.md` is
|
|
49
|
+
**not** in the prompt; the model decides from the description alone whether
|
|
50
|
+
to `read` the file, and it only gets the list at all when the run has the
|
|
51
|
+
`read` tool (a `--no-tools` model run also gets `--no-skills`).
|
|
52
|
+
|
|
53
|
+
So a skill is used when, and only when:
|
|
54
|
+
|
|
55
|
+
1. its `description` matches the situation in words the model will recognise,
|
|
56
|
+
2. the instructions elsewhere (`AGENTS.md`, the task prompt) do not already
|
|
57
|
+
tell the model what to do from memory, and
|
|
58
|
+
3. reading it is cheaper than guessing — a 400-line `SKILL.md` with the one
|
|
59
|
+
needed command on line 300 is read once and then paraphrased forever.
|
|
60
|
+
|
|
61
|
+
## 3. Writing the description
|
|
62
|
+
|
|
63
|
+
The `description` is the trigger. It is limited to 1024 characters, and the
|
|
64
|
+
`name` to 64 lowercase `[a-z0-9-]` characters.
|
|
65
|
+
|
|
66
|
+
- **Say when, not what.** "Use when the user asks to remember something for
|
|
67
|
+
future replies, set default data sources, or change how you should behave
|
|
68
|
+
in this space" (built-in `preferences`) beats "Manage preferences".
|
|
69
|
+
- **Use the user's words**, in every language the space speaks. The built-in
|
|
70
|
+
`conversation-recap` lists `סכם, תסכם, מה שאמרנו` alongside "summarize";
|
|
71
|
+
that is why it fires on Hebrew messages.
|
|
72
|
+
- **Name the negative.** "Use only when they want history — not for normal
|
|
73
|
+
questions." A skill that fires on everything is ignored on everything.
|
|
74
|
+
- **State the routing test when two skills overlap.** The tagula `tracker`
|
|
75
|
+
description ends with "if it is only a list of what exists — use the
|
|
76
|
+
`registry` skill instead", and the body opens with the test ("at least two
|
|
77
|
+
of: moving status, owner, due date, hierarchy"). Without that, the model
|
|
78
|
+
picks by name.
|
|
79
|
+
|
|
80
|
+
## 4. Writing the body
|
|
81
|
+
|
|
82
|
+
- **Commands first, verbatim, copy-pasteable**, with the absolute path the
|
|
83
|
+
agent must use (`/spaces/<space>/.pi/skills/<name>/engine/x.py`). pi
|
|
84
|
+
resolves relative paths against the skill dir, but an absolute path
|
|
85
|
+
removes one failure mode.
|
|
86
|
+
- **One hard rule per section, stated as a mechanism, not a plea.** "The
|
|
87
|
+
board is built by the engine, not by you" (tagula puzzles) is obeyed;
|
|
88
|
+
"try to avoid building boards by hand" is not.
|
|
89
|
+
- **Error messages are control flow.** If the engine says `try another
|
|
90
|
+
--seed`, the agent will loop on it — in front of the customer, until the
|
|
91
|
+
container is killed. Make transient errors say so and structural errors
|
|
92
|
+
say *what to change*, and tell the agent the retry budget in the skill
|
|
93
|
+
("up to three seeds total, then stop and shorten the name").
|
|
94
|
+
- **Numbers the agent will branch on come from the measured low end**, never
|
|
95
|
+
a remembered figure. A "regenerate if crossings < 65%" rule sat above the
|
|
96
|
+
median of a whole configuration and would have looped every board.
|
|
97
|
+
- **Long references go in `references/*.md`**, loaded on demand; keep
|
|
98
|
+
`SKILL.md` to what is needed on every use.
|
|
99
|
+
- **Declare state the skill owns** — a DB path, a registry file, a seed —
|
|
100
|
+
and the rule for it ("register every new tracker in `registries.json` or it
|
|
101
|
+
disappears").
|
|
102
|
+
|
|
103
|
+
## 5. Making a profile actually use its skills
|
|
104
|
+
|
|
105
|
+
Discovery puts the skill on the menu; the profile has to order from it.
|
|
106
|
+
|
|
107
|
+
1. **Name the skill in `AGENTS.md` with the situation and the first command**
|
|
108
|
+
— "Article status lives in the tracker. Never answer 'what is the status?'
|
|
109
|
+
from memory: `python3 $T --dir $D list --group-by status`." The copywriter
|
|
110
|
+
profile does this for every engine it ships, and points at the full
|
|
111
|
+
`SKILL.md` path for the rest ("read it before the first proposal").
|
|
112
|
+
2. **Make the skill the source of truth and say so** — "the tracker is the
|
|
113
|
+
source of truth, not your memory" turns "use the skill" into "you cannot
|
|
114
|
+
answer without the skill".
|
|
115
|
+
3. **Prefer a marker the host expands over a skill the model must remember.**
|
|
116
|
+
feed-watch's daily article carries `[feed-watch:digest]` in the task
|
|
117
|
+
prompt; the `before_container` hook replaces it with the real digest.
|
|
118
|
+
The model does nothing and cannot forget.
|
|
119
|
+
4. **Keep `AGENTS.md` and `SKILL.md` from disagreeing**: `AGENTS.md` says when
|
|
120
|
+
and the one-liner; `SKILL.md` says how. Do not paste the whole command
|
|
121
|
+
table into both — the copy that is not regenerated drifts.
|
|
122
|
+
5. **Verify with a trace, not a reply.** With `agent.trace_runs: true` the
|
|
123
|
+
`.mercury/traces/<run>.jsonl` shows the `read` of `SKILL.md` (or its
|
|
124
|
+
absence). "It answered correctly" proves nothing about whether the skill
|
|
125
|
+
was used.
|
|
126
|
+
|
|
127
|
+
## 6. Where a skill should live
|
|
128
|
+
|
|
129
|
+
| Skill belongs to | Put it | Reaches the container via |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| an extension (CLI, capability, host job) | `<extension>/skill/SKILL.md` + `mercury.skill("./skill")` | copied to `.mercury/global/skills/<ext>/` at startup; every space sees it |
|
|
132
|
+
| a space (a reporter's notebook routine, a studio's engines) | `.mercury/spaces/<space>/.pi/skills/<name>/` — in a space profile, add it to `workspace_seed` (M2.3) or copy it in the deploy step | mounted per run |
|
|
133
|
+
| an applicative profile (all spaces of a deployment) | inside one of the profile's `extensions/*/skill/` dirs | as an extension skill |
|
|
134
|
+
| the whole deployment but no extension | `.mercury/global/skills/<name>/` by hand | **do not** — `installExtensionSkills` removes directories it did not install as stale on every startup |
|
|
135
|
+
|
|
136
|
+
A space-local skill with substituted paths (`{SPACE}` → the real id) must
|
|
137
|
+
never be blanket-copied over from the source: the copy reverts the paths to
|
|
138
|
+
placeholders and the agent's commands break at runtime. Copy, substitute,
|
|
139
|
+
then `diff` and confirm the only difference is the placeholder.
|
|
140
|
+
|
|
141
|
+
## 7. Checklist before you ship a skill
|
|
142
|
+
|
|
143
|
+
- [ ] `name` is lowercase-kebab, ≤64 chars; `description` ≤1024 chars, says
|
|
144
|
+
*when*, in the space's languages, and names what it is *not* for.
|
|
145
|
+
- [ ] The first thing in the body is the command the agent needs most, with
|
|
146
|
+
an absolute path.
|
|
147
|
+
- [ ] Every error the engine can print either says "transient, retry N times"
|
|
148
|
+
or "structural, change X"; the skill states the retry budget.
|
|
149
|
+
- [ ] `AGENTS.md` names the skill for its situation and points at the file;
|
|
150
|
+
it does not duplicate the command table.
|
|
151
|
+
- [ ] The skill sits under one of the two scanned roots; `ls` it from inside
|
|
152
|
+
a container (`docker run --rm --entrypoint ls <image> /home/mercury/.pi/agent/skills`
|
|
153
|
+
for global ones) or check `<available_skills>` in a trace.
|
|
154
|
+
- [ ] A trace of one real run shows the `read` of `SKILL.md`.
|
|
@@ -10,4 +10,5 @@ Real-world Mercury extensions. Copy any of these into `.mercury/extensions/` to
|
|
|
10
10
|
| **pinchtab** | Browser automation via Playwright | cli, skill, permission, `before_container` hook (env + system prompt) |
|
|
11
11
|
| **napkin** | Obsidian vault management + KB distillation | cli, skill, permission, `workspace_init` hook, `before_container` hook, job, config, widget, store |
|
|
12
12
|
| **poster** | Styled posters with correct Hebrew/RTL text — AI background art + deterministic HTML typography | cli, skill, permission, env, config, `requires`, `before_container` hook (config → env) |
|
|
13
|
+
| **feed-watch** | Host-side RSS / Google-News poller — matches headlines against a per-space watchlist and opens a one-shot verify run; feeds the daily article a digest of everything seen. No model on the host side | skill, config, job, store, `before_container` hook (prompt append), `after_container` hook (cursor) |
|
|
13
14
|
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The eight per-space config keys, their validators, and the reader that turns
|
|
3
|
+
* eight strings into one typed `WatchConfig`.
|
|
4
|
+
*
|
|
5
|
+
* Two audiences, deliberately held apart:
|
|
6
|
+
*
|
|
7
|
+
* - **Validators** run at the write boundary (`PUT /api/config`, the dashboard
|
|
8
|
+
* panel, `mrctl config set`) and are strict — a bad value is rejected with a
|
|
9
|
+
* 400 while the admin is standing there to fix it.
|
|
10
|
+
* - **`readSpaceConfig`** runs on every poll and is forgiving. A value that was
|
|
11
|
+
* valid when it was set and is not now (a hand-edited DB, a key written
|
|
12
|
+
* before a validator tightened) falls back to the default and warns. Failing
|
|
13
|
+
* a poll over an unparseable `batch_minutes` would take the watcher down for
|
|
14
|
+
* a field that has a perfectly good default.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_MAX_PER_HOUR = 3;
|
|
18
|
+
export const DEFAULT_BATCH_MINUTES = 4;
|
|
19
|
+
export const MAX_SOURCES = 20;
|
|
20
|
+
export const MAX_TERMS = 50;
|
|
21
|
+
export const MAX_PER_HOUR_CEILING = 12;
|
|
22
|
+
export const MAX_BATCH_MINUTES = 30;
|
|
23
|
+
|
|
24
|
+
/** An RSS/Atom URL, polled as-is. */
|
|
25
|
+
export interface RssSource {
|
|
26
|
+
type: "rss";
|
|
27
|
+
url: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A Google-News search. With no `q` it expands to one query per watch term at
|
|
32
|
+
* fetch time, which is why `sources` can hold 13 entries and still issue 40
|
|
33
|
+
* requests — the cap counts what the admin wrote, not what it expands to.
|
|
34
|
+
*/
|
|
35
|
+
export interface GnewsSource {
|
|
36
|
+
type: "gnews";
|
|
37
|
+
/** Interface language, e.g. `he` or `en-GB`. */
|
|
38
|
+
hl?: string;
|
|
39
|
+
/** Geography, e.g. `IL` or `GB`. */
|
|
40
|
+
gl?: string;
|
|
41
|
+
/** Edition, e.g. `IL:he`. Derived from `gl`/`hl` when absent. */
|
|
42
|
+
ceid?: string;
|
|
43
|
+
/** Fixed query. When set, the source issues this one query instead of one per term. */
|
|
44
|
+
q?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type Source = RssSource | GnewsSource;
|
|
48
|
+
|
|
49
|
+
/** A local quiet window. `start` may be after `end` — it crosses midnight. */
|
|
50
|
+
export interface QuietHours {
|
|
51
|
+
start: string;
|
|
52
|
+
end: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface WatchConfig {
|
|
56
|
+
enabled: boolean;
|
|
57
|
+
sources: Source[];
|
|
58
|
+
terms: string[];
|
|
59
|
+
exclude: string[];
|
|
60
|
+
quietHours: QuietHours | null;
|
|
61
|
+
maxPerHour: number;
|
|
62
|
+
batchMinutes: number;
|
|
63
|
+
/** IANA zone, or "" to fall back to the deployment default and then UTC. */
|
|
64
|
+
timezone: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Minimal logger surface — the extension context's, narrowed for testing. */
|
|
68
|
+
export interface ConfigLogger {
|
|
69
|
+
warn(message: string, meta?: Record<string, unknown>): void;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Validators — strict, used at the write boundary
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
export function isValidEnabled(value: string): boolean {
|
|
77
|
+
return value === "true" || value === "false";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function parseJsonArray(value: string): unknown[] | null {
|
|
81
|
+
try {
|
|
82
|
+
const parsed: unknown = JSON.parse(value);
|
|
83
|
+
return Array.isArray(parsed) ? parsed : null;
|
|
84
|
+
} catch {
|
|
85
|
+
// Not JSON. The caller reports it as an invalid value; there is nothing
|
|
86
|
+
// here worth logging that the rejection does not already say.
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A source URL must be https — a watcher polling cleartext is a downgrade. */
|
|
92
|
+
function isHttpsUrl(value: unknown): boolean {
|
|
93
|
+
if (typeof value !== "string" || !value.trim()) return false;
|
|
94
|
+
try {
|
|
95
|
+
return new URL(value).protocol === "https:";
|
|
96
|
+
} catch {
|
|
97
|
+
// Unparseable URL — invalid, and the validator's `false` is the report.
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isOptionalString(value: unknown): boolean {
|
|
103
|
+
return value === undefined || (typeof value === "string" && value.length > 0);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** One entry of `sources`. Unknown `type` values are rejected, not ignored. */
|
|
107
|
+
export function isValidSourceEntry(entry: unknown): entry is Source {
|
|
108
|
+
if (typeof entry !== "object" || entry === null) return false;
|
|
109
|
+
const e = entry as Record<string, unknown>;
|
|
110
|
+
if (e.type === "rss") return isHttpsUrl(e.url);
|
|
111
|
+
if (e.type === "gnews") {
|
|
112
|
+
return (
|
|
113
|
+
isOptionalString(e.hl) &&
|
|
114
|
+
isOptionalString(e.gl) &&
|
|
115
|
+
isOptionalString(e.ceid) &&
|
|
116
|
+
isOptionalString(e.q)
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function isValidSources(value: string): boolean {
|
|
123
|
+
const arr = parseJsonArray(value);
|
|
124
|
+
if (!arr || arr.length > MAX_SOURCES) return false;
|
|
125
|
+
return arr.every(isValidSourceEntry);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function isValidTerms(value: string): boolean {
|
|
129
|
+
const arr = parseJsonArray(value);
|
|
130
|
+
if (!arr || arr.length > MAX_TERMS) return false;
|
|
131
|
+
return arr.every((t) => typeof t === "string" && t.trim().length > 0);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function isValidExclude(value: string): boolean {
|
|
135
|
+
const arr = parseJsonArray(value);
|
|
136
|
+
if (!arr || arr.length > MAX_TERMS) return false;
|
|
137
|
+
return arr.every((t) => typeof t === "string");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const HHMM_RANGE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/;
|
|
141
|
+
|
|
142
|
+
export function isValidQuietHours(value: string): boolean {
|
|
143
|
+
return value === "" || HHMM_RANGE.test(value.trim());
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function isIntInRange(value: string, min: number, max: number): boolean {
|
|
147
|
+
const t = value.trim();
|
|
148
|
+
if (!/^\d+$/.test(t)) return false;
|
|
149
|
+
const n = Number(t);
|
|
150
|
+
return n >= min && n <= max;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function isValidMaxPerHour(value: string): boolean {
|
|
154
|
+
return isIntInRange(value, 0, MAX_PER_HOUR_CEILING);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function isValidBatchMinutes(value: string): boolean {
|
|
158
|
+
return isIntInRange(value, 0, MAX_BATCH_MINUTES);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* An IANA zone name, checked by asking `Intl` to use it. Empty means "unset",
|
|
163
|
+
* which is a valid state — the poller falls back to the deployment default.
|
|
164
|
+
*/
|
|
165
|
+
export function isValidTimezone(value: string): boolean {
|
|
166
|
+
const t = value.trim();
|
|
167
|
+
if (t === "") return true;
|
|
168
|
+
try {
|
|
169
|
+
new Intl.DateTimeFormat("en-US", { timeZone: t });
|
|
170
|
+
return true;
|
|
171
|
+
} catch {
|
|
172
|
+
// `Intl` throws RangeError on an unknown zone — that is the whole test.
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
// Reader — forgiving, used on every poll
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
const KEY = (k: string) => `feed-watch.${k}`;
|
|
182
|
+
|
|
183
|
+
export type GetConfig = (spaceId: string, key: string) => string | null;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Read one key, run it past its validator, and fall back to the default with a
|
|
187
|
+
* warning if it fails. The warning names the key and the space — a value that
|
|
188
|
+
* silently reverts to a default is the shape of bug that reads as "the feature
|
|
189
|
+
* is off" for a week.
|
|
190
|
+
*/
|
|
191
|
+
function read(
|
|
192
|
+
getConfig: GetConfig,
|
|
193
|
+
spaceId: string,
|
|
194
|
+
key: string,
|
|
195
|
+
fallback: string,
|
|
196
|
+
validate: (v: string) => boolean,
|
|
197
|
+
log?: ConfigLogger,
|
|
198
|
+
): string {
|
|
199
|
+
const raw = getConfig(spaceId, KEY(key));
|
|
200
|
+
if (raw === null) return fallback;
|
|
201
|
+
if (validate(raw)) return raw;
|
|
202
|
+
log?.warn("feed-watch: unusable config value, using the default", {
|
|
203
|
+
spaceId,
|
|
204
|
+
key: KEY(key),
|
|
205
|
+
fallback,
|
|
206
|
+
});
|
|
207
|
+
return fallback;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Parse `quiet_hours` into its two ends. Returns null when unset. */
|
|
211
|
+
export function parseQuietHours(value: string): QuietHours | null {
|
|
212
|
+
const m = HHMM_RANGE.exec(value.trim());
|
|
213
|
+
if (!m) return null;
|
|
214
|
+
return { start: `${m[1]}:${m[2]}`, end: `${m[3]}:${m[4]}` };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Resolve every `feed-watch.*` key for a space into one typed object. */
|
|
218
|
+
export function readSpaceConfig(
|
|
219
|
+
getConfig: GetConfig,
|
|
220
|
+
spaceId: string,
|
|
221
|
+
log?: ConfigLogger,
|
|
222
|
+
): WatchConfig {
|
|
223
|
+
const sources = read(
|
|
224
|
+
getConfig,
|
|
225
|
+
spaceId,
|
|
226
|
+
"sources",
|
|
227
|
+
"[]",
|
|
228
|
+
isValidSources,
|
|
229
|
+
log,
|
|
230
|
+
);
|
|
231
|
+
const terms = read(getConfig, spaceId, "terms", "[]", isValidTerms, log);
|
|
232
|
+
const exclude = read(
|
|
233
|
+
getConfig,
|
|
234
|
+
spaceId,
|
|
235
|
+
"exclude",
|
|
236
|
+
"[]",
|
|
237
|
+
isValidExclude,
|
|
238
|
+
log,
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
enabled:
|
|
243
|
+
read(getConfig, spaceId, "enabled", "false", isValidEnabled, log) ===
|
|
244
|
+
"true",
|
|
245
|
+
// Safe by construction: every one of these passed its validator above, and
|
|
246
|
+
// each validator's first act is to parse the JSON.
|
|
247
|
+
sources: JSON.parse(sources) as Source[],
|
|
248
|
+
terms: (JSON.parse(terms) as string[]).map((t) => t.trim()),
|
|
249
|
+
exclude: (JSON.parse(exclude) as string[]).map((t) => t.trim()),
|
|
250
|
+
quietHours: parseQuietHours(
|
|
251
|
+
read(getConfig, spaceId, "quiet_hours", "", isValidQuietHours, log),
|
|
252
|
+
),
|
|
253
|
+
maxPerHour: Number(
|
|
254
|
+
read(
|
|
255
|
+
getConfig,
|
|
256
|
+
spaceId,
|
|
257
|
+
"max_per_hour",
|
|
258
|
+
String(DEFAULT_MAX_PER_HOUR),
|
|
259
|
+
isValidMaxPerHour,
|
|
260
|
+
log,
|
|
261
|
+
),
|
|
262
|
+
),
|
|
263
|
+
batchMinutes: Number(
|
|
264
|
+
read(
|
|
265
|
+
getConfig,
|
|
266
|
+
spaceId,
|
|
267
|
+
"batch_minutes",
|
|
268
|
+
String(DEFAULT_BATCH_MINUTES),
|
|
269
|
+
isValidBatchMinutes,
|
|
270
|
+
log,
|
|
271
|
+
),
|
|
272
|
+
),
|
|
273
|
+
timezone: read(
|
|
274
|
+
getConfig,
|
|
275
|
+
spaceId,
|
|
276
|
+
"timezone",
|
|
277
|
+
"",
|
|
278
|
+
isValidTimezone,
|
|
279
|
+
log,
|
|
280
|
+
).trim(),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
// Registration table — consumed by index.ts, asserted by the setup test
|
|
286
|
+
// ---------------------------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
export interface ConfigKeyDef {
|
|
289
|
+
key: string;
|
|
290
|
+
description: string;
|
|
291
|
+
default: string;
|
|
292
|
+
validate: (value: string) => boolean;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* The keys as the dashboard and `mrctl config get` see them. Kept as data so
|
|
297
|
+
* `index.ts` is a loop and the setup test can assert the whole set at once.
|
|
298
|
+
*/
|
|
299
|
+
export const CONFIG_KEYS: ConfigKeyDef[] = [
|
|
300
|
+
{
|
|
301
|
+
key: "enabled",
|
|
302
|
+
description:
|
|
303
|
+
"Poll this space's sources and open a verify run when something matches. Off by default: a disabled space fetches nothing and stores nothing.",
|
|
304
|
+
default: "false",
|
|
305
|
+
validate: isValidEnabled,
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
key: "sources",
|
|
309
|
+
description:
|
|
310
|
+
'JSON array (max 20) of {"type":"rss","url":"https://..."} or {"type":"gnews","hl":"he","gl":"IL","ceid":"IL:he"}. A gnews source with no "q" runs one search per watch term.',
|
|
311
|
+
default: "[]",
|
|
312
|
+
validate: isValidSources,
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
key: "terms",
|
|
316
|
+
description:
|
|
317
|
+
'JSON array (max 50) of what to watch, e.g. ["מכבי חיפה","Arsenal"]. Matched as a case-insensitive substring of the headline and summary, so Hebrew prefixes still hit. Keep Latin terms specific.',
|
|
318
|
+
default: "[]",
|
|
319
|
+
validate: isValidTerms,
|
|
320
|
+
},
|
|
321
|
+
{
|
|
322
|
+
key: "exclude",
|
|
323
|
+
description:
|
|
324
|
+
'JSON array of terms that drop an item outright, e.g. ["נוער","נשים","fantasy"]. Checked before the watch terms.',
|
|
325
|
+
default: "[]",
|
|
326
|
+
validate: isValidExclude,
|
|
327
|
+
},
|
|
328
|
+
{
|
|
329
|
+
key: "quiet_hours",
|
|
330
|
+
description:
|
|
331
|
+
'Local window in which no verify run is opened, as "HH:MM-HH:MM" (may cross midnight). Matched items still reach the next daily digest. Empty means never quiet.',
|
|
332
|
+
default: "",
|
|
333
|
+
validate: isValidQuietHours,
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
key: "max_per_hour",
|
|
337
|
+
description: `Most verify runs to open in a rolling hour (0–${MAX_PER_HOUR_CEILING}, default ${DEFAULT_MAX_PER_HOUR}). Overflow stays in the buffer for the digest. 0 is digest-only.`,
|
|
338
|
+
default: String(DEFAULT_MAX_PER_HOUR),
|
|
339
|
+
validate: isValidMaxPerHour,
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
key: "batch_minutes",
|
|
343
|
+
description: `How long to hold after the first match so several outlets carrying one event land in one run (0–${MAX_BATCH_MINUTES}, default ${DEFAULT_BATCH_MINUTES}).`,
|
|
344
|
+
default: String(DEFAULT_BATCH_MINUTES),
|
|
345
|
+
validate: isValidBatchMinutes,
|
|
346
|
+
},
|
|
347
|
+
{
|
|
348
|
+
key: "timezone",
|
|
349
|
+
description:
|
|
350
|
+
'IANA zone for quiet hours and digest timestamps, e.g. "Asia/Jerusalem". Empty falls back to the deployment default, then UTC.',
|
|
351
|
+
default: "",
|
|
352
|
+
validate: isValidTimezone,
|
|
353
|
+
},
|
|
354
|
+
];
|