ownledger 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -41,7 +41,7 @@ amounts, and never write without the owner's go. `npx ownledger check` must pass
41
41
 
42
42
  ## Account types
43
43
 
44
- `cash`, `bank`, `ewallet`, `credit_card` (details: `statement_day`, `due_day`, `limit`), `bnpl`, `deposit`
44
+ `cash`, `bank`, `ewallet`, `credit_card` (details: `statement_day`, `due_day`, `limit`, and optionally `bank` and `product`: the bank's own name for the card, e.g. "MSB Visa Online", used to look the card up in a card catalog such as OpenWallet), `bnpl`, `deposit`
45
45
  (details: `principal`, `rate` (annual %), `term_months`, `start`, `maturity`, `rollover`), `savings_goal` (`target`, `by`),
46
46
  `gold`, `fund`, `stock`, `etf`, `crypto`, `insurance`, `loan_given`, `loan_taken`, `other`.
47
47
  A type not on this list is still fine: it loads as a plain account with a warning. Extra keys are kept.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 (2026-11-22)
4
+
5
+ - `cards` shows each card's current statement period: what was spent by category, refunds, and cashback credited
6
+ (`period`), plus `bank` and `product` from the card's details. `all: true` lists every open card, also those
7
+ with nothing owed.
8
+ - New optional card detail `product`: the bank's own name for the card.
9
+ - Optional OpenWallet source (off by default; `ownledger deploy --openwallet`): `best_card` ranks your own cards
10
+ for one purchase (merchant or kind) by cashback, using each card's spend and cashback this statement period, with
11
+ available credit, due date and budget left. Cards are looked up by `details.product` and `details.bank` each time;
12
+ nothing from OpenWallet is stored. README "OpenWallet" lists exactly what is sent.
13
+ - Question evals (`evals/questions.md`): the owner's questions, the tool calls that answer them and the facts that
14
+ must come back, plus guards (no invented account, category, date or amount; writes only preview). Run in `pnpm test`.
15
+
3
16
  ## 1.1.0 (2026-11-22)
4
17
 
5
18
  - Transactions record where they came from: `trail` gets one entry per add/edit/void made through the MCP
package/README.md CHANGED
@@ -46,14 +46,15 @@ Ask in chat:
46
46
  - "How much did I spend on food this year vs last year?" → `report`
47
47
  - "Net worth over the last 12 months" → `net_worth`
48
48
  - "Move category cafe under drinks" → preview of the remap of every line → go
49
+ - "Quẹt thẻ nào khi đi siêu thị 1 triệu?" → `best_card` (only with the OpenWallet source on, see below)
49
50
 
50
- Tools: `about`, `rules`, `accounts`, `transactions`, `report`, `net_worth`, `cards`, `plans_due`, `deposits`, `today`; previews `add_transaction`, `edit_transaction`, `void_transaction`, `add_account`, `edit_account`, `add_plan`, `add_price`, `add_category`, `edit_category`; and `apply(preview_id)`, which commits a preview and is refused if the data changed since.
51
+ Tools: `about`, `rules`, `accounts`, `transactions`, `report`, `net_worth`, `cards`, `plans_due`, `deposits`, `today`; previews `add_transaction`, `edit_transaction`, `void_transaction`, `add_account`, `edit_account`, `add_plan`, `add_price`, `add_category`, `edit_category`; and `apply(preview_id)`, which commits a preview and is refused if the data changed since. With the OpenWallet source on: `best_card`.
51
52
 
52
53
  ## What talks to what
53
54
 
54
55
  | Part | Talks to | Never |
55
56
  |---|---|---|
56
- | Your Worker | GitHub's API only (your repo, with a 1-hour token scoped to that one repo) | any other server, analytics, telemetry |
57
+ | Your Worker | GitHub's API (your repo, with a 1-hour token scoped to that one repo); and only if you turn it on, OpenWallet (below) | any other server, analytics, telemetry |
57
58
  | Your AI client | your Worker's `/mcp` with a token your Worker issued (1 h, refreshable 30 days, revocable in the dashboard) | your GitHub credentials |
58
59
  | GitHub sign-in | proves who you are; your Worker reads your login, then revokes that GitHub token at once | kept anywhere |
59
60
  | The CLI | GitHub (`gh`), Cloudflare (`wrangler`), npm | sending your data anywhere |
@@ -76,14 +77,27 @@ AGENTS.md the rules any AI follows in this repo
76
77
 
77
78
  Plain text, diffable, yours. See [AGENTS.md](AGENTS.md) for the format.
78
79
 
80
+ ### OpenWallet (optional, off by default)
81
+
82
+ [OpenWallet](https://openwallet.vn) is a public catalog of bank cards in Vietnam (fees, cashback rules, caps). With it
83
+ on, `best_card` answers "which of my cards pays the most for this purchase", counting what each card already spent
84
+ and earned this statement period, next to your available credit, due date and budget.
85
+
86
+ - **Turn on:** `ownledger deploy --openwallet` (or `--openwallet=<url>`). **Off:** `ownledger deploy --no-openwallet`.
87
+ - **What is sent, only when you ask `best_card`:** each card's product name and bank (`details.product`, or the account
88
+ name, and `details.bank`), the purchase (amount, merchant or kind, date), and per card the spend and cashback booked
89
+ this statement period. Never account ids, notes, balances, limits or any other transaction.
90
+ - **Nothing is stored:** your data never holds OpenWallet ids or slugs; cards are looked up by name each time.
91
+ Set `details.product` to the bank's own name for the card (e.g. `MSB Visa Online`) so it is found.
92
+
79
93
  ## CLI
80
94
 
81
95
  ```
82
96
  ownledger init [name] create a data repo
83
97
  ownledger check [dir] check the data (CI runs it)
84
98
  ownledger import <file> import an export (--profile, --preset misa, --yes)
85
- ownledger deploy deploy or update your Worker
86
- ownledger dev [dir] run your Worker locally against the local folder (sign-in skipped)
99
+ ownledger deploy deploy or update your Worker (--openwallet / --no-openwallet)
100
+ ownledger dev [dir] run your Worker locally against the local folder (sign-in skipped; --openwallet[=<url>])
87
101
  ```
88
102
 
89
103
  ## Development
@@ -1 +1,3 @@
1
+ /** `--openwallet` (OpenWallet's public URL) or `--openwallet=<url>` turns the OpenWallet source on, `--no-openwallet` off; undefined = unchanged. */
2
+ export declare function openwalletFlag(args: string[]): string | null | undefined;
1
3
  export declare function cmdDeploy(args: string[]): Promise<number>;
@@ -5,10 +5,23 @@ import { createServer } from "node:http";
5
5
  import { join, resolve } from "node:path";
6
6
  import { parse as parseJsonc } from "./jsonc.js";
7
7
  import { appJwt } from "../worker/github.js";
8
+ import { OPENWALLET_DEFAULT_URL } from "../worker/openwallet.js";
8
9
  function opt(args, name) {
9
10
  const i = args.indexOf(name);
10
11
  return i >= 0 ? args[i + 1] : undefined;
11
12
  }
13
+ /** `--openwallet` (OpenWallet's public URL) or `--openwallet=<url>` turns the OpenWallet source on, `--no-openwallet` off; undefined = unchanged. */
14
+ export function openwalletFlag(args) {
15
+ if (args.includes("--no-openwallet"))
16
+ return null;
17
+ const a = args.find((x) => x === "--openwallet" || x.startsWith("--openwallet="));
18
+ if (!a)
19
+ return undefined;
20
+ const url = a.includes("=") ? a.slice(a.indexOf("=") + 1) : OPENWALLET_DEFAULT_URL;
21
+ if (!/^https?:\/\//.test(url))
22
+ throw new Error(`--openwallet needs an http(s) URL, got "${url}"`);
23
+ return url;
24
+ }
12
25
  function run(cmd, args, cwd, input) {
13
26
  const r = spawnSync(cmd, args, { cwd, input, encoding: "utf8", stdio: [input === undefined ? "inherit" : "pipe", "pipe", "pipe"], env: { ...process.env, FORCE_COLOR: "0" } });
14
27
  if (r.status !== 0)
@@ -226,6 +239,11 @@ export async function cmdDeploy(args) {
226
239
  cfg = { ...baseConfig(c, accountId, kv, publicUrl), ...(cfg.routes ? { routes: cfg.routes } : {}) };
227
240
  if (cfg.vars && readConfig(c).vars?.ALLOWED_LOGINS)
228
241
  cfg.vars.ALLOWED_LOGINS = readConfig(c).vars.ALLOWED_LOGINS;
242
+ const ow = openwalletFlag(args);
243
+ const owUrl = ow === undefined ? readConfig(c).vars?.OPENWALLET_URL : ow;
244
+ if (cfg.vars && owUrl)
245
+ cfg.vars.OPENWALLET_URL = owUrl;
246
+ say(owUrl ? `✓ OpenWallet source on (${owUrl}): best_card sends card product names and purchases there. --no-openwallet turns it off.` : " OpenWallet source off (--openwallet turns it on).");
229
247
  writeConfig(c, cfg);
230
248
  const have = secretNames(c);
231
249
  const needApp = args.includes("--new-app") || !["GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY", "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET"].every((n) => have.includes(n));
package/dist/cli/dev.js CHANGED
@@ -5,6 +5,7 @@ import { createServer } from "node:http";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { readDataDir } from "../node/files.js";
7
7
  import { pkgPath } from "../node/scaffold.js";
8
+ import { openwalletFlag } from "./deploy.js";
8
9
  function opt(args, name) {
9
10
  const i = args.indexOf(name);
10
11
  return i >= 0 ? args[i + 1] : undefined;
@@ -76,6 +77,7 @@ export async function cmdDev(args) {
76
77
  const port = Number(opt(args, "--port") ?? 8787);
77
78
  const dataPort = port + 3;
78
79
  const login = opt(args, "--login") ?? "dev";
80
+ const ow = openwalletFlag(args);
79
81
  startDataServer(root, dataPort);
80
82
  const cfgDir = join(root, ".wrangler");
81
83
  mkdirSync(cfgDir, { recursive: true });
@@ -99,9 +101,10 @@ export async function cmdDev(args) {
99
101
  GITHUB_CLIENT_ID: "dev",
100
102
  GITHUB_CLIENT_SECRET: "dev",
101
103
  COOKIE_SECRET: "dev-only-not-secret",
104
+ ...(ow ? { OPENWALLET_URL: ow } : {}),
102
105
  },
103
106
  }, null, 2));
104
- console.log(`ownledger dev: data ${root}\n MCP http://localhost:${port}/mcp (sign-in skipped: ${login})\n Dashboard http://localhost:${port}/\n Writes commit to the local folder${existsSync(join(root, ".git")) ? " (git)" : ""}.\n`);
107
+ console.log(`ownledger dev: data ${root}\n MCP http://localhost:${port}/mcp (sign-in skipped: ${login})\n Dashboard http://localhost:${port}/\n Writes commit to the local folder${existsSync(join(root, ".git")) ? " (git)" : ""}.\n${ow ? ` OpenWallet ${ow} (best_card on)\n` : ""}`);
105
108
  const child = spawn("npx", ["wrangler", "dev", "-c", cfg, "--port", String(port), "--persist-to", join(cfgDir, "state")], { cwd: root, stdio: "inherit" });
106
109
  return new Promise((r) => child.on("exit", (code) => r(code ?? 0)));
107
110
  }
package/dist/cli/index.js CHANGED
@@ -14,7 +14,8 @@ Usage: ownledger <command> [options]
14
14
  check [dir] Check the data repo (default: current folder)
15
15
  import <file> Import an export (profile first; preview; --yes writes, checks and commits)
16
16
  deploy Deploy your Worker to your Cloudflare (GitHub App, secrets, KV); prints the connector URL
17
- dev [dir] Run your Worker locally against the local data/ (fake sign-in)
17
+ --openwallet[=<url>] turns on the OpenWallet card catalog (best_card), --no-openwallet off
18
+ dev [dir] Run your Worker locally against the local data/ (fake sign-in); --openwallet[=<url>] as above
18
19
  --version Print the version
19
20
  `;
20
21
  const commands = {
@@ -11,6 +11,33 @@ export interface CardStatus {
11
11
  toPay: number | null;
12
12
  dueDate: ISODate | null;
13
13
  daysToDue: number | null;
14
+ /** details.bank and details.product as the owner wrote them (product: the card's real product name), or null */
15
+ bank: string | null;
16
+ product: string | null;
17
+ period: CardPeriod;
18
+ }
19
+ /**
20
+ * What happened on a card in the current statement period (day after the last statement → asOf), or in the
21
+ * calendar month when the card has no statement_day. Only transactions where the card is the only account count
22
+ * towards spending; transfers and card payments never do.
23
+ */
24
+ export interface CardPeriod {
25
+ from: ISODate;
26
+ to: ISODate;
27
+ basis: "statement" | "month";
28
+ /** expense lines paid with the card (before refunds) */
29
+ spent: number;
30
+ /** expense lines refunded to the card */
31
+ refunds: number;
32
+ /** spent - refunds, per expense category path, largest first */
33
+ byCategory: {
34
+ category: string;
35
+ amount: number;
36
+ }[];
37
+ /** income under the `cashback` category (and its children) credited to the card */
38
+ cashback: number;
39
+ /** transactions that touch the card together with other accounts and categories: not split, left out of the figures above */
40
+ mixed: number;
14
41
  }
15
42
  export declare function cards(l: Ledger, asOf: ISODate): CardStatus[];
16
43
  export interface PlanStatus {
@@ -6,8 +6,45 @@ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined)
6
6
  const day = (v) => (Number.isInteger(v) && v >= 1 && v <= 31 ? v : undefined);
7
7
  const date = (v) => (isDate(v) ? v : undefined);
8
8
  const open = (a, asOf) => !(isDate(a.closed) && a.closed <= asOf);
9
+ function cardPeriod(l, card, from, to, basis, kinds) {
10
+ let spent = 0;
11
+ let refunds = 0;
12
+ let cashback = 0;
13
+ let mixed = 0;
14
+ const by = new Map();
15
+ for (const t of l.transactions) {
16
+ if (t.void || t.date < from || t.date > to)
17
+ continue;
18
+ if (!t.lines.some((ln) => ln.account === card))
19
+ continue;
20
+ const cats = t.lines.filter((ln) => ln.category !== undefined);
21
+ if (!cats.length)
22
+ continue; // a transfer or card payment
23
+ if (t.lines.some((ln) => ln.account !== undefined && ln.account !== card)) {
24
+ mixed++;
25
+ continue;
26
+ }
27
+ for (const ln of cats) {
28
+ const c = ln.category;
29
+ if (kinds.get(c) === "expense") {
30
+ if (ln.amount > 0)
31
+ spent += ln.amount;
32
+ else
33
+ refunds -= ln.amount;
34
+ by.set(c, (by.get(c) ?? 0) + ln.amount);
35
+ }
36
+ else if (kinds.get(c) === "income" && (c === "cashback" || c.startsWith("cashback/"))) {
37
+ cashback -= ln.amount;
38
+ }
39
+ }
40
+ }
41
+ const byCategory = [...by].filter(([, a]) => a !== 0).map(([category, amount]) => ({ category, amount })).sort((a, b) => b.amount - a.amount);
42
+ return { from, to, basis, spent, refunds, byCategory, cashback, mixed };
43
+ }
9
44
  export function cards(l, asOf) {
10
45
  const now = holdingsAt(l, asOf);
46
+ const kinds = new Map([...flattenCategories(l.categories).map].map(([p, c]) => [p, c.kind]));
47
+ const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : null);
11
48
  const out = [];
12
49
  for (const a of l.accounts) {
13
50
  if (a.type !== "credit_card" || !open(a, asOf))
@@ -58,6 +95,11 @@ export function cards(l, asOf) {
58
95
  toPay,
59
96
  dueDate,
60
97
  daysToDue: dueDate ? daysBetween(asOf, dueDate) : null,
98
+ bank: str(d.bank),
99
+ product: str(d.product),
100
+ period: statementDate
101
+ ? cardPeriod(l, a.id, addDays(statementDate, 1), asOf, "statement", kinds)
102
+ : cardPeriod(l, a.id, monthStart(asOf), asOf, "month", kinds),
61
103
  });
62
104
  }
63
105
  return out;
@@ -0,0 +1,49 @@
1
+ import { type ISODate, type Ledger } from "../engine/index.js";
2
+ import type { OpenWallet } from "./openwallet.js";
3
+ export interface BestCardInput {
4
+ amount: number;
5
+ merchant?: string;
6
+ kind?: string;
7
+ date?: ISODate;
8
+ category?: string;
9
+ accounts?: string[];
10
+ }
11
+ interface NotMatched {
12
+ account: string;
13
+ name: string;
14
+ product: string | null;
15
+ why: string;
16
+ candidates?: {
17
+ id: string;
18
+ name: string;
19
+ }[];
20
+ }
21
+ export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet, input: BestCardInput): Promise<{
22
+ purchase: {};
23
+ what: string;
24
+ ranking: unknown[];
25
+ not_matched?: NotMatched[] | undefined;
26
+ budget?: {
27
+ category: string;
28
+ every: "month" | "year";
29
+ amount: number;
30
+ spent: number;
31
+ left: number;
32
+ none?: undefined;
33
+ } | {
34
+ every?: undefined;
35
+ amount?: undefined;
36
+ spent?: undefined;
37
+ left?: undefined;
38
+ category: string;
39
+ none: boolean;
40
+ } | undefined;
41
+ assumptions: string[];
42
+ source: {
43
+ name: string;
44
+ url: string;
45
+ catalog: unknown;
46
+ };
47
+ note: string;
48
+ }>;
49
+ export {};
@@ -0,0 +1,137 @@
1
+ // best_card: which of the owner's own cards pays the most cashback for one purchase, through OpenWallet (an outside
2
+ // source the owner turns on). The owner's data says nothing about OpenWallet: cards are looked up each time by the
3
+ // card's product name (details.product, or the account name) and bank. Nothing OpenWallet returns is stored.
4
+ import { budgets, cards, fold } from "../engine/index.js";
5
+ /** letters and digits only, no accents: "Demo Bank" and "demo-bank" are the same */
6
+ const key = (s) => fold(s).replace(/[^a-z0-9]/g, "");
7
+ const isDebit = (t) => (Array.isArray(t) ? t.includes("debit") && !t.includes("credit") : t === "debit");
8
+ async function findCard(ow, c) {
9
+ const product = c.product ?? c.name;
10
+ const miss = (why, candidates) => ({
11
+ account: c.account,
12
+ name: c.name,
13
+ product: c.product,
14
+ why,
15
+ ...(candidates?.length ? { candidates } : {}),
16
+ });
17
+ const search = async (q) => ((await ow.call("search_cards", { q, limit: 10 }))?.cards ?? []);
18
+ const sameBank = (xs) => {
19
+ if (!c.bank)
20
+ return xs;
21
+ const b = key(c.bank);
22
+ return xs.filter((x) => key(x.bank) === b || key(x.name).startsWith(b));
23
+ };
24
+ let list = sameBank((await search(product)).filter((x) => !isDebit(x.type)));
25
+ // not found (at that bank): try again with the bank's name in the query
26
+ if (!list.length && c.bank && !fold(product).includes(fold(c.bank)))
27
+ list = sameBank((await search(`${c.bank} ${product}`)).filter((x) => !isDebit(x.type)));
28
+ const exact = list.filter((x) => fold(x.name) === fold(product));
29
+ const pick = exact.length === 1 ? exact[0] : list.length === 1 ? list[0] : undefined;
30
+ if (pick)
31
+ return { card: c, ow: { id: pick.id, name: pick.name, url: pick.url, lastChecked: pick.lastChecked ?? null } };
32
+ if (!list.length)
33
+ return miss(`not found in OpenWallet by "${product}"${c.bank ? ` at ${c.bank}` : ""}${c.product ? "" : " (that is the account name: set details.product to the bank's name for the card)"}`);
34
+ return miss(`several OpenWallet cards match "${product}": set details.product to the exact name`, list.slice(0, 5).map((x) => ({ id: x.id, name: x.name })));
35
+ }
36
+ async function resolveWhat(ow, input) {
37
+ if (input.merchant) {
38
+ const r = await ow.call("find_merchants", { q: input.merchant, limit: 3 });
39
+ const m = r?.merchants?.[0];
40
+ if (!m)
41
+ throw new Error(`OpenWallet doesn't know the merchant "${input.merchant}". Give kind instead (e.g. groceries, dining, fuel).`);
42
+ return { merchant: m.slug, label: m.name };
43
+ }
44
+ const kinds = ((await ow.call("list_spending_categories", {}))?.categories ?? []);
45
+ const k = fold(input.kind.trim());
46
+ const hit = kinds.find((x) => fold(x.slug) === k || fold(x.label) === k) ?? kinds.find((x) => fold(x.label).includes(k) || fold(x.slug).includes(k));
47
+ if (!hit)
48
+ throw new Error(`OpenWallet has no spending kind "${input.kind}". Its kinds: ${kinds.map((x) => x.slug).join(", ")}`);
49
+ return { intent: hit.slug, label: hit.label };
50
+ }
51
+ function budgetFor(l, asOf, category) {
52
+ const all = budgets(l, asOf);
53
+ // the most specific budget that covers the category
54
+ const b = all.filter((x) => category === x.category || category.startsWith(x.category + "/")).sort((a, b) => b.category.length - a.category.length)[0];
55
+ return b ? { category: b.category, every: b.every, amount: b.amount, spent: b.spent, left: b.left } : { category, none: true };
56
+ }
57
+ export async function bestCard(l, asOf, ow, input) {
58
+ if (!input.merchant && !input.kind)
59
+ throw new Error("Say what is bought: merchant (e.g. Shopee, Co.opmart) or kind (e.g. groceries).");
60
+ const date = input.date ?? asOf;
61
+ let mine = cards(l, asOf);
62
+ if (input.accounts?.length) {
63
+ const unknown = input.accounts.filter((a) => !mine.some((c) => c.account === a));
64
+ if (unknown.length)
65
+ throw new Error(`not an open credit card: ${unknown.join(", ")}`);
66
+ mine = mine.filter((c) => input.accounts.includes(c.account));
67
+ }
68
+ if (!mine.length)
69
+ throw new Error("No open credit cards in the ledger.");
70
+ const [what, ...looked] = await Promise.all([resolveWhat(ow, input), ...mine.map((c) => findCard(ow, c))]);
71
+ const found = [];
72
+ const notMatched = [];
73
+ for (const r of looked) {
74
+ if ("ow" in r) {
75
+ const twin = found.find((f) => f.ow.id === r.ow.id);
76
+ if (twin)
77
+ notMatched.push({ account: r.card.account, name: r.card.name, product: r.card.product, why: `same OpenWallet card as ${twin.card.account}: ranked once` });
78
+ else
79
+ found.push(r);
80
+ }
81
+ else
82
+ notMatched.push(r);
83
+ }
84
+ const assumptions = [
85
+ "spend_so_far and cap_used come from the ledger: only what is recorded this statement period counts.",
86
+ "cap_used is the cashback booked to the card this period; banks often pay it after the statement closes, so the bank's figure can be higher.",
87
+ ];
88
+ let ranking = [];
89
+ let catalog = null;
90
+ let purchase = null;
91
+ if (found.length) {
92
+ const states = found.map((f) => ({ id: f.ow.id, spend_so_far: Math.max(0, f.card.period.spent - f.card.period.refunds), cap_used: Math.max(0, f.card.period.cashback) }));
93
+ const r = await ow.call("rank_cards_for_spend", {
94
+ purchase: { amount: input.amount, date, ...(what.merchant ? { merchant: what.merchant } : { intent: what.intent }) },
95
+ cards: states,
96
+ limit: 20,
97
+ });
98
+ purchase = r?.purchase ?? null;
99
+ catalog = r?.meta?.catalog ?? null;
100
+ assumptions.push(...(r?.assumptions ?? []));
101
+ ranking = (r?.cards ?? []).map((x) => {
102
+ const f = found.find((y) => y.ow.id === x.id);
103
+ const st = states.find((s) => s.id === x.id);
104
+ return {
105
+ rank: x.rank,
106
+ account: f.card.account,
107
+ name: f.card.name,
108
+ cashback: x.cashback,
109
+ effective_rate: x.effective_rate,
110
+ status: x.status,
111
+ reason: x.reason,
112
+ rule: x.rule ? { rate: x.rule.rate ?? null, cap: x.rule.cap ?? null, cap_remaining: x.rule.cap_remaining ?? null, ...(x.rule.intents ? { kinds: x.rule.intents } : {}) } : null,
113
+ global_cap_remaining: x.global_cap_remaining ?? null,
114
+ min_spend: x.min_spend ?? null,
115
+ spend_so_far: st.spend_so_far,
116
+ cap_used: st.cap_used,
117
+ available: f.card.available,
118
+ enough_credit: f.card.available === null ? null : f.card.available >= input.amount,
119
+ toPay: f.card.toPay,
120
+ dueDate: f.card.dueDate,
121
+ openwallet: { id: f.ow.id, name: f.ow.name, url: x.url ?? f.ow.url ?? null, lastChecked: x.lastChecked ?? f.ow.lastChecked ?? null },
122
+ };
123
+ });
124
+ }
125
+ return {
126
+ purchase: purchase ?? { amount: input.amount, date, merchant: what.merchant ?? null, intent: what.intent ?? null },
127
+ what: what.label,
128
+ ranking,
129
+ ...(notMatched.length ? { not_matched: notMatched } : {}),
130
+ ...(input.category ? { budget: budgetFor(l, asOf, input.category) } : {}),
131
+ assumptions,
132
+ source: { name: "OpenWallet", url: ow.url, catalog },
133
+ note: found.length
134
+ ? "Cashback rules are OpenWallet's, quoted with their date (lastChecked, or the catalog date when null: then unverified). Unknown is not 0."
135
+ : "None of the cards could be found in OpenWallet: see not_matched.",
136
+ };
137
+ }
@@ -11,6 +11,8 @@ export interface Env {
11
11
  /** GitHub logins allowed to sign in, comma-separated */
12
12
  ALLOWED_LOGINS: string;
13
13
  TIMEZONE?: string;
14
+ /** OpenWallet's MCP URL: turns on best_card (an outside source; unset = off) */
15
+ OPENWALLET_URL?: string;
14
16
  GITHUB_APP_ID: string;
15
17
  GITHUB_APP_PRIVATE_KEY: string;
16
18
  GITHUB_CLIENT_ID: string;
@@ -1,4 +1,9 @@
1
1
  import { McpServer } from "@modelcontextprotocol/server";
2
2
  import type { Env, Props } from "./env.js";
3
3
  import { type DataSource } from "./store.js";
4
- export declare function buildServer(env: Env, props: Props, src?: DataSource): McpServer;
4
+ import { type OpenWallet } from "./openwallet.js";
5
+ export interface Deps {
6
+ /** OpenWallet client; by default made from env.OPENWALLET_URL (unset = off) */
7
+ openwallet?: OpenWallet | null;
8
+ }
9
+ export declare function buildServer(env: Env, props: Props, src?: DataSource, deps?: Deps): McpServer;
@@ -11,11 +11,15 @@ import { cards, deposits, planStatus, plansDue, today } from "../engine/schedule
11
11
  import { MainMovedError } from "./github.js";
12
12
  import { applyPending, savePending, snapshot, sourceFor } from "./store.js";
13
13
  import { VERSION } from "./version.js";
14
+ import { bestCard } from "./bestcard.js";
15
+ import { openWalletClient } from "./openwallet.js";
14
16
  const out = (v) => ({ content: [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v) }] });
15
17
  const fail = (msg) => ({ content: [{ type: "text", text: msg }], isError: true });
16
18
  const INSTRUCTIONS = `ownledger: the owner's personal finance ledger, kept in their private GitHub repo.
17
19
  Amounts are whole numbers in the base currency (see about). Answers are computed here; never add up raw rows yourself when a tool computes it.
18
20
  Writes: the add_/edit_/void_ tools only PREVIEW. Show the owner the preview (what, amounts, accounts), wait for their explicit go, then call apply with the preview_id. Never invent an amount, date, account or category: ask. Call rules once before the first write.`;
21
+ const OPENWALLET_LINE = `
22
+ Which card to use for a purchase: best_card (the owner turned on OpenWallet, an outside card catalog: it gets the cards' product names and the purchase). Quote its cashback with OpenWallet's date and link; unknown is not 0. If a card is in not_matched, say so and how to fix it.`;
19
23
  function compactTx(t) {
20
24
  return {
21
25
  id: t.id,
@@ -59,8 +63,9 @@ const reason = z
59
63
  .min(3)
60
64
  .max(A.REASON_MAX)
61
65
  .describe("Required. One line: what the owner asked for, close to their own words (kept on the transaction's trail and in the commit).");
62
- export function buildServer(env, props, src = sourceFor(env)) {
63
- const server = new McpServer({ name: "ownledger", version: VERSION }, { instructions: INSTRUCTIONS });
66
+ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
67
+ const ow = deps.openwallet !== undefined ? deps.openwallet : env.OPENWALLET_URL ? openWalletClient(env.OPENWALLET_URL) : null;
68
+ const server = new McpServer({ name: "ownledger", version: VERSION }, { instructions: INSTRUCTIONS + (ow ? OPENWALLET_LINE : "") });
64
69
  const tz = env.TIMEZONE || "Asia/Ho_Chi_Minh";
65
70
  const now = () => todayIn(tz);
66
71
  const snap = () => snapshot(env, src);
@@ -224,10 +229,35 @@ export function buildServer(env, props, src = sourceFor(env)) {
224
229
  ...(months ? { series: netWorthSeries(s.ledger, addMonths(asOf.slice(0, 7) + "-01", -(months - 1)), asOf).map((x) => ({ date: x.date, net: x.net, assets: x.assets, liabilities: x.liabilities })) } : {}),
225
230
  };
226
231
  }));
227
- server.registerTool("cards", { description: "Credit cards: owed, last statement, what to pay, due date, available credit.", inputSchema: z.object({ date: z.string().optional() }), annotations: ro }, wrap(async ({ date }) => {
232
+ server.registerTool("cards", {
233
+ description: "Credit cards: owed, last statement, what to pay, due date, available credit, product name, and this statement period (spent by category, refunds, cashback credited).",
234
+ inputSchema: z.object({
235
+ date: z.string().optional(),
236
+ all: z.boolean().optional().describe("Every open card, also those with nothing owed (e.g. to choose a card for a purchase). Default: only cards with something owed."),
237
+ }),
238
+ annotations: ro,
239
+ }, wrap(async ({ date, all }) => {
228
240
  const s = await snap();
229
- return cards(s.ledger, date ?? now()).filter((c) => c.owed !== 0 || (c.toPay ?? 0) > 0);
241
+ const list = cards(s.ledger, date ?? now());
242
+ return all ? list : list.filter((c) => c.owed !== 0 || (c.toPay ?? 0) > 0);
230
243
  }));
244
+ if (ow) {
245
+ server.registerTool("best_card", {
246
+ description: "Which of the owner's credit cards pays the most cashback for one purchase, given what each card already spent and earned this statement period; with available credit, due date and (with category) the budget left. Asks OpenWallet (outside source the owner turned on): sends the cards' product names and banks, the purchase, and each card's spend and cashback this period.",
247
+ inputSchema: z.object({
248
+ amount: z.number().int().positive().describe("the purchase, whole base-currency units"),
249
+ merchant: z.string().optional().describe("where, e.g. Shopee, Co.opmart, Grab"),
250
+ kind: z.string().optional().describe("what kind, when no merchant: OpenWallet spending kind, e.g. groceries, dining, fuel, travel"),
251
+ date: z.string().optional().describe("yyyy-mm-dd, default today"),
252
+ category: z.string().optional().describe("the owner's category path for this purchase (e.g. food/groceries): adds the budget left"),
253
+ accounts: z.array(z.string()).optional().describe("only these card account ids"),
254
+ }),
255
+ annotations: { readOnlyHint: true, openWorldHint: true },
256
+ }, wrap(async (a) => {
257
+ const s = await snap();
258
+ return bestCard(s.ledger, now(), ow, a);
259
+ }));
260
+ }
231
261
  server.registerTool("plans_due", { description: "Instalments, loan payments and premiums due in the next N days (and overdue), plus what's left per plan.", inputSchema: z.object({ days: z.number().int().max(366).optional() }), annotations: ro }, wrap(async ({ days }) => {
232
262
  const s = await snap();
233
263
  const asOf = now();
@@ -0,0 +1,11 @@
1
+ export declare const OPENWALLET_DEFAULT_URL = "https://mcp.openwallet.vn/mcp";
2
+ export declare class OpenWalletError extends Error {
3
+ }
4
+ export interface OpenWallet {
5
+ url: string;
6
+ call(tool: string, args: Record<string, unknown>): Promise<any>;
7
+ }
8
+ type Fetch = typeof fetch;
9
+ /** A minimal MCP client over Streamable HTTP: initialize once, then tools/call. */
10
+ export declare function openWalletClient(url: string, fetchImpl?: Fetch): OpenWallet;
11
+ export {};
@@ -0,0 +1,89 @@
1
+ // OpenWallet (https://openwallet.vn): a public catalog of bank cards in Vietnam with an MCP server. An outside source
2
+ // the owner turns on (OPENWALLET_URL); off by default. Nothing it returns is stored. What is sent: card product
3
+ // names and banks (to find the cards), the purchase (amount, merchant or kind, date) and, per card, what was spent
4
+ // and the cashback booked this statement period. Never account ids, notes, balances or anything else.
5
+ export const OPENWALLET_DEFAULT_URL = "https://mcp.openwallet.vn/mcp";
6
+ const TIMEOUT_MS = 10_000;
7
+ export class OpenWalletError extends Error {
8
+ }
9
+ /** Reads a JSON-RPC response that came back as JSON or as server-sent events. */
10
+ async function rpcBody(res, id) {
11
+ const type = res.headers.get("content-type") ?? "";
12
+ const text = await res.text();
13
+ if (type.includes("text/event-stream")) {
14
+ for (const block of text.split(/\r?\n\r?\n/)) {
15
+ const data = block
16
+ .split(/\r?\n/)
17
+ .filter((l) => l.startsWith("data:"))
18
+ .map((l) => l.slice(5).trimStart())
19
+ .join("\n");
20
+ if (!data)
21
+ continue;
22
+ const m = JSON.parse(data);
23
+ if (m.id === id)
24
+ return m;
25
+ }
26
+ throw new OpenWalletError("OpenWallet: no answer in the event stream");
27
+ }
28
+ return text ? JSON.parse(text) : null;
29
+ }
30
+ /** A minimal MCP client over Streamable HTTP: initialize once, then tools/call. */
31
+ export function openWalletClient(url, fetchImpl = fetch) {
32
+ let session = null;
33
+ let n = 0;
34
+ const post = async (body, sessionId, protocol) => {
35
+ const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
36
+ if (sessionId)
37
+ headers["mcp-session-id"] = sessionId;
38
+ if (protocol)
39
+ 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})`);
46
+ }
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
+ };
51
+ const init = async () => {
52
+ const id = ++n;
53
+ const res = await post({ jsonrpc: "2.0", id, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "ownledger", version: "1" } } });
54
+ const m = await rpcBody(res, id);
55
+ if (!m || m.error)
56
+ throw new OpenWalletError(`OpenWallet: ${m?.error?.message ?? "no answer to initialize"}`);
57
+ const s = { id: res.headers.get("mcp-session-id") ?? undefined, protocol: String(m.result?.protocolVersion ?? "2025-06-18") };
58
+ await post({ jsonrpc: "2.0", method: "notifications/initialized" }, s.id, s.protocol);
59
+ return s;
60
+ };
61
+ return {
62
+ url,
63
+ async call(tool, args) {
64
+ session ??= init().catch((e) => {
65
+ session = null;
66
+ throw e;
67
+ });
68
+ const s = await session;
69
+ const id = ++n;
70
+ const m = await rpcBody(await post({ jsonrpc: "2.0", id, method: "tools/call", params: { name: tool, arguments: args } }, s.id, s.protocol), id);
71
+ if (!m)
72
+ throw new OpenWalletError(`OpenWallet: no answer to ${tool}`);
73
+ if (m.error)
74
+ throw new OpenWalletError(`OpenWallet ${tool}: ${m.error.message}`);
75
+ const r = m.result ?? {};
76
+ if (r.structuredContent && !r.isError)
77
+ return r.structuredContent;
78
+ const text = (r.content ?? []).map((c) => c.text ?? "").join("\n");
79
+ if (r.isError)
80
+ throw new OpenWalletError(`OpenWallet ${tool}: ${text}`);
81
+ try {
82
+ return JSON.parse(text);
83
+ }
84
+ catch {
85
+ return text;
86
+ }
87
+ },
88
+ };
89
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "1.1.0";
1
+ export declare const VERSION = "1.2.0";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "1.1.0";
2
+ export const VERSION = "1.2.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
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",