mercury-agent 0.24.4-beta.2 → 0.24.4-beta.4

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 (38) hide show
  1. package/docs/configuration.md +2 -2
  2. package/docs/extensions.md +11 -0
  3. package/docs/pending-verification.md +12 -5
  4. package/docs/permissions.md +6 -0
  5. package/docs/web-search.md +4 -4
  6. package/examples/extensions/web-search/capability.ts +5 -1
  7. package/examples/extensions/web-search/chain.ts +3 -2
  8. package/examples/extensions/web-search/index.ts +15 -0
  9. package/examples/extensions/web-search/providers/index.ts +7 -1
  10. package/examples/extensions/web-search/providers/linkup.ts +203 -0
  11. package/examples/extensions/web-search/providers/types.ts +7 -1
  12. package/examples/extensions/web-search/skill/SKILL.md +3 -3
  13. package/package.json +2 -2
  14. package/resources/skills/problem-report/SKILL.md +53 -0
  15. package/resources/skills/tasks/SKILL.md +11 -0
  16. package/src/audit/ledger-queries.ts +3 -0
  17. package/src/cli/mercury.ts +14 -2
  18. package/src/cli/mrctl-http.ts +20 -0
  19. package/src/cli/mrctl.ts +11 -0
  20. package/src/core/api.ts +2 -0
  21. package/src/core/direct-send.ts +17 -0
  22. package/src/core/problem-report.ts +171 -37
  23. package/src/core/routes/console.ts +17 -2
  24. package/src/core/routes/dashboard.ts +5 -1
  25. package/src/core/routes/index.ts +1 -0
  26. package/src/core/routes/problem.ts +120 -0
  27. package/src/core/routes/spaces.ts +10 -2
  28. package/src/core/runtime.ts +138 -3
  29. package/src/core/space-delete.ts +71 -6
  30. package/src/core/system-messages.ts +5 -0
  31. package/src/core/task-output.ts +100 -3
  32. package/src/core/web-access-failures.ts +1 -1
  33. package/src/extensions/hooks.ts +10 -2
  34. package/src/extensions/reserved.ts +1 -0
  35. package/src/extensions/types.ts +27 -0
  36. package/src/server.ts +1 -0
  37. package/src/storage/memory.ts +9 -2
  38. package/src/types.ts +6 -1
@@ -24,7 +24,7 @@ These must be supplied via environment variables only; they are **not** read fro
24
24
  - `MERCURY_DISCORD_GATEWAY_SECRET`
25
25
  - `MERCURY_HEARTBEAT_URL` (see [Heartbeat](#heartbeat-mercury_heartbeat_url-mercury_heartbeat_tasks))
26
26
 
27
- Platform tokens, provider API keys, and extension keys (e.g. `MERCURY_TELEGRAM_BOT_TOKEN`, `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY`) are also **env-only** today—they are not part of the YAML schema.
27
+ Platform tokens, provider API keys, and extension keys (e.g. `MERCURY_TELEGRAM_BOT_TOKEN`, `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY`, `MERCURY_LINKUP_API_KEY`) are also **env-only** today—they are not part of the YAML schema.
28
28
 
29
29
  ## YAML layout
30
30
 
@@ -578,7 +578,7 @@ agent:
578
578
  ```
579
579
 
580
580
  - **`claimed`** (default) — only variables an extension declared via `mercury.env()` are passed, and only when the triggering caller holds that extension's permission. Undeclared variables stay on the host.
581
- - **`all`** — every `MERCURY_*` var except a fixed blocklist is passed into the container with the prefix stripped (`MERCURY_BILLING_API_KEY` → `BILLING_API_KEY`). Convenient, but blunt: a secret added to `.env` for one purpose reaches **every space's container**, regardless of who triggered the turn or whether that space has anything to do with it. Vars an extension declares `hostOnly` are excluded even here — `MERCURY_BRAVE_API_KEY` and `MERCURY_TAVILY_API_KEY` stay on the host once `web-search` is installed, which brokers search queries through `mrctl capability web-search` (see `docs/web-search.md` for the provider chain and its `web-search.providers`, `monthly_budget` and `tavily_monthly_budget` keys).
581
+ - **`all`** — every `MERCURY_*` var except a fixed blocklist is passed into the container with the prefix stripped (`MERCURY_BILLING_API_KEY` → `BILLING_API_KEY`). Convenient, but blunt: a secret added to `.env` for one purpose reaches **every space's container**, regardless of who triggered the turn or whether that space has anything to do with it. Vars an extension declares `hostOnly` are excluded even here — `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY` and `MERCURY_LINKUP_API_KEY` stay on the host once `web-search` is installed, which brokers search queries through `mrctl capability web-search` (see `docs/web-search.md` for the provider chain and its `web-search.providers`, `monthly_budget`, `tavily_monthly_budget` and `linkup_monthly_budget` keys).
582
582
 
583
583
  **Model-provider credentials are exempt** and pass in both modes (`MERCURY_ANTHROPIC_API_KEY`, `MERCURY_ANTHROPIC_OAUTH_TOKEN`, `MERCURY_GEMINI_API_KEY`, `MERCURY_GROQ_API_KEY`, and the rest of the provider list). pi reads them inside the container, and no extension declares them — without the exemption, `claimed` would leave the agent unable to reach any model. They remain subject to the blocklist.
584
584
 
@@ -167,6 +167,17 @@ mercury.on("workspace_init", async (event, ctx) => {
167
167
  | `before_container` | About to spawn container | Yes |
168
168
  | `after_container` | Container finished | Yes |
169
169
  | `delivery` | Reply stored, attachments final | No |
170
+ | `space_deleted` | A space's rows and workspace directory are gone | No |
171
+
172
+ `space_deleted` carries `spaceId`, `workspace` (the path it lived at),
173
+ `workspaceRemoved` (false when the directory could not be deleted), `source`
174
+ (`chat` | `api` | `console` | `cli`) and `callerId` (null for the console).
175
+ It is emitted once, from `deleteSpaceEverywhere`, after the delete — so it is
176
+ the place to undo what your extension created for the space *outside* its rows
177
+ and directory (a box-level timer, a remote copy). It is fire-and-forget: the
178
+ delete's reply does not wait for it, and a handler cannot undo or fail the
179
+ delete, so log what you did. The `mercury spaces delete` CLI loads no
180
+ extensions and therefore emits nothing; it prints a note saying so.
170
181
 
171
182
  Both `workspace_init` and `before_container` events include:
172
183
  - `workspace` — absolute host path (for file operations on the host)
@@ -2529,14 +2529,21 @@ zap extractor reads one-store cards labelled `למפרט טכני` (restart-depl
2529
2529
 
2530
2530
  ## Issue #143 / F19 — dashboard sessions and the failed-secret throttle (added 2026-10-19, deploy-gated: new release + restart)
2531
2531
 
2532
- - [ ] MANUAL-VERIFY(2026-10-19): Open `https://<box>/dashboard/login` in a private window. A password form should appear, not the dashboard. Enter the secret: the dashboard opens, the URL has no `token=`, and the browser's cookie list for the site shows `mercury_token` marked Secure, with a value that is not the secret.
2533
- - [ ] MANUAL-VERIFY(2026-10-19): Click **Sign out** at the top right. You should land on the login form, and reloading `/dashboard` should bring you back to it.
2534
- - [ ] MANUAL-VERIFY(2026-10-19): From a laptop, run `for i in $(seq 11); do curl -s -o /dev/null -w "%{http_code} " -H "Authorization: Bearer wrong" https://<box>/api/spaces; done`. You should see ten `401` then `429`. The journal should show `Secret check refused` lines with your real IP as `clientAddress` (not 127.0.0.1) and one `Failed-secret throttle engaged`. Wait 10 minutes before using the secret from that IP again.
2535
- - [ ] MANUAL-VERIFY(2026-10-19): In the Tagula console, open this box's embedded dashboard. It should load and update live, with no "Assistant login did not return a session" error (the console's `init` login still uses `?token=` and looks for a `mercury_token` cookie).
2532
+ *Verified 2026-10-20 on tagula-assistant (46.225.180.66), installed package `0.24.4-beta.2` (F19 throttle, `space-delete.ts` and `reapHostChildren` grepped in `/usr/lib/node_modules/mercury-agent/src`).*
2533
+
2534
+ - [x] MANUAL-VERIFY(2026-10-19): Open `https://<box>/dashboard/login` in a private window. A password form should appear, not the dashboard. Enter the secret: the dashboard opens, the URL has no `token=`, and the browser's cookie list for the site shows `mercury_token` marked Secure, with a value that is not the secret.
2535
+ *Verified 2026-10-20 by the owner.*
2536
+ - [x] MANUAL-VERIFY(2026-10-19): Click **Sign out** at the top right. You should land on the login form, and reloading `/dashboard` should bring you back to it.
2537
+ *Verified 2026-10-20 by the owner.*
2538
+ - [x] MANUAL-VERIFY(2026-10-19): From a laptop, run `for i in $(seq 11); do curl -s -o /dev/null -w "%{http_code} " -H "Authorization: Bearer wrong" https://<box>/api/spaces; done`. You should see ten `401` then `429`. The journal should show `Secret check refused` lines with your real IP as `clientAddress` (not 127.0.0.1) and one `Failed-secret throttle engaged`. Wait 10 minutes before using the secret from that IP again.
2539
+ *Verified 2026-10-20 23:38 IDT, run from the box through its public hostname (Caddy): ten `401` then `429`; journal `Secret check refused clientAddress=46.225.180.66` and one `Failed-secret throttle engaged ... retryAfterSeconds=600`. Side note: requests made on the box directly to `localhost:8787` carry no X-Forwarded-For and all share the `::1` bucket — local tools only, Caddy traffic is per client.*
2540
+ - [x] MANUAL-VERIFY(2026-10-19): In the Tagula console, open this box's embedded dashboard. It should load and update live, with no "Assistant login did not return a session" error (the console's `init` login still uses `?token=` and looks for a `mercury_token` cookie).
2541
+ *Verified 2026-10-20 by the owner: the embedded dashboard opens. Another console link answered 401; the box journal showed no refused console request at that time, so it is being checked on the tagula-agents side.*
2536
2542
 
2537
2543
  ## Issue #143 / F14 — deleting a space removes all of it (added 2026-10-19, deploy-gated: new release + restart)
2538
2544
 
2539
- - [ ] MANUAL-VERIFY(2026-10-19): Create a throwaway space, link a test group to it, send a message, then delete it from chat with `/spaces delete <id>` and answer `yes`. The reply should say it removed its files. On the box, `ls ~/whatsapp-bot/.mercury/spaces/<id>` should say "No such file", and `sqlite3 ~/whatsapp-bot/.mercury/state.db "SELECT COUNT(*) FROM conversations WHERE observed_title LIKE '%<group name>%'"` should print 0. Adjust the paths if the project lives elsewhere.
2545
+ - [x] MANUAL-VERIFY(2026-10-19): Create a throwaway space, link a test group to it, send a message, then delete it from chat with `/spaces delete <id>` and answer `yes`. The reply should say it removed its files. On the box, `ls ~/whatsapp-bot/.mercury/spaces/<id>` should say "No such file", and `sqlite3 ~/whatsapp-bot/.mercury/state.db "SELECT COUNT(*) FROM conversations WHERE observed_title LIKE '%<group name>%'"` should print 0. Adjust the paths if the project lives elsewhere.
2546
+ *Verified 2026-10-20 on `0.24.4-beta.2` with the stale customer space `meirav-magnezi` (owner-approved delete, not a throwaway): `ls /opt/tagula/assistants/tagula-assistant/.mercury/spaces/meirav-magnezi` → "No such file or directory"; a read-only scan of all 27 `state.db` tables found 0 rows with that `space_id`. Its `mercury-space-backup@` timer and its Drive copy (`rclone copy` never deletes) are outside F14 and still exist.*
2540
2547
 
2541
2548
  ## Plan tagula-client-1008 / S8 — the "Third-party apps" 400 falls to the next leg and alerts (added 2026-10-20, deploy-gated: image rebuild + restart)
2542
2549
 
@@ -69,6 +69,12 @@ sends a report card to the operator recipients (`alerts.recipients`, see
69
69
  `docs/configuration.md`) and starts no agent run. A paused space accepts only
70
70
  the one-message form, `/problem <what does not work>`.
71
71
 
72
+ `mrctl problem report "<summary>"` (`POST /api/problem`) also needs no
73
+ permission: the agent files the same report for the person it is talking to,
74
+ from any role's run. Identity is the caller token's (caller, space,
75
+ conversation); the body carries only the summary. A scheduled run, the
76
+ operator credential, and the `system` / `preflight` callers are refused.
77
+
72
78
  ### Media permissions
73
79
 
74
80
  `media.receive` and `media.send` gate the media pipeline per caller role, per space. Both are granted to `member` by default, so behavior is unchanged unless an operator revokes them (e.g. `mrctl permissions set member prompt,prefs.get` — omitting the media names revokes them in that space).
@@ -12,16 +12,16 @@ Or install from the dashboard's **Features** page (one click).
12
12
 
13
13
  No API key is required for the browser. The extension uses [pinchtab](https://www.npmjs.com/package/pinchtab) to control a local headless Chromium and opens pages the same way a human would. It states no search policy: it does not tell the agent to search through a search engine's own site, because a scraped `search.brave.com` is unmetered and ends in a "Verifying you're not a bot" page after a few queries.
14
14
 
15
- The separate `web-search` extension (`mercury add web-search`) adds structured site search (flights, hotels, cars, apartments) on top of pinchtab and, for fast keyword and news lookups, exposes a search **API** as a host-side capability: the agent runs `mrctl capability web-search news '{"q":"..."}'` (or `web`) and the host answers from a chain of providers, Brave first, then Tavily. Set a provider's key in `.env` to enable it: `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY` (Tavily's free plan: 1,000 searches a month, no card). The order is `web-search.providers` in the `@global` scope (default `brave,tavily`); a provider runs only when it is named there **and** its key is set, so a provider that must not run on a box has no key there. An unknown or repeated name narrows the chain to the names it gets right, warns on every call and alerts the operators once a month; it never widens to the default. Every reply names the `provider` that answered, and so does the journal's `web-search: query` line.
15
+ The separate `web-search` extension (`mercury add web-search`) adds structured site search (flights, hotels, cars, apartments) on top of pinchtab and, for fast keyword and news lookups, exposes a search **API** as a host-side capability: the agent runs `mrctl capability web-search news '{"q":"..."}'` (or `web`) and the host answers from a chain of providers, Brave first, then Tavily, then Linkup. Set a provider's key in `.env` to enable it: `MERCURY_BRAVE_API_KEY`, `MERCURY_TAVILY_API_KEY` (Tavily's free plan: 1,000 searches a month, no card), `MERCURY_LINKUP_API_KEY` (Linkup: $20/month free top-up for organizations signed up with a professional email, about 4,000 searches). The order is `web-search.providers` in the `@global` scope (default `brave,tavily,linkup`); a provider runs only when it is named there **and** its key is set, so a provider that must not run on a box has no key there. An unknown or repeated name narrows the chain to the names it gets right, warns on every call and alerts the operators once a month; it never widens to the default. Every reply names the `provider` that answered, and so does the journal's `web-search: query` line.
16
16
 
17
17
  A search moves to the next provider only when the provider fails: out of credit, a rejected key, a rate limit, a 5xx or network error, a timeout (10 s per attempt, 20 s per search), or a request it will not take. The caps below on the caller never fail over. While `web-search` is loaded **and some provider has a key**, every run's system prompt says keyword search goes only through that capability, never through a search engine's site in the browser, and its run-cap, hourly-cap and broken-key refusals say the same instead of pointing at the browser. Once **every** provider's credit is gone for the month (its budget below is spent, or it said so), that rule is replaced: the prompt and the refusal tell the agent to search in the browser, because a box with keys and no credit would otherwise have no keyword search at all. Without any key the capability answers every call with a 503, so that rule is not emitted: a keyless host states no search policy, like a host without `web-search`. Every key is declared `hostOnly`, so none enters a container; the host makes the call, applies a per-space hourly cap (`brave_hourly_cap`, default 60, counting searches whichever provider answers), and returns trimmed results.
18
18
 
19
19
  More brakes sit behind it:
20
20
  - **Per run:** `run_cap`, default 20 searches. The same query (same `q`, `count` and `freshness`) asked twice in one run is answered once, including two copies sent at the same time and a repeat after the run was refused. A cap set to a number too large to be exact (past 2^53 - 1) is rejected and falls back to the default.
21
- - **Per provider per host per calendar month (UTC):** `monthly_budget` (Brave's; default 1000, about its free grant) and `tavily_monthly_budget` (default 950, Tavily's 1,000 free credits less a margin). Read from the `@global` scope only, so a space cannot change them. They count attempts, so calls that time out or fail upstream count too. A provider whose budget is spent is skipped until the next month and the next one answers.
21
+ - **Per provider per host per calendar month (UTC):** `monthly_budget` (Brave's; default 1000, about its free grant) `tavily_monthly_budget` (default 950, Tavily's 1,000 free credits less a margin) and `linkup_monthly_budget` (default 3600, Linkup's $20 top-up at $0.005 a search, about 4,000, less a 10% margin because the top-up day is not stated). Read from the `@global` scope only, so a space cannot change them. They count attempts, so calls that time out or fail upstream count too. A provider whose budget is spent is skipped until the next month and the next one answers.
22
22
  - **Monthly warnings:** the host's operators (`admins`) get one message per provider at 80%, one at 95%, and one at 100%, when that provider is skipped; one more when every provider is spent and the bot moves to the browser (only with more than one provider enabled).
23
- - **A provider's own "out of credit":** credit can run out before this host's count does (another bot on the key, or usage from before the count existed). Brave's 402 marks Brave's month spent at the current `monthly_budget` and sends its 100% message; raising `monthly_budget` after topping up brings Brave back the same month. Tavily's 432/433 skips Tavily for 24 hours (its reset day is not stated), then it is tried once again; the first one each month alerts the operators.
24
- - **Skips that clear:** a rejected key skips that provider for 24 hours or until the key changes (one alert per key); a rate limit skips it for its `Retry-After` (60 s default, at most 10 min); a 5xx, network error or unreadable answer for 60 s. A timeout or a refused request skips nothing. A request a provider refuses alerts once a month, because a request shape every query trips is a bug.
23
+ - **A provider's own "out of credit":** credit can run out before this host's count does (another bot on the key, or usage from before the count existed). Brave's 402 marks Brave's month spent at the current `monthly_budget` and sends its 100% message; raising `monthly_budget` after topping up brings Brave back the same month. Tavily's 432/433 and Linkup's 429 with `INSUFFICIENT_FUNDS_CREDITS` or `EXCEED_BUDGET_LIMIT` (or any 429 whose body mentions credit) skip that provider for 24 hours (neither states its reset day), then it is tried once again; the first one each month alerts the operators. Linkup's other 429s are a rate limit, and its 402 (x402 pay-per-request, sent when no usable key reached it) counts as a rejected key.
24
+ - **Skips that clear:** a rejected key skips that provider for 24 hours or until the key changes (one alert per key); a rate limit skips it for its `Retry-After` (60 s default, at most 10 min); a 5xx, network error or unreadable answer for 60 s. A timeout or a refused request skips nothing. A request a provider refuses alerts once a month, because a request shape every query trips is a bug. Linkup answers a search that matched nothing with a 400 (`SEARCH_QUERY_NO_RESULT`); today that is a refused request too, so it moves on and can trigger that alert (`docs/bugs/linkup-no-result-400-is-read-as-a-refused-request.md`).
25
25
 
26
26
  The skips are rows in the extension's store and survive a restart. Read and clear them from a script file on the box:
27
27
 
@@ -50,6 +50,7 @@ import {
50
50
  } from "./providers/types.js";
51
51
 
52
52
  export { BRAVE_ENV } from "./providers/brave.js";
53
+ export { LINKUP_ENV } from "./providers/linkup.js";
53
54
  export { TAVILY_ENV } from "./providers/tavily.js";
54
55
  export { SEARCH_ACTIONS, type SearchAction } from "./providers/types.js";
55
56
 
@@ -62,7 +63,10 @@ export const BRAVE_PROVIDER = braveProvider.id;
62
63
  */
63
64
  export const braveApiKey = providerApiKey;
64
65
 
65
- /** Every provider's ceiling for `count` (Brave's and Tavily's are both 20). */
66
+ /**
67
+ * Every provider's ceiling for `count` (Brave's and Tavily's are both 20;
68
+ * Linkup's `maxResults` states no ceiling).
69
+ */
66
70
  export const MAX_COUNT = 20;
67
71
  export const DEFAULT_COUNT = 5;
68
72
 
@@ -400,8 +400,9 @@ async function attempt(
400
400
  query: SearchQuery,
401
401
  fetchImpl: FetchLike,
402
402
  boundMs: number,
403
+ nowMs: number,
403
404
  ): Promise<Raw | "timeout"> {
404
- const req = cp.provider.buildRequest(action, query, cp.apiKey);
405
+ const req = cp.provider.buildRequest(action, query, cp.apiKey, nowMs);
405
406
  const controller = new AbortController();
406
407
  const work = (async (): Promise<Raw> => {
407
408
  try {
@@ -531,7 +532,7 @@ export async function runChain(
531
532
  continue;
532
533
  }
533
534
 
534
- const raw = await attempt(cp, action, query, fetchImpl, boundMs);
535
+ const raw = await attempt(cp, action, query, fetchImpl, boundMs, startMs);
535
536
  const at = now();
536
537
 
537
538
  if (raw === "timeout") {
@@ -158,6 +158,10 @@ function readChainDeps(ctx: ConfigReader): Pick<
158
158
  apiKey: process.env[PROVIDERS.tavily.envKey],
159
159
  monthlyBudget: readMonthlyBudget(ctx, "tavily"),
160
160
  },
161
+ linkup: {
162
+ apiKey: process.env[PROVIDERS.linkup.envKey],
163
+ monthlyBudget: readMonthlyBudget(ctx, "linkup"),
164
+ },
161
165
  },
162
166
  order: orderParse.order,
163
167
  orderParse,
@@ -205,6 +209,13 @@ export default function (mercury: MercuryExtensionAPI) {
205
209
  validate: isValidCap,
206
210
  });
207
211
 
212
+ mercury.config(PROVIDERS.linkup.budgetConfigKey, {
213
+ description:
214
+ "Max billed Linkup searches this host makes per calendar month (UTC), across all spaces. Read from the global scope only. Linkup tops eligible accounts back up to $20 a month, about 4,000 searches at $0.005; the default leaves a margin. Warns at 80% and 95%; at 100% Linkup is skipped until next month. 0 skips Linkup.",
215
+ default: String(PROVIDERS.linkup.defaultMonthlyBudget),
216
+ validate: isValidCap,
217
+ });
218
+
208
219
  mercury.config(PROVIDERS_CONFIG_KEY, {
209
220
  description: `Search providers to try, in order, comma-separated (${Object.keys(PROVIDERS).join(", ")}). Read from the global scope only. A provider is used only when its API key is set on the host. An unknown or repeated name narrows the chain to the names it gets right, never widens it.`,
210
221
  default: DEFAULT_ORDER.join(","),
@@ -280,6 +291,10 @@ export default function (mercury: MercuryExtensionAPI) {
280
291
  apiKey: process.env[PROVIDERS.tavily.envKey],
281
292
  monthlyBudget: PROVIDERS.tavily.defaultMonthlyBudget,
282
293
  },
294
+ linkup: {
295
+ apiKey: process.env[PROVIDERS.linkup.envKey],
296
+ monthlyBudget: PROVIDERS.linkup.defaultMonthlyBudget,
297
+ },
283
298
  },
284
299
  }).length > 0;
285
300
  ctx.log?.warn("web-search: ledger read failed; assuming credit left", {
@@ -6,16 +6,22 @@
6
6
  */
7
7
 
8
8
  import { braveProvider } from "./brave.js";
9
+ import { linkupProvider } from "./linkup.js";
9
10
  import { tavilyProvider } from "./tavily.js";
10
11
  import type { ProviderId, SearchProvider } from "./types.js";
11
12
 
12
13
  export const PROVIDERS: Readonly<Record<ProviderId, SearchProvider>> = {
13
14
  brave: braveProvider,
14
15
  tavily: tavilyProvider,
16
+ linkup: linkupProvider,
15
17
  };
16
18
 
17
19
  /** The order when `web-search.providers` is not set at all. */
18
- export const DEFAULT_ORDER: readonly ProviderId[] = ["brave", "tavily"];
20
+ export const DEFAULT_ORDER: readonly ProviderId[] = [
21
+ "brave",
22
+ "tavily",
23
+ "linkup",
24
+ ];
19
25
 
20
26
  export function isProviderId(v: string): v is ProviderId {
21
27
  return Object.hasOwn(PROVIDERS, v);
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Linkup Search API (https://docs.linkup.so, read 2026-10-20): request,
3
+ * classification and trim. Pure; the chain makes the call (chain.ts).
4
+ *
5
+ * `depth: "standard"` with `outputType: "searchResults"` costs $0.005, the
6
+ * same as `fast` and `flash` (pricing page); `flash` is labelled Alpha and
7
+ * `deep` costs ten times as much. Eligible accounts (signed up with a
8
+ * professional email) are topped back up to $20 each month, about 4,000
9
+ * searches; the top-up day is not stated.
10
+ *
11
+ * Errors (errors page, and the official Python SDK's mapping): the body is
12
+ * `{statusCode, error: {code, message, details[]}}`. 429 is both "out of
13
+ * credit" (`INSUFFICIENT_FUNDS_CREDITS`) and "too many concurrent requests"
14
+ * (`TOO_MANY_REQUESTS`); 402 is x402 pay-per-request, which only happens when
15
+ * no usable key was sent.
16
+ */
17
+
18
+ import {
19
+ clip,
20
+ hostnameOf,
21
+ MAX_DESCRIPTION_CHARS,
22
+ MAX_DETAIL_CHARS,
23
+ type ProviderFailure,
24
+ rawErrorText,
25
+ retryAfterMs,
26
+ type SearchAction,
27
+ type SearchProvider,
28
+ type SearchQuery,
29
+ type SearchResult,
30
+ str,
31
+ } from "./types.js";
32
+
33
+ export const LINKUP_ENV = "MERCURY_LINKUP_API_KEY";
34
+ export const LINKUP_URL = "https://api.linkup.so/v1/search";
35
+
36
+ const DAY_MS = 24 * 60 * 60 * 1000;
37
+
38
+ /** Linkup filters by a start date, not a window: freshness becomes days back. */
39
+ const FRESHNESS_DAYS = { pd: 1, pw: 7, pm: 30, py: 365 } as const;
40
+
41
+ /**
42
+ * Linkup has no news topic, so `news` without a freshness gets the last week
43
+ * (the archived design, search-provider-fallback-chain): without a date,
44
+ * `news` would be the same search as `web`.
45
+ */
46
+ const NEWS_DEFAULT_DAYS = 7;
47
+
48
+ /** 429 codes that mean the money is gone, not that we were too fast. */
49
+ const CREDIT_CODES = new Set([
50
+ "INSUFFICIENT_FUNDS_CREDITS",
51
+ "EXCEED_BUDGET_LIMIT",
52
+ ]);
53
+
54
+ /** 429 codes that mean "too fast": never credit, whatever the message says. */
55
+ const RATE_CODES = new Set(["TOO_MANY_REQUESTS"]);
56
+
57
+ /** The UTC date `days` before `nowMs`, as Linkup's `fromDate` (YYYY-MM-DD). */
58
+ export function linkupFromDate(nowMs: number, days: number): string {
59
+ return new Date(nowMs - days * DAY_MS).toISOString().slice(0, 10);
60
+ }
61
+
62
+ export function linkupBody(
63
+ action: SearchAction,
64
+ query: SearchQuery,
65
+ nowMs: number,
66
+ ): Record<string, unknown> {
67
+ const days = query.freshness
68
+ ? FRESHNESS_DAYS[query.freshness]
69
+ : action === "news"
70
+ ? NEWS_DEFAULT_DAYS
71
+ : null;
72
+ return {
73
+ q: query.q,
74
+ depth: "standard",
75
+ outputType: "searchResults",
76
+ maxResults: query.count,
77
+ includeImages: false,
78
+ ...(days !== null ? { fromDate: linkupFromDate(nowMs, days) } : {}),
79
+ };
80
+ }
81
+
82
+ function trimLinkup(payload: unknown): SearchResult[] | null {
83
+ if (typeof payload !== "object" || payload === null) return null;
84
+ const raw = (payload as Record<string, unknown>).results;
85
+ if (!Array.isArray(raw)) return null;
86
+ return raw
87
+ .filter(
88
+ (r): r is Record<string, unknown> =>
89
+ typeof r === "object" && r !== null && r.type === "text",
90
+ )
91
+ .map((r) => {
92
+ const url = str(r.url);
93
+ return {
94
+ title: str(r.name),
95
+ url,
96
+ description: clip(
97
+ str(r.content).replace(/\s+/g, " ").trim(),
98
+ MAX_DESCRIPTION_CHARS,
99
+ ),
100
+ // Linkup's search results carry no date.
101
+ age: null,
102
+ source: hostnameOf(url),
103
+ };
104
+ })
105
+ .filter((r) => r.url !== "");
106
+ }
107
+
108
+ interface LinkupError {
109
+ code: string;
110
+ /** `CODE: message; field: message`, bounded; the raw text when not JSON. */
111
+ detail: string;
112
+ }
113
+
114
+ /** Linkup's reason from `{error: {code, message, details[]}}`, else the raw text. */
115
+ export function linkupError(text: string): LinkupError {
116
+ try {
117
+ const parsed = JSON.parse(text) as { error?: unknown };
118
+ const e = parsed?.error;
119
+ if (typeof e === "object" && e !== null && !Array.isArray(e)) {
120
+ const err = e as Record<string, unknown>;
121
+ const code = str(err.code).trim();
122
+ const parts = [str(err.message).trim()];
123
+ if (Array.isArray(err.details)) {
124
+ for (const d of err.details) {
125
+ if (typeof d !== "object" || d === null) continue;
126
+ const field = str((d as Record<string, unknown>).field).trim();
127
+ const msg = str((d as Record<string, unknown>).message).trim();
128
+ if (msg !== "") parts.push(field !== "" ? `${field}: ${msg}` : msg);
129
+ }
130
+ }
131
+ const message = parts.filter((p) => p !== "").join("; ");
132
+ const joined = [code, message].filter((p) => p !== "").join(": ");
133
+ if (joined !== "") {
134
+ return {
135
+ code,
136
+ detail: rawErrorText(joined).slice(0, MAX_DETAIL_CHARS),
137
+ };
138
+ }
139
+ }
140
+ } catch {
141
+ // Not JSON: the raw slice below is the reason, and the chain logs it.
142
+ }
143
+ return { code: "", detail: rawErrorText(text) };
144
+ }
145
+
146
+ export function classifyLinkup(
147
+ status: number,
148
+ bodyText: string,
149
+ headers: { get(name: string): string | null } | undefined,
150
+ ): ProviderFailure {
151
+ const { code, detail } = linkupError(bodyText);
152
+ const base = { status, detail };
153
+ // 402 is x402 pay-per-request: Linkup did not take the key we sent.
154
+ if (status === 401 || status === 402 || status === 403) {
155
+ return { kind: "auth", ...base };
156
+ }
157
+ if (status === 429) {
158
+ // The documented code first; the text only as a fallback for a body
159
+ // with no code we know, since "out of credit" and "too fast" share 429.
160
+ const known = CREDIT_CODES.has(code) || RATE_CODES.has(code);
161
+ if (CREDIT_CODES.has(code) || (!known && /credit/i.test(bodyText))) {
162
+ return { kind: "credit", ...base };
163
+ }
164
+ const after = retryAfterMs(headers);
165
+ return {
166
+ kind: "rate",
167
+ ...base,
168
+ ...(after !== null ? { retryAfterMs: after } : {}),
169
+ };
170
+ }
171
+ // TODO: 400 `SEARCH_QUERY_NO_RESULT` is "nothing matched", an empty answer
172
+ // rather than a refused request. `classify` can only return a failure, so
173
+ // it is `request` here: the chain moves on and the monthly `request:linkup`
174
+ // alert can fire for it. Reading it as an empty answer needs a chain seam
175
+ // (docs/bugs/linkup-no-result-400-is-read-as-a-refused-request.md).
176
+ if (status >= 400 && status < 500) return { kind: "request", ...base };
177
+ return { kind: "upstream", ...base };
178
+ }
179
+
180
+ export const linkupProvider: SearchProvider = {
181
+ id: "linkup",
182
+ label: "Linkup",
183
+ envKey: LINKUP_ENV,
184
+ budgetConfigKey: "linkup_monthly_budget",
185
+ // $20 a month at $0.005 a search is 4,000; 10% margin because the top-up
186
+ // day is unstated.
187
+ defaultMonthlyBudget: 3600,
188
+ creditIsMonthly: false,
189
+ buildRequest: (action, query, apiKey, nowMs) => ({
190
+ url: LINKUP_URL,
191
+ init: {
192
+ method: "POST",
193
+ headers: {
194
+ Accept: "application/json",
195
+ "Content-Type": "application/json",
196
+ Authorization: `Bearer ${apiKey}`,
197
+ },
198
+ body: JSON.stringify(linkupBody(action, query, nowMs)),
199
+ },
200
+ }),
201
+ classify: classifyLinkup,
202
+ trim: (payload) => trimLinkup(payload),
203
+ };
@@ -52,7 +52,7 @@ export interface ProviderFailure {
52
52
  retryAfterMs?: number;
53
53
  }
54
54
 
55
- export type ProviderId = "brave" | "tavily";
55
+ export type ProviderId = "brave" | "tavily" | "linkup";
56
56
 
57
57
  export interface ProviderRequest {
58
58
  url: string;
@@ -84,10 +84,16 @@ export interface SearchProvider {
84
84
  * row instead, then one probe (chain.ts).
85
85
  */
86
86
  creditIsMonthly: boolean;
87
+ /**
88
+ * `nowMs` is the chain's clock at the attempt, for a provider whose
89
+ * freshness is a date rather than a window (Linkup's `fromDate`). A
90
+ * provider that does not need it leaves the parameter out.
91
+ */
87
92
  buildRequest(
88
93
  action: SearchAction,
89
94
  query: SearchQuery,
90
95
  apiKey: string,
96
+ nowMs: number,
91
97
  ): ProviderRequest;
92
98
  /** Total over every non-200 status: an unlisted one falls into a default kind. */
93
99
  classify(
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: web-search
3
- description: "Search the web. Three paths — (1) the host's search API (Brave, then Tavily) for fast keyword/headline queries, keys held on the host — the body is one quoted JSON object, never a bare string: `mrctl capability web-search news '{\"q\":\"<query>\",\"count\":5,\"freshness\":\"pd\"}'` (or `web` instead of `news`; `freshness` pd/pw/pm/py, optional); (2) headless browser automation (pinchtab) for structured real-world searches — flights, hotels, car rentals, cars for purchase, apartments/rentals; (3) Israeli product prices on Zap (zap.co.il). Trigger when the user asks to search, look up news, find/compare/book travel, accommodation, vehicles or apartments, or asks what a store-bought product costs (product price, כמה עולה <product>, השוואת מחירים, זאפ)."
3
+ description: "Search the web. Three paths — (1) the host's search API (Brave, then Tavily, then Linkup) for fast keyword/headline queries, keys held on the host — the body is one quoted JSON object, never a bare string: `mrctl capability web-search news '{\"q\":\"<query>\",\"count\":5,\"freshness\":\"pd\"}'` (or `web` instead of `news`; `freshness` pd/pw/pm/py, optional); (2) headless browser automation (pinchtab) for structured real-world searches — flights, hotels, car rentals, cars for purchase, apartments/rentals; (3) Israeli product prices on Zap (zap.co.il). Trigger when the user asks to search, look up news, find/compare/book travel, accommodation, vehicles or apartments, or asks what a store-bought product costs (product price, כמה עולה <product>, השוואת מחירים, זאפ)."
4
4
  ---
5
5
 
6
6
  # Web Search
@@ -18,10 +18,10 @@ is that row's site search, not Zap: Zap compares products sold in shops.
18
18
 
19
19
  ## Quick search (search API)
20
20
 
21
- The host holds the search API keys (Brave, Tavily) and makes the call for
21
+ The host holds the search API keys (Brave, Tavily, Linkup) and makes the call for
22
22
  you, trying the next provider when one is out of credit or failing. There is
23
23
  no API key in your environment and you do not need one. Do not try to call
24
- `api.search.brave.com` or `api.tavily.com` yourself — the request will be
24
+ `api.search.brave.com`, `api.tavily.com` or `api.linkup.so` yourself — the request will be
25
25
  unauthenticated.
26
26
 
27
27
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mercury-agent",
3
- "version": "0.24.4-beta.2",
3
+ "version": "0.24.4-beta.4",
4
4
  "description": "Personal AI assistant for chat platforms (WhatsApp, Slack, Discord, Telegram)",
5
5
  "license": "MIT",
6
6
  "author": "Avishai Tsabari",
@@ -119,7 +119,7 @@
119
119
  "commander": "^15.0.0",
120
120
  "cron-parser": "^5.5.0",
121
121
  "discord.js": "^14.26.3",
122
- "hono": "^4.13.7",
122
+ "hono": "^4.13.11",
123
123
  "qrcode-terminal": "^0.12.0",
124
124
  "yaml": "^2.8.3",
125
125
  "zod": "^4.3.6"
@@ -0,0 +1,53 @@
1
+ ---
2
+ name: problem-report
3
+ description: Tell the team when the person you are talking to has a problem with YOU or your tools — "I have a problem", "it is not working", "I did not get the article", "you did not answer", an error, a missing or wrong output; Hebrew "יש לי בעיה", "לא עובד", "תקלה", "לא קיבלתי", "לא ענית". Files a problem report with mrctl problem report; the team gets a card and the person gets a P- number. Not for a problem in the person's own business or topic (their invoice, their client, their code) — that is a normal question.
4
+ ---
5
+
6
+ ## Command
7
+
8
+ ```bash
9
+ mrctl problem report "<what is not working, in one or two sentences>"
10
+ ```
11
+
12
+ It prints JSON: `{"ref": "P-12", "merged": false, "cardStatus": "sent"}`.
13
+
14
+ The host takes who is reporting, the space and the conversation from your
15
+ run. You send only the summary. Never put a person's name, phone number or
16
+ any key or password in it.
17
+
18
+ ## The routing test
19
+
20
+ File a report only when **both** are true:
21
+
22
+ 1. The person says something does not work, or did not arrive, or is wrong.
23
+ 2. The thing is **you or a tool, engine or task you run** — not their own
24
+ business, their client, their device or their topic.
25
+
26
+ If you are not sure, ask one short question first ("Is this about something
27
+ I did, or should not have done?"). Do not file "just in case".
28
+
29
+ ## What the summary says
30
+
31
+ - What the person expected, and what happened instead.
32
+ - Which tool, engine, task or output it is about, when you know.
33
+ - The error text you saw, if any (short).
34
+
35
+ Write it for the team, in plain words. One report covers the problem —
36
+ the host merges any later report from the same person in the next 10
37
+ minutes into the same `P-` number.
38
+
39
+ ## What you tell the person — branch on `cardStatus`
40
+
41
+ | `cardStatus` | What you say |
42
+ |--------------|--------------|
43
+ | `sent` / `partial` | The team has it, with the `ref` ("I told the team — reference P-12."). |
44
+ | `null` (with `merged: true`) | The team already has this report, with the `ref`. |
45
+ | `unconfirmed` / `failed` / `no-recipient` | You filed it with the `ref`, but you could not confirm the team got it. Never say it was sent. |
46
+
47
+ A refusal or error from `mrctl problem report` (`403`, `400`, `500`, `503`):
48
+ do not retry. Tell the person you could not file it, and that they can type
49
+ `/problem` (or `/בעיה`) followed by what is wrong — that reaches the team
50
+ even when you are busy or not answering.
51
+
52
+ Then continue to help with the problem if you can. Filing the report is
53
+ not a reply to the person by itself.
@@ -70,5 +70,16 @@ the like — so nothing reaches the chat. Attachments still send.
70
70
  Write the prompt to end such a run with the single word `NO_UPDATE`. That is a
71
71
  positive instruction that models follow reliably; "write nothing" is not.
72
72
 
73
+ `NO_UPDATE` means "I checked and found nothing new". It never means "I could
74
+ not check". When the source is blocked, a login wall, a captcha or an empty
75
+ page, the run ends with `BLOCKED: <reason>` instead (for example
76
+ `BLOCKED: Facebook showed a login page`), and that line is the whole reply.
77
+ It is not sent either, but Mercury records the run as blocked, and after several blocked runs in a row it
78
+ tells the space once. Write the prompt that way, and never tell the person
79
+ "if the site blocks me, I won't send anything": say that they will hear about
80
+ it if the site keeps blocking the check. A run that watches several sources
81
+ and found news on one while another was blocked is a report: send the news and
82
+ say in a sentence which source could not be checked, without the sentinel.
83
+
73
84
  The same rule means a task whose *intended* output is a bare `OK` (a heartbeat)
74
85
  will not post. Give it a sentence instead.
@@ -196,6 +196,7 @@ export function outcomeMix(
196
196
  day: string;
197
197
  posted: number;
198
198
  noUpdate: number;
199
+ blocked: number;
199
200
  error: number;
200
201
  interrupted: number;
201
202
  other: number;
@@ -209,6 +210,7 @@ export function outcomeMix(
209
210
  day,
210
211
  posted: count("posted"),
211
212
  noUpdate: count("no_update"),
213
+ blocked: count("blocked"),
212
214
  error: count("error"),
213
215
  interrupted: rows.filter((r) => r.status === "interrupted").length,
214
216
  other: rows.filter(
@@ -216,6 +218,7 @@ export function outcomeMix(
216
218
  r.status !== "interrupted" &&
217
219
  r.outcome !== "posted" &&
218
220
  r.outcome !== "no_update" &&
221
+ r.outcome !== "blocked" &&
219
222
  r.outcome !== "error",
220
223
  ).length,
221
224
  usd: rows.reduce((sum, r) => sum + (r.cost ?? 0), 0),
@@ -3411,7 +3411,14 @@ spacesCommand
3411
3411
  function deleteSpaceFromCli(id: string): void {
3412
3412
  const spacesDir = join(CWD, getProjectDataDir(CWD), "spaces");
3413
3413
  const result = withProjectDb((db) =>
3414
- deleteSpaceEverywhere(db, spacesDir, id),
3414
+ // The CLI loads no extensions, so nothing can hear `space_deleted`.
3415
+ deleteSpaceEverywhere(
3416
+ db,
3417
+ spacesDir,
3418
+ id,
3419
+ { source: "cli", callerId: null },
3420
+ null,
3421
+ ),
3415
3422
  );
3416
3423
  if (result.workspaceError) {
3417
3424
  console.warn(
@@ -3421,6 +3428,11 @@ function deleteSpaceFromCli(id: string): void {
3421
3428
  console.log(
3422
3429
  `Deleted space '${id}' — removed ${result.removed.messages} messages, ${result.removed.tasks} tasks, ${result.removed.conversations} conversations`,
3423
3430
  );
3431
+ if (result.deleted && !result.extensionsNotified) {
3432
+ console.warn(
3433
+ `Note: extensions were not notified (the CLI loads none). Anything an extension created for '${id}' outside its rows and folder — a per-space backup timer, a remote backup copy — is still there. Deleting from chat or the console notifies them.`,
3434
+ );
3435
+ }
3424
3436
  }
3425
3437
 
3426
3438
  // ─── Backup & restore ───────────────────────────────────────────────────
@@ -3552,7 +3564,7 @@ program
3552
3564
  "Show failed web-search provider calls, newest first (read-only)",
3553
3565
  )
3554
3566
  .option("--space <id>", "Only this space")
3555
- .option("--source <provider>", "Only this provider (brave, tavily)")
3567
+ .option("--source <provider>", "Only this provider (brave, tavily, linkup)")
3556
3568
  .option("--since <when>", "7d, 12h, or a UTC date like 2026-10-01")
3557
3569
  .option("--limit <n>", `Rows to show (default ${DEFAULT_WEB_FAILURES_LIMIT})`)
3558
3570
  .option("--json", "Full rows as JSON")