mercury-agent 0.24.3-beta.6 → 0.24.3-beta.7

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 CHANGED
@@ -7,7 +7,7 @@
7
7
  </p>
8
8
 
9
9
  <p align="center">
10
- <a href="https://github.com/Avishai-Tsabari/mercury"><img alt="GitHub" src="https://img.shields.io/badge/github-mercury-181717?style=flat-square&logo=github" /></a>
10
+ <a href="https://github.com/tagula-ai/mercury"><img alt="GitHub" src="https://img.shields.io/badge/github-mercury-181717?style=flat-square&logo=github" /></a>
11
11
  <a href="https://www.npmjs.com/package/mercury-agent"><img alt="npm" src="https://img.shields.io/npm/v/mercury-agent?style=flat-square&logo=npm" /></a>
12
12
  </p>
13
13
 
@@ -148,7 +148,7 @@ RUN bun run /app/src/agent/image-manifest.ts \
148
148
  # image, which inherits labels from this base with no builder change.
149
149
  LABEL org.opencontainers.image.version="${MERCURY_VERSION}" \
150
150
  org.opencontainers.image.title="mercury-agent" \
151
- org.opencontainers.image.source="https://github.com/Avishai-Tsabari/mercury" \
151
+ org.opencontainers.image.source="https://github.com/tagula-ai/mercury" \
152
152
  com.mercury.version="${MERCURY_VERSION}" \
153
153
  com.mercury.image-manifest="/app/image-manifest.json"
154
154
 
package/docs/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Mercury — docs
2
2
 
3
3
  Product docs, planning docs, ops runbooks and workflow scaffolding for
4
- [mercury](https://github.com/Avishai-Tsabari/mercury). All of it lives in this
4
+ [mercury](https://github.com/tagula-ai/mercury). All of it lives in this
5
5
  repository, tracked normally.
6
6
 
7
7
  ## Layout
@@ -372,6 +372,28 @@ shared folder) — SQLite WAL locking is unreliable there.
372
372
  The database itself refuses to open when `quick_check` fails — loudly, with a
373
373
  typed error, never auto-repaired. The fix is `mercury restore`.
374
374
 
375
+ ## Web-access failure log
376
+
377
+ Failed web-search provider calls are kept in `state.db`
378
+ (`web_access_failures`; read with `mercury web-failures`, see
379
+ [web search](./web-search.md#failure-log)). Retention is 90 days, export
380
+ first: on the first storage sweep of each UTC month, rows older than 90 days
381
+ are written to `<dataDir>/exports/web-access-failures/<YYYY-MM>.jsonl` (one
382
+ JSON object per row, every column), the file is fsynced and renamed into
383
+ place, and only then are exactly those rows deleted. One operator notice says
384
+ how many moved (same recipients and `alerts.enabled` switch as every operator
385
+ alert); zero rows writes no file and sends nothing.
386
+
387
+ A failed write deletes nothing and is retried on every sweep, with one alert a
388
+ month. A failed delete leaves the file standing and the rows in place; they
389
+ are exported again the next month (a duplicate carries the same `id`). The
390
+ month markers are `project_config` keys
391
+ `web_access_failures.last_export_month` and
392
+ `web_access_failures.last_export_failure_month`.
393
+
394
+ `<dataDir>/exports/` is not part of the state.db snapshots: copy it into
395
+ whatever backs up the box.
396
+
375
397
  ## One process per data dir (`mercury.instance.lock`)
376
398
 
377
399
  A Mercury process takes an exclusive lock on **`<dataDir>/mercury.instance.lock`**
@@ -76,6 +76,20 @@ cd ~/whatsapp-bot
76
76
 
77
77
  `run` refuses outside a gap (a mercury container or a `bin/pi` process running, or a probe that cannot answer). It also skips any provider the eval would take to 80% of its @global budget, because a script cannot deliver the threshold alert. Output goes to `<dataDir>/evals/web-search/<time>/`: `results.json`, `metrics.json` (answered, latency, Hebrew share, dated share, expected hits, URL overlap), `summary.txt`, and a blind `grades.md`. You mark each query `A`, `B` or `tie` in `grades.md`, and `grade` un-blinds the marks per language and per action. A blank verdict counts as ungraded, never as a tie. A new provider joins the eval by being a row in `providers/index.ts`.
78
78
 
79
+ ## Failure log
80
+
81
+ Every provider call that fails (out of credit, key rejected, rate-limited, 5xx or network error, refused request, timeout) leaves one row in the host's `web_access_failures` table, written by the capability in code, never by the agent. A row records the time, the full space id, the action, the provider, the query, the failure kind, the HTTP status, the provider's reason, and the outcome: `recovered:<provider>` when a later provider answered, `gave_up` when none did. Query and reason are passed through `redactTokens` (secret-shaped params such as `api_key=` become `[REDACTED]`) and stripped of control and invisible characters; no header, body or key is kept. A provider skipped by its health row or spent budget, our own run and hourly caps, and a repeated query in the same run write nothing: none of them is a call.
82
+
83
+ ```bash
84
+ mercury web-failures # newest 50
85
+ mercury web-failures --space <id> --source tavily --since 7d
86
+ mercury web-failures --since 2026-10-01 --limit 200 --json
87
+ ```
88
+
89
+ The command opens `state.db` read-only. Rows older than 90 days are exported, then deleted, once a month (see [configuration](./configuration.md#web-access-failure-log)).
90
+
91
+ To seed a list of sites that blocked the bot before this log existed, `bun scripts/web-block-sweep.ts [--db <path>] [--since <YYYY-MM-DD>]` scans stored messages for block-page markers (`Just a moment`, `Access Denied`, 403, Cloudflare, captcha, נחסם, חסום) and prints `url, count, first seen, last seen`. It is read-only and writes nothing to the table. Page-reading failures join the log in phase 2, inside the fetch helper.
92
+
79
93
  ## Security & RBAC
80
94
 
81
95
  Extension CLIs are called directly in bash, with RBAC enforced by Mercury's in-container permission guard. If a caller lacks the `pinchtab` permission, execution is blocked.
@@ -6,7 +6,7 @@
6
6
  * a credential that works until someone revokes it. Now the host exchanges the
7
7
  * refresh token here and the container gets only the short-lived access token
8
8
  * (`GOOGLE_WORKSPACE_CLI_TOKEN`, which the gws CLI ranks above any credentials
9
- * file). Spec: docs/archive/2026-10-16-gws-per-space-credentials.md.
9
+ * file). Spec: docs/archive/extensions/2026-10-16-gws-per-space-credentials.md.
10
10
  *
11
11
  * Pure over its inputs: `fetchImpl`, the clock and the timeout are injected, so
12
12
  * tests run every branch without a network call.
@@ -19,6 +19,7 @@ import type {
19
19
  CapabilityRequest,
20
20
  CapabilityResult,
21
21
  ExtensionStore,
22
+ WebAccessFailureInput,
22
23
  } from "../../../src/extensions/types.js";
23
24
  import {
24
25
  type Attempt,
@@ -343,6 +344,11 @@ export interface SearchDeps {
343
344
  /** Whole-chain bound. */
344
345
  deadlineMs?: number;
345
346
  log?: ChainLog;
347
+ /**
348
+ * Writes one row to the host's web-access failure log
349
+ * (ctx.recordWebAccessFailure). Absent = nothing is logged (tests).
350
+ */
351
+ recordFailure?: (row: WebAccessFailureInput) => void;
346
352
  }
347
353
 
348
354
  /** The chain this host would run, in order: named in the order and holding a key. */
@@ -488,6 +494,7 @@ export async function handleSearchCapability(
488
494
  const pending = search(action, parsed.query, req, chainDeps, {
489
495
  run,
490
496
  rateRemaining: rate.remaining,
497
+ recordFailure: deps.recordFailure,
491
498
  });
492
499
  run.answers.set(qKey, pending);
493
500
  const result = await pending;
@@ -584,20 +591,87 @@ function refuse(
584
591
  }
585
592
  }
586
593
 
594
+ /**
595
+ * The provider was called: not skipped by its health row or our ledger
596
+ * budget, and not left out by the search's own deadline. Only a call is a
597
+ * failure worth a row in the web-access failure log; a skip is already
598
+ * visible in the ledger and the refusal journal line.
599
+ */
600
+ export function wasCalled(a: Attempt): boolean {
601
+ return a.skipped === undefined && a.notCalled !== true;
602
+ }
603
+
604
+ /**
605
+ * One row per provider call that failed in this search, written in code by
606
+ * the tool that failed. A failed write must not cost the search its answer:
607
+ * the host's method never throws, and this guards a caller-supplied one too.
608
+ */
609
+ export function logFailedCalls(
610
+ attempts: readonly Attempt[],
611
+ outcome: WebAccessFailureInput["outcome"],
612
+ search: { spaceId: string; action: SearchAction; q: string; ts: number },
613
+ recordFailure: SearchDeps["recordFailure"],
614
+ log: ChainLog | undefined,
615
+ ): void {
616
+ if (!recordFailure) return;
617
+ for (const a of attempts) {
618
+ if (!wasCalled(a)) continue;
619
+ try {
620
+ recordFailure({
621
+ spaceId: search.spaceId,
622
+ action: search.action,
623
+ source: a.provider.id,
624
+ query: search.q,
625
+ failureKind: a.timedOut ? "timeout" : a.kind,
626
+ statusCode: a.status,
627
+ detail: a.detail,
628
+ outcome,
629
+ ts: search.ts,
630
+ });
631
+ } catch (error) {
632
+ log?.warn("web-search: could not record a failed provider call", {
633
+ provider: a.provider.id,
634
+ error: error instanceof Error ? error.message : String(error),
635
+ });
636
+ }
637
+ }
638
+ }
639
+
587
640
  /** The search itself. Never throws: every failure is a result. */
588
641
  async function search(
589
642
  action: SearchAction,
590
643
  query: SearchQuery,
591
644
  req: Pick<CapabilityRequest, "spaceId" | "callerId">,
592
645
  deps: Parameters<typeof runChain>[2],
593
- ctx: { run: RunState; rateRemaining: number },
646
+ ctx: {
647
+ run: RunState;
648
+ rateRemaining: number;
649
+ recordFailure: SearchDeps["recordFailure"];
650
+ },
594
651
  ): Promise<CapabilityResult> {
595
652
  const outcome = await runChain(action, query, deps, {
596
653
  spaceId: req.spaceId,
597
654
  });
598
655
  const nowMs = (deps.now ?? Date.now)();
599
- if (!outcome.ok) return refuse(outcome.attempts, ctx.run, deps, nowMs);
656
+ const logged = { spaceId: req.spaceId, action, q: query.q, ts: nowMs };
657
+ if (!outcome.ok) {
658
+ logFailedCalls(
659
+ outcome.attempts,
660
+ "gave_up",
661
+ logged,
662
+ ctx.recordFailure,
663
+ deps.log,
664
+ );
665
+ return refuse(outcome.attempts, ctx.run, deps, nowMs);
666
+ }
600
667
  const { provider, results, quota } = outcome;
668
+ logFailedCalls(
669
+ outcome.failed,
670
+ { recoveredVia: provider.id },
671
+ logged,
672
+ ctx.recordFailure,
673
+ deps.log,
674
+ );
601
675
  // The provider's own figure, when its headers carry one. Logged, not acted
602
676
  // on: the ledger is the brake, this is the cross-check against the account
603
677
  // total the ledger cannot see (another bot on the same key).
@@ -271,6 +271,11 @@ export interface Attempt {
271
271
  /** Not called: skipped by its health row, or by our ledger budget. */
272
272
  skipped?: "health" | "budget";
273
273
  timedOut?: boolean;
274
+ /**
275
+ * Not called: the search's own deadline left no time for it. Read like a
276
+ * timeout by the verdict, but it is our bound, not the provider's failure.
277
+ */
278
+ notCalled?: true;
274
279
  /** For `skipped: "budget"`: the budget that is spent. */
275
280
  budget?: number;
276
281
  }
@@ -283,6 +288,11 @@ export type ChainResult =
283
288
  monthUsed: number;
284
289
  monthBudget: number;
285
290
  quota: ProviderQuota | null;
291
+ /**
292
+ * Every attempt before the winner, skips included: the failures this
293
+ * search recovered from. The capability logs the ones that were calls.
294
+ */
295
+ failed: Attempt[];
286
296
  }
287
297
  | { ok: false; attempts: Attempt[] };
288
298
 
@@ -479,6 +489,7 @@ export async function runChain(
479
489
  status: null,
480
490
  detail: "no time left in the search's deadline",
481
491
  timedOut: true,
492
+ notCalled: true,
482
493
  });
483
494
  continue;
484
495
  }
@@ -569,6 +580,7 @@ export async function runChain(
569
580
  monthUsed: ledger.used,
570
581
  monthBudget: cp.monthlyBudget,
571
582
  quota: raw.headers && p.quota ? p.quota(raw.headers) : null,
583
+ failed: attempts,
572
584
  };
573
585
  }
574
586
  deps.log?.warn(
@@ -242,6 +242,7 @@ export default function (mercury: MercuryExtensionAPI) {
242
242
  alertOperators: (text) =>
243
243
  ctx.alertOperators({ extension: "web-search", text }),
244
244
  log: ctx.log,
245
+ recordFailure: (row) => ctx.recordWebAccessFailure(row),
245
246
  });
246
247
  },
247
248
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mercury-agent",
3
- "version": "0.24.3-beta.6",
3
+ "version": "0.24.3-beta.7",
4
4
  "description": "Personal AI assistant for chat platforms (WhatsApp, Slack, Discord, Telegram)",
5
5
  "license": "MIT",
6
6
  "author": "Avishai Tsabari",
@@ -16,7 +16,7 @@
16
16
  ],
17
17
  "repository": {
18
18
  "type": "git",
19
- "url": "https://github.com/Avishai-Tsabari/mercury"
19
+ "url": "https://github.com/tagula-ai/mercury"
20
20
  },
21
21
  "type": "module",
22
22
  "exports": {
@@ -90,8 +90,8 @@
90
90
  "typecheck:examples": "bunx tsc --noEmit -p tsconfig.examples.json",
91
91
  "typecheck:resources": "bunx tsc --noEmit -p tsconfig.resources.json",
92
92
  "typecheck:tests": "bunx tsc --noEmit -p tsconfig.tests.json",
93
- "lint": "bunx biome check src/ tests/ scripts/check.ts scripts/space-profile.ts scripts/football-harness.ts scripts/football-audit.ts scripts/ops-preflight.ts scripts/archive-erase-space.ts scripts/check-image-sources.ts scripts/check-sync-calls.ts scripts/lib/ratchet.ts scripts/check-early-return-no-log.ts scripts/check-bare-delivery-await.ts scripts/check-absent-allows.ts scripts/check-unbounded-race.ts scripts/feed-watch-scorecard.ts scripts/web-search-provider-eval.ts scripts/lib/search-eval.ts examples/extensions/archive/ examples/extensions/feed-watch/ examples/extensions/gws/ examples/extensions/napkin/ examples/extensions/pinchtab/ examples/extensions/overview/ examples/extensions/longview/ examples/extensions/yahoo-mail/ examples/extensions/morning/ examples/extensions/office-365-mail/ examples/extensions/web-search/ resources/",
94
- "lint:fix": "bunx biome check --fix src/ tests/ scripts/check.ts scripts/space-profile.ts scripts/football-harness.ts scripts/football-audit.ts scripts/ops-preflight.ts scripts/archive-erase-space.ts scripts/check-image-sources.ts scripts/check-sync-calls.ts scripts/lib/ratchet.ts scripts/check-early-return-no-log.ts scripts/check-bare-delivery-await.ts scripts/check-absent-allows.ts scripts/check-unbounded-race.ts scripts/feed-watch-scorecard.ts scripts/web-search-provider-eval.ts scripts/lib/search-eval.ts examples/extensions/archive/ examples/extensions/feed-watch/ examples/extensions/gws/ examples/extensions/napkin/ examples/extensions/pinchtab/ examples/extensions/overview/ examples/extensions/longview/ examples/extensions/yahoo-mail/ examples/extensions/morning/ examples/extensions/office-365-mail/ examples/extensions/web-search/ resources/",
93
+ "lint": "bunx biome check src/ tests/ scripts/check.ts scripts/space-profile.ts scripts/football-harness.ts scripts/football-audit.ts scripts/ops-preflight.ts scripts/archive-erase-space.ts scripts/check-image-sources.ts scripts/check-sync-calls.ts scripts/lib/ratchet.ts scripts/check-early-return-no-log.ts scripts/check-bare-delivery-await.ts scripts/check-absent-allows.ts scripts/check-unbounded-race.ts scripts/feed-watch-scorecard.ts scripts/web-search-provider-eval.ts scripts/web-block-sweep.ts scripts/lib/search-eval.ts examples/extensions/archive/ examples/extensions/feed-watch/ examples/extensions/gws/ examples/extensions/napkin/ examples/extensions/pinchtab/ examples/extensions/overview/ examples/extensions/longview/ examples/extensions/yahoo-mail/ examples/extensions/morning/ examples/extensions/office-365-mail/ examples/extensions/web-search/ resources/",
94
+ "lint:fix": "bunx biome check --fix src/ tests/ scripts/check.ts scripts/space-profile.ts scripts/football-harness.ts scripts/football-audit.ts scripts/ops-preflight.ts scripts/archive-erase-space.ts scripts/check-image-sources.ts scripts/check-sync-calls.ts scripts/lib/ratchet.ts scripts/check-early-return-no-log.ts scripts/check-bare-delivery-await.ts scripts/check-absent-allows.ts scripts/check-unbounded-race.ts scripts/feed-watch-scorecard.ts scripts/web-search-provider-eval.ts scripts/web-block-sweep.ts scripts/lib/search-eval.ts examples/extensions/archive/ examples/extensions/feed-watch/ examples/extensions/gws/ examples/extensions/napkin/ examples/extensions/pinchtab/ examples/extensions/overview/ examples/extensions/longview/ examples/extensions/yahoo-mail/ examples/extensions/morning/ examples/extensions/office-365-mail/ examples/extensions/web-search/ resources/",
95
95
  "check:silent-catch": "bun run scripts/check-silent-catch.ts",
96
96
  "check:sync-calls": "bun run scripts/check-sync-calls.ts",
97
97
  "check:dep-floors": "bun run scripts/check-dep-floors.ts",
@@ -59,7 +59,7 @@
59
59
  # # auto_compact_threshold: 50
60
60
 
61
61
  # agent:
62
- # image: ghcr.io/avishai-tsabari/mercury-agent:latest
62
+ # image: ghcr.io/tagula-ai/mercury-agent:latest
63
63
  # container_timeout_ms: 300000
64
64
  # # Docker runtime for agent containers: runc (default) or runsc (gVisor).
65
65
  # # runsc skips bwrap entirely, so neither of the two relaxations below is
@@ -433,7 +433,7 @@ Prioritize practical outputs and explicit assumptions.`;
433
433
 
434
434
  const platformIntro = `Files received from users (images, documents, voice notes) are saved to the \`inbox/\` directory in the current workspace. To send files back with your reply, write them to the \`outbox/\` directory — any files created or modified there during this run will be automatically attached to your response.
435
435
 
436
- You are ${botName}. You run on the Mercury platform (https://github.com/Avishai-Tsabari/mercury). When users ask about the platform — what it can do, how to configure it, scheduling, permissions, extensions, or anything about Mercury — you MUST read from \`/docs/mercury/\` before answering. Start with \`/docs/mercury/README.md\` for an overview, then check \`/docs/mercury/docs/\` for detailed guides.
436
+ You are ${botName}. You run on the Mercury platform (https://github.com/tagula-ai/mercury). When users ask about the platform — what it can do, how to configure it, scheduling, permissions, extensions, or anything about Mercury — you MUST read from \`/docs/mercury/\` before answering. Start with \`/docs/mercury/README.md\` for an overview, then check \`/docs/mercury/docs/\` for detailed guides.
437
437
 
438
438
  ## Permissions & Security
439
439
  Each run is triggered by a specific caller with a role (admin or member). The caller's identity and role are provided in the user prompt as a <caller /> tag.
@@ -168,6 +168,11 @@ import {
168
168
  runUpgrade,
169
169
  type UpgradeDeps,
170
170
  } from "./upgrade.js";
171
+ import {
172
+ DEFAULT_LIMIT as DEFAULT_WEB_FAILURES_LIMIT,
173
+ runWebFailures,
174
+ type WebFailuresOptions,
175
+ } from "./web-failures.js";
171
176
 
172
177
  // NOTE: `./whatsapp-auth.js` is imported lazily, inside `mercury auth whatsapp`.
173
178
  // It pulls in baileys, which reaches `sharp` — and importing sharp maps
@@ -3469,6 +3474,23 @@ program
3469
3474
  console.log(" 4. mercury service install");
3470
3475
  });
3471
3476
 
3477
+ program
3478
+ .command("web-failures")
3479
+ .description(
3480
+ "Show failed web-search provider calls, newest first (read-only)",
3481
+ )
3482
+ .option("--space <id>", "Only this space")
3483
+ .option("--source <provider>", "Only this provider (brave, tavily)")
3484
+ .option("--since <when>", "7d, 12h, or a UTC date like 2026-10-01")
3485
+ .option("--limit <n>", `Rows to show (default ${DEFAULT_WEB_FAILURES_LIMIT})`)
3486
+ .option("--json", "Full rows as JSON")
3487
+ .action((options: WebFailuresOptions) => {
3488
+ const result = runWebFailures(projectDbPath(), options, Date.now());
3489
+ for (const line of result.out) console.log(line);
3490
+ for (const line of result.err) console.error(line);
3491
+ if (result.code !== 0) process.exit(result.code);
3492
+ });
3493
+
3472
3494
  program
3473
3495
  .command("conversations")
3474
3496
  .alias("convos")
@@ -0,0 +1,163 @@
1
+ /**
2
+ * `mercury web-failures` — the operator's read of the web-access failure log
3
+ * (`web_access_failures`, written by core/web-access-failures.ts).
4
+ *
5
+ * Read-only at the driver, and hand-opened rather than through `Db`: `Db`
6
+ * migrates on open, and a read must never write the live database. A
7
+ * state.db from before the table existed reads as "no failures".
8
+ */
9
+
10
+ import { Database } from "bun:sqlite";
11
+ import { existsSync } from "node:fs";
12
+ import {
13
+ type WebAccessFailureRow,
14
+ webAccessFailureSelect,
15
+ } from "../storage/db.js";
16
+
17
+ export const DEFAULT_LIMIT = 50;
18
+ const QUERY_COLUMN_CHARS = 80;
19
+ const DAY_MS = 24 * 60 * 60 * 1000;
20
+
21
+ export interface WebFailuresOptions {
22
+ space?: string;
23
+ source?: string;
24
+ /** `7d`, `12h`, or a UTC date `2026-10-01`. */
25
+ since?: string;
26
+ limit?: string;
27
+ json?: boolean;
28
+ }
29
+
30
+ export interface WebFailuresResult {
31
+ code: 0 | 1;
32
+ out: string[];
33
+ err: string[];
34
+ }
35
+
36
+ /** `7d` / `12h` back from now, or a `YYYY-MM-DD` UTC date. Null = unreadable. */
37
+ export function parseSince(raw: string, nowMs: number): number | null {
38
+ const v = raw.trim();
39
+ const rel = /^(\d+)([dh])$/.exec(v);
40
+ if (rel) {
41
+ const n = Number(rel[1]);
42
+ const unit = rel[2] === "d" ? DAY_MS : DAY_MS / 24;
43
+ return Number.isSafeInteger(n) ? nowMs - n * unit : null;
44
+ }
45
+ if (/^\d{4}-\d{2}-\d{2}$/.test(v)) {
46
+ const t = Date.parse(`${v}T00:00:00Z`);
47
+ return Number.isFinite(t) ? t : null;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ function cell(value: string | number | null): string {
53
+ return value === null ? "-" : String(value);
54
+ }
55
+
56
+ function truncate(s: string, max: number): string {
57
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
58
+ }
59
+
60
+ export function formatTable(rows: readonly WebAccessFailureRow[]): string[] {
61
+ const header = [
62
+ "time",
63
+ "space",
64
+ "source",
65
+ "kind",
66
+ "status",
67
+ "outcome",
68
+ "query",
69
+ ];
70
+ const body = rows.map((r) => [
71
+ new Date(r.ts).toISOString().slice(0, 19).replace("T", " "),
72
+ r.spaceId,
73
+ r.source,
74
+ r.failureKind,
75
+ cell(r.statusCode),
76
+ r.outcome,
77
+ truncate(r.query ?? "-", QUERY_COLUMN_CHARS),
78
+ ]);
79
+ const widths = header.map((h, i) =>
80
+ Math.max(h.length, ...body.map((row) => row[i]?.length ?? 0)),
81
+ );
82
+ const line = (cols: string[]) =>
83
+ cols
84
+ .map((c, i) => (i === cols.length - 1 ? c : c.padEnd(widths[i] ?? 0)))
85
+ .join(" ");
86
+ return [line(header), ...body.map(line)];
87
+ }
88
+
89
+ export function runWebFailures(
90
+ dbPath: string,
91
+ opts: WebFailuresOptions,
92
+ nowMs: number,
93
+ ): WebFailuresResult {
94
+ let sinceMs: number | undefined;
95
+ if (opts.since !== undefined) {
96
+ const parsed = parseSince(opts.since, nowMs);
97
+ if (parsed === null) {
98
+ return {
99
+ code: 1,
100
+ out: [],
101
+ err: [
102
+ `Error: --since must be like 7d, 12h or 2026-10-01 (got "${opts.since}")`,
103
+ ],
104
+ };
105
+ }
106
+ sinceMs = parsed;
107
+ }
108
+ let limit = DEFAULT_LIMIT;
109
+ if (opts.limit !== undefined) {
110
+ const n = Number(opts.limit);
111
+ if (!/^\d+$/.test(opts.limit) || !Number.isSafeInteger(n) || n < 1) {
112
+ return {
113
+ code: 1,
114
+ out: [],
115
+ err: [
116
+ `Error: --limit must be a positive integer (got "${opts.limit}")`,
117
+ ],
118
+ };
119
+ }
120
+ limit = n;
121
+ }
122
+
123
+ if (!existsSync(dbPath)) {
124
+ return { code: 1, out: [], err: [`Error: no database at ${dbPath}`] };
125
+ }
126
+
127
+ const select = webAccessFailureSelect({
128
+ spaceId: opts.space,
129
+ source: opts.source,
130
+ sinceMs,
131
+ limit,
132
+ });
133
+
134
+ let db: Database | null = null;
135
+ let rows: WebAccessFailureRow[];
136
+ try {
137
+ db = new Database(dbPath, { readonly: true });
138
+ const hasTable = db
139
+ .query(
140
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'web_access_failures'",
141
+ )
142
+ .get();
143
+ // A database from before this table existed has recorded nothing.
144
+ rows = hasTable
145
+ ? (db.query(select.sql).all(...select.args) as WebAccessFailureRow[])
146
+ : [];
147
+ } catch (err) {
148
+ return {
149
+ code: 1,
150
+ out: [],
151
+ err: [
152
+ `Error: could not read ${dbPath} (${err instanceof Error ? err.message : String(err)})`,
153
+ ],
154
+ };
155
+ } finally {
156
+ db?.close();
157
+ }
158
+
159
+ if (opts.json)
160
+ return { code: 0, out: [JSON.stringify(rows, null, 2)], err: [] };
161
+ if (rows.length === 0) return { code: 0, out: ["no failures"], err: [] };
162
+ return { code: 0, out: formatTable(rows), err: [] };
163
+ }
@@ -8,6 +8,13 @@ import {
8
8
  maybeRunScheduledBackup,
9
9
  } from "../storage/backup.js";
10
10
  import type { Db } from "../storage/db.js";
11
+ import { emitExtensionNotice } from "./operator-alerts.js";
12
+ import {
13
+ EXPORT_SUBDIR,
14
+ type ExportOutcome,
15
+ NOTICE_EXTENSION,
16
+ runWebAccessFailureExport,
17
+ } from "./web-access-failures.js";
11
18
 
12
19
  interface CleanupOpts {
13
20
  config: AppConfig;
@@ -27,6 +34,8 @@ interface CleanupResult {
27
34
  /** Path of the state.db snapshot this pass created, if one was due. */
28
35
  backupCreated: string | null;
29
36
  backupsPruned: number;
37
+ /** The monthly web-access failure export; null when the step did not run. */
38
+ webAccessExport: ExportOutcome | null;
30
39
  }
31
40
 
32
41
  /**
@@ -52,6 +61,7 @@ export async function runStorageCleanup(
52
61
  traceFilesDeleted: 0,
53
62
  backupCreated: null,
54
63
  backupsPruned: 0,
64
+ webAccessExport: null,
55
65
  };
56
66
 
57
67
  // Ambient retention is database-wide and must not depend on the spaces
@@ -160,6 +170,29 @@ export async function runStorageCleanup(
160
170
  }
161
171
  }
162
172
 
173
+ // Web-access failures older than 90 days: exported to a file, then deleted,
174
+ // once a month. Same dataDir guard as the steps above, and above the
175
+ // spaces-directory read for the same reason. The step owns its own failure
176
+ // reporting (log + one alert a month); this catch is for what it did not
177
+ // foresee, so the sweep goes on.
178
+ if (typeof config.dataDir === "string" && config.dataDir.length > 0) {
179
+ try {
180
+ result.webAccessExport = await runWebAccessFailureExport({
181
+ db,
182
+ exportDir: path.join(resolveProjectPath(config.dataDir), EXPORT_SUBDIR),
183
+ now,
184
+ notify: (text) =>
185
+ emitExtensionNotice({ extension: NOTICE_EXTENSION, text }),
186
+ log,
187
+ });
188
+ } catch (err) {
189
+ log.error(
190
+ "Web-access failure export failed",
191
+ err instanceof Error ? err : undefined,
192
+ );
193
+ }
194
+ }
195
+
163
196
  let spaceDirs: string[];
164
197
  try {
165
198
  spaceDirs = fs
@@ -0,0 +1,351 @@
1
+ /**
2
+ * The web-access failure log: one row per failed web attempt, written by the
3
+ * tool that failed, in code — never by the agent's judgement. Phase 1 is the
4
+ * web-search provider chain (examples/extensions/web-search); page reading
5
+ * joins in phase 2, inside the fetch helper.
6
+ *
7
+ * Two halves, both pure over their inputs (db, fs, clock, notice):
8
+ * - `recordWebAccessFailure`: shapes a row (redaction, caps, outcome) and
9
+ * writes it. Never throws: a failed write is logged and the search goes on.
10
+ * - `runWebAccessFailureExport`: the monthly step of the cleanup sweep. Rows
11
+ * older than 90 days go to a renamed, fsynced JSONL file first; only then
12
+ * are exactly those rows deleted.
13
+ */
14
+
15
+ import { copyFile, mkdir, open, rename, stat } from "node:fs/promises";
16
+ import path from "node:path";
17
+ import type { Logger } from "../logger.js";
18
+ import type { Db, WebAccessFailureRecord } from "../storage/db.js";
19
+ import { redactTokens } from "../storage/pi-auth.js";
20
+ import { stripInvisibleUnicode } from "../text/sanitize-text.js";
21
+
22
+ /** What a failure was. Phase 1 uses the provider kinds; the rest are phase 2's. */
23
+ export type FailureKindLogged =
24
+ | "credit"
25
+ | "auth"
26
+ | "rate"
27
+ | "upstream"
28
+ | "request"
29
+ | "timeout"
30
+ | "cloudflare_challenge"
31
+ | "login_redirect"
32
+ | "geo_block"
33
+ | "captcha";
34
+
35
+ export interface WebAccessFailureInput {
36
+ spaceId: string;
37
+ /** 'web' | 'news' now; 'fetch' | 'browser' | 'api' in phase 2. */
38
+ action: string;
39
+ /** Provider id now ('brave', 'tavily'); the fetch rung later. */
40
+ source: string;
41
+ url?: string;
42
+ query?: string;
43
+ failureKind: FailureKindLogged;
44
+ statusCode: number | null;
45
+ detail?: string;
46
+ outcome: { recoveredVia: string } | "gave_up";
47
+ /** When the attempt failed (epoch ms). Defaults to the write time. */
48
+ ts?: number;
49
+ }
50
+
51
+ /** The longest `detail` kept, after redaction. */
52
+ export const MAX_DETAIL_CHARS = 500;
53
+ /** A query is capped too: the capability bounds it at 400, a later caller may not. */
54
+ export const MAX_QUERY_CHARS = 1_000;
55
+ export const MAX_URL_CHARS = 2_000;
56
+
57
+ /** Rows older than this are exported, then deleted. */
58
+ export const RETENTION_DAYS = 90;
59
+ const RETENTION_MS = RETENTION_DAYS * 24 * 60 * 60 * 1000;
60
+ /** Rows per synchronous DB step, so a large first export never holds the host thread long. */
61
+ export const EXPORT_BATCH = 2_000;
62
+
63
+ export const LAST_EXPORT_MONTH_KEY = "web_access_failures.last_export_month";
64
+ export const LAST_EXPORT_FAILURE_MONTH_KEY =
65
+ "web_access_failures.last_export_failure_month";
66
+ /** The `extension` label the export notices carry. */
67
+ export const NOTICE_EXTENSION = "web-access-failures";
68
+ /** Under `<dataDir>`. */
69
+ export const EXPORT_SUBDIR = path.join("exports", "web-access-failures");
70
+
71
+ /**
72
+ * C0 and C1 controls. A query is agent-written text and the operator reads it
73
+ * in a terminal, so an escape sequence must not survive into the row. Tab, LF
74
+ * and CR become a space (they separate words); every other control is
75
+ * removed outright, so one planted inside a key name (`api<SOH>_key=`) leaves
76
+ * the name whole for the redactor instead of splitting it past it.
77
+ */
78
+ const LINE_CONTROLS = /[\t\n\r]+/g;
79
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the controls are what this strips
80
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g;
81
+
82
+ function clean(value: string | undefined, max: number): string | null {
83
+ if (value === undefined) return null;
84
+ // Normalise, then redact, then cut. Stripping first: an invisible or
85
+ // control character inside a key name (`api<ZWSP>_key=`) would otherwise
86
+ // dodge the redactor and be joined back into a live `api_key=` after it.
87
+ // Redaction before the cut, so a cut cannot leave half a secret behind.
88
+ const scrubbed = redactTokens(
89
+ stripInvisibleUnicode(value)
90
+ .replace(LINE_CONTROLS, " ")
91
+ .replace(CONTROL_CHARS, ""),
92
+ ).trim();
93
+ if (scrubbed === "") return null;
94
+ return scrubbed.length > max ? `${scrubbed.slice(0, max - 1)}…` : scrubbed;
95
+ }
96
+
97
+ /** The row as stored: redacted, control-stripped, capped, outcome encoded. */
98
+ export function shapeWebAccessFailure(
99
+ input: WebAccessFailureInput,
100
+ nowMs: number,
101
+ ): WebAccessFailureRecord {
102
+ return {
103
+ ts: input.ts ?? nowMs,
104
+ spaceId: input.spaceId,
105
+ action: input.action,
106
+ source: input.source,
107
+ url: clean(input.url, MAX_URL_CHARS),
108
+ query: clean(input.query, MAX_QUERY_CHARS),
109
+ failureKind: input.failureKind,
110
+ statusCode: input.statusCode,
111
+ detail: clean(input.detail, MAX_DETAIL_CHARS),
112
+ outcome:
113
+ input.outcome === "gave_up"
114
+ ? "gave_up"
115
+ : `recovered:${input.outcome.recoveredVia}`,
116
+ };
117
+ }
118
+
119
+ /** Write one row. Never throws: a failed write is logged, the caller goes on. */
120
+ export function recordWebAccessFailure(
121
+ db: Pick<Db, "insertWebAccessFailure">,
122
+ log: Pick<Logger, "warn">,
123
+ input: WebAccessFailureInput,
124
+ nowMs: number = Date.now(),
125
+ ): void {
126
+ try {
127
+ db.insertWebAccessFailure(shapeWebAccessFailure(input, nowMs));
128
+ } catch (error) {
129
+ log.warn("Could not record a web-access failure", {
130
+ spaceId: input.spaceId,
131
+ source: input.source,
132
+ failureKind: input.failureKind,
133
+ error: error instanceof Error ? error.message : String(error),
134
+ });
135
+ }
136
+ }
137
+
138
+ // ── monthly export and prune ────────────────────────────────────────────────
139
+
140
+ export interface ExportDeps {
141
+ db: Pick<
142
+ Db,
143
+ | "getProjectConfig"
144
+ | "setProjectConfig"
145
+ | "exportableWebAccessFailures"
146
+ | "deleteWebAccessFailuresUpTo"
147
+ >;
148
+ /** `<dataDir>/exports/web-access-failures`. */
149
+ exportDir: string;
150
+ now: number;
151
+ /** Tells the operators (`emitExtensionNotice`). */
152
+ notify: (text: string) => void;
153
+ log: Pick<Logger, "info" | "error">;
154
+ }
155
+
156
+ export type ExportOutcome =
157
+ | { status: "not-due" }
158
+ | { status: "exported"; rows: number; file: string | null }
159
+ | { status: "write-failed"; error: string }
160
+ | { status: "delete-failed"; rows: number; file: string; error: string };
161
+
162
+ /** `YYYY-MM`, UTC. */
163
+ export function exportMonth(nowMs: number): string {
164
+ return new Date(nowMs).toISOString().slice(0, 7);
165
+ }
166
+
167
+ function errText(error: unknown): string {
168
+ return error instanceof Error ? error.message : String(error);
169
+ }
170
+
171
+ /**
172
+ * Only ENOENT means absent. Any other stat error is thrown, so it takes the
173
+ * write-failed path: reading "unreadable" as "absent" would open the month's
174
+ * file fresh and rename it over rows that exist nowhere else.
175
+ */
176
+ async function exists(p: string): Promise<boolean> {
177
+ try {
178
+ await stat(p);
179
+ return true;
180
+ } catch (error) {
181
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
182
+ throw error;
183
+ }
184
+ }
185
+
186
+ /**
187
+ * fsync the directory, so the rename itself is durable before any row is
188
+ * deleted. Windows cannot open a directory for sync; there the rename is
189
+ * left to NTFS's own journal, and that is logged rather than failed.
190
+ */
191
+ async function syncDir(dir: string, log: ExportDeps["log"]): Promise<void> {
192
+ try {
193
+ const handle = await open(dir, "r");
194
+ try {
195
+ await handle.sync();
196
+ } finally {
197
+ await handle.close();
198
+ }
199
+ } catch (error) {
200
+ if (process.platform !== "win32") throw error;
201
+ log.info("Web-access failure export: directory fsync unsupported here", {
202
+ dir,
203
+ error: errText(error),
204
+ });
205
+ }
206
+ }
207
+
208
+ /** Let the host thread serve other work between two synchronous DB steps. */
209
+ function yieldTurn(): Promise<void> {
210
+ return new Promise((resolve) => setImmediate(resolve));
211
+ }
212
+
213
+ /**
214
+ * One alert per month for a failing export, claimed before it is sent. A db
215
+ * that cannot even record the claim is logged, not alerted on every sweep.
216
+ */
217
+ function alertFailureOnce(deps: ExportDeps, month: string, text: string): void {
218
+ try {
219
+ if (deps.db.getProjectConfig(LAST_EXPORT_FAILURE_MONTH_KEY) === month) {
220
+ return;
221
+ }
222
+ deps.db.setProjectConfig(
223
+ LAST_EXPORT_FAILURE_MONTH_KEY,
224
+ month,
225
+ "storage-cleanup",
226
+ );
227
+ } catch (error) {
228
+ deps.log.error("Web-access failure export: could not record its alert", {
229
+ error: errText(error),
230
+ });
231
+ return;
232
+ }
233
+ deps.notify(text);
234
+ }
235
+
236
+ /**
237
+ * The monthly step. Due on the first sweep of a UTC month whose marker is not
238
+ * that month — an absent marker is due. Nothing is deleted before the rows
239
+ * are in a renamed, fsynced file; a file already there for this month (a crash
240
+ * after the rename) is appended to, never overwritten.
241
+ */
242
+ export async function runWebAccessFailureExport(
243
+ deps: ExportDeps,
244
+ ): Promise<ExportOutcome> {
245
+ const { db, log } = deps;
246
+ const month = exportMonth(deps.now);
247
+ if (db.getProjectConfig(LAST_EXPORT_MONTH_KEY) === month) {
248
+ return { status: "not-due" };
249
+ }
250
+ const cutoff = deps.now - RETENTION_MS;
251
+ const file = path.join(deps.exportDir, `${month}.jsonl`);
252
+ const tmp = `${file}.tmp`;
253
+ const relFile = path.posix.join(
254
+ "exports",
255
+ "web-access-failures",
256
+ `${month}.jsonl`,
257
+ );
258
+
259
+ // 1–2: select in batches, write, fsync, rename. Any failure: nothing deleted,
260
+ // marker not set (retried next sweep), one alert a month.
261
+ /** The last id of each batch written: the delete ranges. */
262
+ const boundaries: number[] = [];
263
+ let rows = 0;
264
+ try {
265
+ let batch = db.exportableWebAccessFailures(cutoff, 0, EXPORT_BATCH);
266
+ if (batch.length === 0) {
267
+ db.setProjectConfig(LAST_EXPORT_MONTH_KEY, month, "storage-cleanup");
268
+ return { status: "exported", rows: 0, file: null };
269
+ }
270
+ await mkdir(deps.exportDir, { recursive: true });
271
+ const appending = await exists(file);
272
+ if (appending) await copyFile(file, tmp);
273
+ const handle = await open(tmp, appending ? "a" : "w");
274
+ try {
275
+ while (batch.length > 0) {
276
+ await handle.write(
277
+ `${batch.map((r) => JSON.stringify(r)).join("\n")}\n`,
278
+ );
279
+ rows += batch.length;
280
+ const lastId = batch[batch.length - 1]?.id ?? 0;
281
+ boundaries.push(lastId);
282
+ batch = db.exportableWebAccessFailures(cutoff, lastId, EXPORT_BATCH);
283
+ }
284
+ await handle.sync();
285
+ } finally {
286
+ await handle.close();
287
+ }
288
+ await rename(tmp, file);
289
+ await syncDir(deps.exportDir, log);
290
+ } catch (error) {
291
+ log.error("Web-access failure export failed; nothing deleted", {
292
+ file,
293
+ error: errText(error),
294
+ });
295
+ alertFailureOnce(
296
+ deps,
297
+ month,
298
+ `Web-access failure export to ${relFile} failed (${errText(error)}). No records were deleted; the table keeps growing until this is fixed. Retried on every cleanup sweep; this alert is sent once a month.`,
299
+ );
300
+ return { status: "write-failed", error: errText(error) };
301
+ }
302
+
303
+ // 3: delete exactly what was written, one batch range at a time. A failure
304
+ // leaves the file standing and the rest of the rows in place; the marker is
305
+ // set, so they are exported again next month (duplicates share `id`).
306
+ let deleted = 0;
307
+ let after = 0;
308
+ try {
309
+ for (const upTo of boundaries) {
310
+ deleted += db.deleteWebAccessFailuresUpTo(after, upTo, cutoff);
311
+ after = upTo;
312
+ await yieldTurn();
313
+ }
314
+ } catch (error) {
315
+ log.error("Web-access failure export: rows written but not deleted", {
316
+ file,
317
+ rows,
318
+ deleted,
319
+ error: errText(error),
320
+ });
321
+ try {
322
+ db.setProjectConfig(LAST_EXPORT_MONTH_KEY, month, "storage-cleanup");
323
+ } catch (markerError) {
324
+ log.error("Web-access failure export: could not set its marker", {
325
+ error: errText(markerError),
326
+ });
327
+ }
328
+ alertFailureOnce(
329
+ deps,
330
+ month,
331
+ `Web-access failure records older than ${RETENTION_DAYS} days were written to ${relFile}, but deleting them failed (${errText(error)}). They stay in the table and are exported again next month.`,
332
+ );
333
+ return { status: "delete-failed", rows, file, error: errText(error) };
334
+ }
335
+
336
+ // 4: marker, one notice. The rows are already moved, so a marker that
337
+ // cannot be written must not cost the operators the notice: it is logged,
338
+ // and the next sweep finds the month's file and appends to it.
339
+ try {
340
+ db.setProjectConfig(LAST_EXPORT_MONTH_KEY, month, "storage-cleanup");
341
+ } catch (error) {
342
+ log.error("Web-access failure export: could not set its marker", {
343
+ error: errText(error),
344
+ });
345
+ }
346
+ log.info("Web-access failures exported", { file, rows, deleted });
347
+ deps.notify(
348
+ `${rows} web-access failure records older than ${RETENTION_DAYS} days moved to ${relFile}.`,
349
+ );
350
+ return { status: "exported", rows, file };
351
+ }
@@ -6,6 +6,7 @@ import type { AppConfig } from "../config.js";
6
6
  import { DirectSendError } from "../core/direct-send.js";
7
7
  import { emitExtensionNotice } from "../core/operator-alerts.js";
8
8
  import { hasPermission, resolveRole } from "../core/permissions.js";
9
+ import { recordWebAccessFailure } from "../core/web-access-failures.js";
9
10
  import type { Logger } from "../logger.js";
10
11
  import type { Db } from "../storage/db.js";
11
12
  import {
@@ -88,6 +89,9 @@ export function createMercuryExtensionContext(opts: {
88
89
  alertOperators(alert: { extension: string; text: string }): void {
89
90
  emitExtensionNotice(alert);
90
91
  },
92
+ recordWebAccessFailure(row): void {
93
+ recordWebAccessFailure(db, log, row);
94
+ },
91
95
  getConfig(spaceId: string, key: string): string | null {
92
96
  return resolveExtensionConfig({
93
97
  db,
@@ -8,10 +8,16 @@
8
8
  import type { ContainerError } from "../agent/container-error.js";
9
9
  import type { ModelCapabilityKey } from "../agent/model-capabilities.js";
10
10
  import type { AppConfig } from "../config.js";
11
+ import type { WebAccessFailureInput } from "../core/web-access-failures.js";
11
12
  import type { Logger } from "../logger.js";
12
13
  import type { Db } from "../storage/db.js";
13
14
  import type { EgressFile, InputSource, MessageAttachment } from "../types.js";
14
15
 
16
+ export type {
17
+ FailureKindLogged,
18
+ WebAccessFailureInput,
19
+ } from "../core/web-access-failures.js";
20
+
15
21
  // ---------------------------------------------------------------------------
16
22
  // Extension context — passed to event handlers and job runners
17
23
  // ---------------------------------------------------------------------------
@@ -63,6 +69,13 @@ export interface MercuryExtensionContext {
63
69
  * cooldown, so the caller owns "once" (persist that it announced).
64
70
  */
65
71
  alertOperators(alert: { extension: string; text: string }): void;
72
+ /**
73
+ * Record one failed web attempt in the host's web-access failure log
74
+ * (`web_access_failures`, read by `mercury web-failures`). Written by the
75
+ * tool that failed, in code. The query and detail are redacted and capped
76
+ * by the host. Never throws; a failed write is logged.
77
+ */
78
+ recordWebAccessFailure(row: WebAccessFailureInput): void;
66
79
  }
67
80
 
68
81
  // ---------------------------------------------------------------------------
package/src/storage/db.ts CHANGED
@@ -226,6 +226,28 @@ export interface SpaceLinkAuditRow {
226
226
  createdAt: number;
227
227
  }
228
228
 
229
+ /**
230
+ * One row of `web_access_failures`, already shaped (redacted, capped,
231
+ * outcome encoded) by `core/web-access-failures.ts`.
232
+ */
233
+ export interface WebAccessFailureRecord {
234
+ ts: number;
235
+ spaceId: string;
236
+ action: string;
237
+ source: string;
238
+ url: string | null;
239
+ query: string | null;
240
+ failureKind: string;
241
+ statusCode: number | null;
242
+ detail: string | null;
243
+ /** `recovered:<source>` or `gave_up`. */
244
+ outcome: string;
245
+ }
246
+
247
+ export interface WebAccessFailureRow extends WebAccessFailureRecord {
248
+ id: number;
249
+ }
250
+
229
251
  /** One edge to create (`createSpaceLink` / `createSpaceLinks`). */
230
252
  export interface SpaceLinkInput {
231
253
  holderSpaceId: string;
@@ -462,6 +484,51 @@ const INPUT_SOURCES: ReadonlySet<string> = new Set<InputSource>([
462
484
 
463
485
  export const SPACE_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
464
486
 
487
+ /**
488
+ * `web_access_failures` as `WebAccessFailureRow`. Exported so the operator
489
+ * CLI's read-only handle selects the same shape.
490
+ */
491
+ export const WEB_ACCESS_FAILURE_COLUMNS = `id, ts, space_id AS spaceId, action, source, url, query,
492
+ failure_kind AS failureKind, status_code AS statusCode, detail, outcome`;
493
+
494
+ export interface WebAccessFailureFilter {
495
+ spaceId?: string;
496
+ source?: string;
497
+ sinceMs?: number;
498
+ limit: number;
499
+ }
500
+
501
+ /**
502
+ * The one statement of "recent failures, filtered, newest first". `Db` and
503
+ * the operator CLI's read-only handle both run it.
504
+ */
505
+ export function webAccessFailureSelect(filter: WebAccessFailureFilter): {
506
+ sql: string;
507
+ args: (string | number)[];
508
+ } {
509
+ const where: string[] = [];
510
+ const args: (string | number)[] = [];
511
+ if (filter.spaceId !== undefined) {
512
+ where.push("space_id = ?");
513
+ args.push(filter.spaceId);
514
+ }
515
+ if (filter.source !== undefined) {
516
+ where.push("source = ?");
517
+ args.push(filter.source);
518
+ }
519
+ if (filter.sinceMs !== undefined) {
520
+ where.push("ts >= ?");
521
+ args.push(filter.sinceMs);
522
+ }
523
+ args.push(filter.limit);
524
+ return {
525
+ sql: `SELECT ${WEB_ACCESS_FAILURE_COLUMNS} FROM web_access_failures
526
+ ${where.length > 0 ? `WHERE ${where.join(" AND ")}` : ""}
527
+ ORDER BY ts DESC, id DESC LIMIT ?`,
528
+ args,
529
+ };
530
+ }
531
+
465
532
  export class Db {
466
533
  private readonly db: Database;
467
534
 
@@ -814,6 +881,32 @@ export class Db {
814
881
 
815
882
  CREATE INDEX IF NOT EXISTS idx_space_link_audit_holder
816
883
  ON space_link_audit(holder_space_id, id);
884
+
885
+ -- One row per failed web attempt, written by the tool that failed
886
+ -- (core/web-access-failures.ts), never by the agent. Host bookkeeping:
887
+ -- read by the operator CLI only, never part of a prompt. query and
888
+ -- detail are stored after redactTokens; outcome is 'recovered:<source>'
889
+ -- or 'gave_up'. Rows older than 90 days are exported, then deleted, by
890
+ -- the cleanup sweep.
891
+ CREATE TABLE IF NOT EXISTS web_access_failures (
892
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
893
+ ts INTEGER NOT NULL,
894
+ space_id TEXT NOT NULL,
895
+ action TEXT NOT NULL,
896
+ source TEXT NOT NULL,
897
+ url TEXT,
898
+ query TEXT,
899
+ failure_kind TEXT NOT NULL,
900
+ status_code INTEGER,
901
+ detail TEXT,
902
+ outcome TEXT NOT NULL
903
+ );
904
+
905
+ CREATE INDEX IF NOT EXISTS idx_web_access_failures_ts
906
+ ON web_access_failures(ts);
907
+
908
+ CREATE INDEX IF NOT EXISTS idx_web_access_failures_space_ts
909
+ ON web_access_failures(space_id, ts);
817
910
  `);
818
911
  this.ensureMessagesRunMetaColumn();
819
912
  this.ensureChatStateClearBoundaryColumn();
@@ -3639,6 +3732,72 @@ export class Db {
3639
3732
  return res.changes > 0;
3640
3733
  }
3641
3734
 
3735
+ // --- Web-access failures (host bookkeeping, operator-read only) ---
3736
+
3737
+ insertWebAccessFailure(row: WebAccessFailureRecord): number {
3738
+ const res = this.db
3739
+ .query(
3740
+ `INSERT INTO web_access_failures
3741
+ (ts, space_id, action, source, url, query, failure_kind, status_code, detail, outcome)
3742
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3743
+ )
3744
+ .run(
3745
+ row.ts,
3746
+ row.spaceId,
3747
+ row.action,
3748
+ row.source,
3749
+ row.url,
3750
+ row.query,
3751
+ row.failureKind,
3752
+ row.statusCode,
3753
+ row.detail,
3754
+ row.outcome,
3755
+ );
3756
+ return Number(res.lastInsertRowid);
3757
+ }
3758
+
3759
+ /**
3760
+ * Newest first, filtered (`webAccessFailureSelect`, which the operator
3761
+ * CLI's read-only handle runs too).
3762
+ */
3763
+ selectWebAccessFailures(
3764
+ filter: WebAccessFailureFilter,
3765
+ ): WebAccessFailureRow[] {
3766
+ const { sql, args } = webAccessFailureSelect(filter);
3767
+ return this.db.query(sql).all(...args) as WebAccessFailureRow[];
3768
+ }
3769
+
3770
+ /** One export batch: rows older than `cutoffMs` with `id > afterId`, by id. */
3771
+ exportableWebAccessFailures(
3772
+ cutoffMs: number,
3773
+ afterId: number,
3774
+ limit: number,
3775
+ ): WebAccessFailureRow[] {
3776
+ return this.db
3777
+ .query(
3778
+ `SELECT ${WEB_ACCESS_FAILURE_COLUMNS} FROM web_access_failures
3779
+ WHERE ts < ? AND id > ? ORDER BY id LIMIT ?`,
3780
+ )
3781
+ .all(cutoffMs, afterId, limit) as WebAccessFailureRow[];
3782
+ }
3783
+
3784
+ /**
3785
+ * Delete exactly the rows an export wrote: `afterId < id <= upToId` and
3786
+ * older than the same cutoff the export selected on. Returns rows deleted.
3787
+ */
3788
+ deleteWebAccessFailuresUpTo(
3789
+ afterId: number,
3790
+ upToId: number,
3791
+ cutoffMs: number,
3792
+ ): number {
3793
+ const res = this.db
3794
+ .query(
3795
+ "DELETE FROM web_access_failures WHERE id > ? AND id <= ? AND ts < ?",
3796
+ )
3797
+ .run(afterId, upToId, cutoffMs);
3798
+ return res.changes;
3799
+ }
3800
+
3642
3801
  // --- Space preferences (chat-managed) ---
3643
3802
 
3644
3803
  getSpacePreference(spaceId: string, key: string): string | null {
@@ -339,13 +339,15 @@ export const DETAIL_LIMIT = 400;
339
339
  * and the key may follow `=` so `body=refresh_token=…` — the first pair of an
340
340
  * echoed request, right after the framing — is caught too.
341
341
  * `grant_type=refresh_token` is not a secret and is left alone: the pattern
342
- * requires the *key* to end in `_token` / `_secret` / `password`.
342
+ * requires the *key* to end in `_token` / `_secret` / `password` / `api_key`
343
+ * (also `apikey`, `api-key`). The `api_key` leg is the web-access failure
344
+ * log's: a search query is agent-written text and may carry `api_key=…`.
343
345
  */
344
346
  export function redactTokens(text: string): string {
345
347
  return text
346
348
  .replace(/("(?:access|refresh)_token"\s*:\s*")[^"]*/g, "$1[REDACTED]")
347
349
  .replace(
348
- /((?:^|[&?;=\s"'])[A-Za-z0-9_.-]*(?:[_-]token|[_-]secret|password)=)[^&\s"';]*/gi,
350
+ /((?:^|[&?;=\s"'])[A-Za-z0-9_.-]*(?:[_-]token|[_-]secret|password|api[_-]?key)=)[^&\s"';]*/gi,
349
351
  "$1[REDACTED]",
350
352
  )
351
353
  .replace(/\bsk-ant-[A-Za-z0-9_-]+/g, "sk-ant-[REDACTED]");