ownledger 1.2.0 → 1.2.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.1 (2026-11-22)
4
+
5
+ - `best_card` is sturdier with many cards: at most 4 requests to OpenWallet at a time, one retry after a timeout or
6
+ a 429, and card lookups kept in the Worker's memory for an hour (never written anywhere).
7
+
3
8
  ## 1.2.0 (2026-11-22)
4
9
 
5
10
  - `cards` shows each card's current statement period: what was spent by category, refunds, and cashback credited
@@ -18,6 +18,7 @@ interface NotMatched {
18
18
  name: string;
19
19
  }[];
20
20
  }
21
+ export declare const clearSearchCache: () => void;
21
22
  export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet, input: BestCardInput): Promise<{
22
23
  purchase: {};
23
24
  what: string;
@@ -5,6 +5,10 @@ import { budgets, cards, fold } from "../engine/index.js";
5
5
  /** letters and digits only, no accents: "Demo Bank" and "demo-bank" are the same */
6
6
  const key = (s) => fold(s).replace(/[^a-z0-9]/g, "");
7
7
  const isDebit = (t) => (Array.isArray(t) ? t.includes("debit") && !t.includes("credit") : t === "debit");
8
+ /** search results kept in this Worker's memory for an hour (never written anywhere): fewer calls to OpenWallet */
9
+ const SEARCH_TTL_MS = 60 * 60 * 1000;
10
+ const searchCache = new Map();
11
+ export const clearSearchCache = () => searchCache.clear();
8
12
  async function findCard(ow, c) {
9
13
  const product = c.product ?? c.name;
10
14
  const miss = (why, candidates) => ({
@@ -14,7 +18,15 @@ async function findCard(ow, c) {
14
18
  why,
15
19
  ...(candidates?.length ? { candidates } : {}),
16
20
  });
17
- const search = async (q) => ((await ow.call("search_cards", { q, limit: 10 }))?.cards ?? []);
21
+ const search = async (q) => {
22
+ const k = `${ow.url}|${q}`;
23
+ const hit = searchCache.get(k);
24
+ if (hit && hit.until > Date.now())
25
+ return hit.cards;
26
+ const cards = ((await ow.call("search_cards", { q, limit: 10 }))?.cards ?? []);
27
+ searchCache.set(k, { cards, until: Date.now() + SEARCH_TTL_MS });
28
+ return cards;
29
+ };
18
30
  const sameBank = (xs) => {
19
31
  if (!c.bank)
20
32
  return xs;
@@ -7,5 +7,5 @@ export interface OpenWallet {
7
7
  }
8
8
  type Fetch = typeof fetch;
9
9
  /** A minimal MCP client over Streamable HTTP: initialize once, then tools/call. */
10
- export declare function openWalletClient(url: string, fetchImpl?: Fetch): OpenWallet;
10
+ export declare function openWalletClient(url: string, fetchImpl?: Fetch, retryDelayMs?: number): OpenWallet;
11
11
  export {};
@@ -3,7 +3,9 @@
3
3
  // names and banks (to find the cards), the purchase (amount, merchant or kind, date) and, per card, what was spent
4
4
  // and the cashback booked this statement period. Never account ids, notes, balances or anything else.
5
5
  export const OPENWALLET_DEFAULT_URL = "https://mcp.openwallet.vn/mcp";
6
- const TIMEOUT_MS = 10_000;
6
+ const TIMEOUT_MS = 15_000;
7
+ /** at most this many requests in flight to OpenWallet (it rate-limits per caller) */
8
+ const MAX_IN_FLIGHT = 4;
7
9
  export class OpenWalletError extends Error {
8
10
  }
9
11
  /** Reads a JSON-RPC response that came back as JSON or as server-sent events. */
@@ -28,25 +30,53 @@ async function rpcBody(res, id) {
28
30
  return text ? JSON.parse(text) : null;
29
31
  }
30
32
  /** A minimal MCP client over Streamable HTTP: initialize once, then tools/call. */
31
- export function openWalletClient(url, fetchImpl = fetch) {
33
+ export function openWalletClient(url, fetchImpl = fetch, retryDelayMs = 1500) {
32
34
  let session = null;
33
35
  let n = 0;
36
+ let inFlight = 0;
37
+ const queue = [];
38
+ const slot = async () => {
39
+ if (inFlight >= MAX_IN_FLIGHT)
40
+ await new Promise((r) => queue.push(r));
41
+ inFlight++;
42
+ };
43
+ const release = () => {
44
+ inFlight--;
45
+ queue.shift()?.();
46
+ };
34
47
  const post = async (body, sessionId, protocol) => {
35
48
  const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
36
49
  if (sessionId)
37
50
  headers["mcp-session-id"] = sessionId;
38
51
  if (protocol)
39
52
  headers["mcp-protocol-version"] = protocol;
40
- let res;
41
- try {
42
- res = await fetchImpl(url, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(TIMEOUT_MS) });
43
- }
44
- catch (e) {
45
- throw new OpenWalletError(`OpenWallet did not answer (${e.name === "TimeoutError" ? "timeout" : e.message})`);
53
+ // one retry after a timeout, a network error or a 429
54
+ for (let attempt = 0;; attempt++) {
55
+ await slot();
56
+ let res = null;
57
+ let failure = null;
58
+ try {
59
+ res = await fetchImpl(url, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(TIMEOUT_MS) });
60
+ }
61
+ catch (e) {
62
+ failure = `OpenWallet did not answer (${e.name === "TimeoutError" ? "timeout" : e.message})`;
63
+ }
64
+ finally {
65
+ release();
66
+ }
67
+ if (res && res.status === 429)
68
+ failure = "OpenWallet answered 429 (rate limited: try again in a minute)";
69
+ if (failure) {
70
+ if (attempt === 0) {
71
+ await new Promise((r) => setTimeout(r, retryDelayMs));
72
+ continue;
73
+ }
74
+ throw new OpenWalletError(failure);
75
+ }
76
+ if (!res.ok && res.status !== 202)
77
+ throw new OpenWalletError(`OpenWallet answered ${res.status}`);
78
+ return res;
46
79
  }
47
- if (!res.ok && res.status !== 202)
48
- throw new OpenWalletError(`OpenWallet answered ${res.status}${res.status === 429 ? " (rate limited: try again in a minute)" : ""}`);
49
- return res;
50
80
  };
51
81
  const init = async () => {
52
82
  const id = ++n;
@@ -1 +1 @@
1
- export declare const VERSION = "1.2.0";
1
+ export declare const VERSION = "1.2.1";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "1.2.0";
2
+ export const VERSION = "1.2.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Personal finance ledger used through AI chat (MCP). Your data in your own private GitHub repo, served by your own Cloudflare Worker.",
5
5
  "license": "MIT",
6
6
  "author": "phucbm",