ownledger 1.2.0 → 2.0.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.
Files changed (153) hide show
  1. package/AGENTS.md +28 -1
  2. package/CHANGELOG.md +48 -0
  3. package/assets/apple-touch-icon.png +0 -0
  4. package/assets/icon-192.png +0 -0
  5. package/assets/icon-512.png +0 -0
  6. package/assets/icon-maskable-512.png +0 -0
  7. package/assets/index.html +15 -18
  8. package/assets/manifest.webmanifest +1 -1
  9. package/assets/static/Account-DEBzshne.js +1 -0
  10. package/assets/static/Accounts-C1iNsQsy.js +1 -0
  11. package/assets/static/Attention-qo4v70P1.js +1 -0
  12. package/assets/static/ByCategory-33P2zSs-.js +1 -0
  13. package/assets/static/CardDetail-CvRo7JPt.js +1 -0
  14. package/assets/static/Cards-C3AdusmT.js +1 -0
  15. package/assets/static/Cards-DuqZFxkQ.js +1 -0
  16. package/assets/static/CardsValue-BM9WUQmy.js +1 -0
  17. package/assets/static/Cashback-DsWyjgRr.js +1 -0
  18. package/assets/static/CategoryIcon-E6EWIpbr.js +1 -0
  19. package/assets/static/CategoryPicker-BPeJNSuM.js +1 -0
  20. package/assets/static/ChartWidget-Bk1TAvJM.js +1 -0
  21. package/assets/static/Combobox-lRNTmjKR.js +1 -0
  22. package/assets/static/Deposits-CgEFypxb.js +1 -0
  23. package/assets/static/DrillLink-pa6s17Xu.js +1 -0
  24. package/assets/static/Field-OkPhoYM1.js +1 -0
  25. package/assets/static/HomeEditor-DdrzEPe2.js +1 -0
  26. package/assets/static/Import-DrhHmL65.js +2 -0
  27. package/assets/static/IncomeSpending-Cveqr3xt.js +1 -0
  28. package/assets/static/KV-CKGyL0p7.js +1 -0
  29. package/assets/static/Left-Bs_oKU19.js +1 -0
  30. package/assets/static/Money-DCMKf898.js +1 -0
  31. package/assets/static/NetWorth-Cjd13J56.js +1 -0
  32. package/assets/static/Pace-CBUDNxzH.js +1 -0
  33. package/assets/static/Panel-CXjnsEN0.js +1 -0
  34. package/assets/static/PinDialog-DoGuAyi4.js +1 -0
  35. package/assets/static/Plans-EWJdPCJ3.js +1 -0
  36. package/assets/static/Recent-BmJjA5dK.js +1 -0
  37. package/assets/static/Reports-DSrLn_wC.js +1 -0
  38. package/assets/static/Settings-DdiEp2Qi.js +1 -0
  39. package/assets/static/Transactions-Cy0kgcLE.js +1 -0
  40. package/assets/static/TxRow-IqjFXpya.js +1 -0
  41. package/assets/static/Unusual-D5-L9ZOy.js +1 -0
  42. package/assets/static/Upcoming-CCqPol8c.js +1 -0
  43. package/assets/static/WhichCard-Butdi7AN.js +1 -0
  44. package/assets/static/arrow-up-C8D_7x_H.js +1 -0
  45. package/assets/static/bits-BoWPOwTB.js +1 -0
  46. package/assets/static/button-Cj0k8AtB.js +1 -0
  47. package/assets/static/cards-AZlSJQ0z.js +1 -0
  48. package/assets/static/charts-Cj_hTR4h.js +65 -0
  49. package/assets/static/chevron-down-BLodeu9a.js +1 -0
  50. package/assets/static/chevron-right-BetctQ6k.js +1 -0
  51. package/assets/static/createLucideIcon-DUW9Fpzj.js +1 -0
  52. package/assets/static/dialog-BIbLA-XP.js +1 -0
  53. package/assets/static/dist-CbNfxqbd.js +1 -0
  54. package/assets/static/dist-CetESl7K.js +1 -0
  55. package/assets/static/dist-DYP_TYPy.js +1 -0
  56. package/assets/static/dist-DaSyQKU7.js +1 -0
  57. package/assets/static/drill-t1zr57xi.js +1 -0
  58. package/assets/static/es2015-BgAh-EkH.js +41 -0
  59. package/assets/static/fold-CGWYt9Iu.js +1 -0
  60. package/assets/static/index-CBsgYTMJ.css +1 -0
  61. package/assets/static/index-DYyIpxqK.js +14 -0
  62. package/assets/static/queries-C_4ufx4u.js +1 -0
  63. package/assets/static/react-dom-CI34djkT.js +1 -0
  64. package/assets/static/select-2EwEpMf_.js +1 -0
  65. package/assets/static/shared-CR-hvb-r.js +1 -0
  66. package/assets/static/triangle-exclamation-point-C6padEUM.js +1 -0
  67. package/assets/static/useMutation-BWtHiYPX.js +1 -0
  68. package/dist/cli/cards.d.ts +2 -0
  69. package/dist/cli/cards.js +86 -0
  70. package/dist/cli/import.js +12 -2
  71. package/dist/cli/index.js +3 -0
  72. package/dist/engine/actions.d.ts +5 -0
  73. package/dist/engine/actions.js +9 -5
  74. package/dist/engine/attention.d.ts +15 -0
  75. package/dist/engine/attention.js +63 -0
  76. package/dist/engine/check.js +8 -1
  77. package/dist/engine/dashboard.d.ts +72 -0
  78. package/dist/engine/dashboard.js +180 -0
  79. package/dist/engine/features.d.ts +20 -0
  80. package/dist/engine/features.js +37 -0
  81. package/dist/engine/index.d.ts +5 -0
  82. package/dist/engine/index.js +5 -0
  83. package/dist/engine/insights.d.ts +164 -0
  84. package/dist/engine/insights.js +534 -0
  85. package/dist/engine/load.js +6 -0
  86. package/dist/engine/registry.d.ts +2 -0
  87. package/dist/engine/registry.js +15 -33
  88. package/dist/engine/reports.d.ts +21 -2
  89. package/dist/engine/reports.js +51 -3
  90. package/dist/engine/schedules.d.ts +7 -84
  91. package/dist/engine/schedules.js +8 -207
  92. package/dist/engine/types.d.ts +2 -0
  93. package/dist/engine/write.d.ts +9 -0
  94. package/dist/engine/write.js +26 -5
  95. package/dist/import/mapping.js +6 -0
  96. package/dist/import/run.d.ts +7 -0
  97. package/dist/import/run.js +28 -1
  98. package/dist/modules/api.d.ts +19 -0
  99. package/dist/modules/api.js +16 -0
  100. package/dist/modules/cards/api.d.ts +3 -0
  101. package/dist/modules/cards/api.js +73 -0
  102. package/dist/modules/cards/engine.d.ts +42 -0
  103. package/dist/modules/cards/engine.js +102 -0
  104. package/dist/modules/cards/index.d.ts +26 -0
  105. package/dist/modules/cards/index.js +304 -0
  106. package/dist/modules/cards/statements.d.ts +128 -0
  107. package/dist/modules/cards/statements.js +426 -0
  108. package/dist/modules/cards/terms.d.ts +105 -0
  109. package/dist/modules/cards/terms.js +194 -0
  110. package/dist/modules/cards/tracker.d.ts +36 -0
  111. package/dist/modules/cards/tracker.js +232 -0
  112. package/dist/modules/cards/types.d.ts +2 -0
  113. package/dist/modules/cards/types.js +16 -0
  114. package/dist/modules/deposits/engine.d.ts +14 -0
  115. package/dist/modules/deposits/engine.js +32 -0
  116. package/dist/modules/deposits/index.d.ts +2 -0
  117. package/dist/modules/deposits/index.js +24 -0
  118. package/dist/modules/deposits/types.d.ts +2 -0
  119. package/dist/modules/deposits/types.js +15 -0
  120. package/dist/modules/index.d.ts +5 -0
  121. package/dist/modules/index.js +10 -0
  122. package/dist/modules/insurance/index.d.ts +3 -0
  123. package/dist/modules/insurance/index.js +8 -0
  124. package/dist/modules/insurance/types.d.ts +2 -0
  125. package/dist/modules/insurance/types.js +3 -0
  126. package/dist/modules/investments/index.d.ts +2 -0
  127. package/dist/modules/investments/index.js +24 -0
  128. package/dist/modules/investments/types.d.ts +2 -0
  129. package/dist/modules/investments/types.js +7 -0
  130. package/dist/modules/loans/engine.d.ts +30 -0
  131. package/dist/modules/loans/engine.js +77 -0
  132. package/dist/modules/loans/index.d.ts +2 -0
  133. package/dist/modules/loans/index.js +27 -0
  134. package/dist/modules/loans/types.d.ts +2 -0
  135. package/dist/modules/loans/types.js +5 -0
  136. package/dist/modules/types.d.ts +39 -0
  137. package/dist/modules/types.js +1 -0
  138. package/dist/modules/util.d.ts +8 -0
  139. package/dist/modules/util.js +8 -0
  140. package/dist/node/scaffold.js +2 -2
  141. package/dist/worker/api.d.ts +11 -1
  142. package/dist/worker/api.js +167 -13
  143. package/dist/worker/bestcard.d.ts +32 -9
  144. package/dist/worker/bestcard.js +91 -51
  145. package/dist/worker/mcp.js +209 -30
  146. package/dist/worker/openwallet.d.ts +1 -1
  147. package/dist/worker/openwallet.js +41 -11
  148. package/dist/worker/version.d.ts +1 -1
  149. package/dist/worker/version.js +1 -1
  150. package/package.json +26 -4
  151. package/presets/misa.mapping.yaml +7 -0
  152. package/assets/app.css +0 -61
  153. package/assets/app.js +0 -369
@@ -1,10 +1,17 @@
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.
1
+ // best_card: which of the owner's cards to use for one purchase. Cards with the owner's own cashback terms
2
+ // (details.cashback / data/cards.yaml) are ranked here, nothing sent anywhere. Cards without terms ask OpenWallet,
3
+ // when the owner turned it on (an outside source): those cards are looked up each time by their product name
4
+ // (details.product, or the account name) and bank, and nothing OpenWallet returns is stored.
4
5
  import { budgets, cards, fold } from "../engine/index.js";
6
+ import { bestCard as localBestCard } from "../modules/cards/statements.js";
7
+ import { recordFor, termsOf } from "../modules/cards/terms.js";
5
8
  /** letters and digits only, no accents: "Demo Bank" and "demo-bank" are the same */
6
9
  const key = (s) => fold(s).replace(/[^a-z0-9]/g, "");
7
10
  const isDebit = (t) => (Array.isArray(t) ? t.includes("debit") && !t.includes("credit") : t === "debit");
11
+ /** search results kept in this Worker's memory for an hour (never written anywhere): fewer calls to OpenWallet */
12
+ const SEARCH_TTL_MS = 60 * 60 * 1000;
13
+ const searchCache = new Map();
14
+ export const clearSearchCache = () => searchCache.clear();
8
15
  async function findCard(ow, c) {
9
16
  const product = c.product ?? c.name;
10
17
  const miss = (why, candidates) => ({
@@ -14,7 +21,15 @@ async function findCard(ow, c) {
14
21
  why,
15
22
  ...(candidates?.length ? { candidates } : {}),
16
23
  });
17
- const search = async (q) => ((await ow.call("search_cards", { q, limit: 10 }))?.cards ?? []);
24
+ const search = async (q) => {
25
+ const k = `${ow.url}|${q}`;
26
+ const hit = searchCache.get(k);
27
+ if (hit && hit.until > Date.now())
28
+ return hit.cards;
29
+ const cards = ((await ow.call("search_cards", { q, limit: 10 }))?.cards ?? []);
30
+ searchCache.set(k, { cards, until: Date.now() + SEARCH_TTL_MS });
31
+ return cards;
32
+ };
18
33
  const sameBank = (xs) => {
19
34
  if (!c.bank)
20
35
  return xs;
@@ -54,19 +69,7 @@ function budgetFor(l, asOf, category) {
54
69
  const b = all.filter((x) => category === x.category || category.startsWith(x.category + "/")).sort((a, b) => b.category.length - a.category.length)[0];
55
70
  return b ? { category: b.category, every: b.every, amount: b.amount, spent: b.spent, left: b.left } : { category, none: true };
56
71
  }
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.");
72
+ async function openWalletRows(l, asOf, ow, mine, input, date) {
70
73
  const [what, ...looked] = await Promise.all([resolveWhat(ow, input), ...mine.map((c) => findCard(ow, c))]);
71
74
  const found = [];
72
75
  const notMatched = [];
@@ -81,13 +84,9 @@ export async function bestCard(l, asOf, ow, input) {
81
84
  else
82
85
  notMatched.push(r);
83
86
  }
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 = [];
87
+ const rows = new Map();
88
+ const assumptions = [];
89
89
  let catalog = null;
90
- let purchase = null;
91
90
  if (found.length) {
92
91
  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
92
  const r = await ow.call("rank_cards_for_spend", {
@@ -95,43 +94,84 @@ export async function bestCard(l, asOf, ow, input) {
95
94
  cards: states,
96
95
  limit: 20,
97
96
  });
98
- purchase = r?.purchase ?? null;
99
97
  catalog = r?.meta?.catalog ?? null;
100
- assumptions.push(...(r?.assumptions ?? []));
101
- ranking = (r?.cards ?? []).map((x) => {
98
+ assumptions.push("OpenWallet cards: spend_so_far and cap_used come from the ledger (what is recorded this statement period); banks often pay cashback after the statement closes, so the bank's cap used can be higher.", ...(r?.assumptions ?? []).map((a) => `OpenWallet: ${a}`));
99
+ for (const x of (r?.cards ?? [])) {
102
100
  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,
101
+ const st = states.find((y) => y.id === x.id);
102
+ rows.set(f.card.account, {
103
+ source: "openwallet",
104
+ earn: x.cashback ?? null,
105
+ rate: typeof x.effective_rate === "number" ? Math.round(x.effective_rate * 10000) / 100 : null,
106
+ capLeft: x.rule?.cap_remaining ?? x.global_cap_remaining ?? null,
110
107
  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
108
  spend_so_far: st.spend_so_far,
116
109
  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
110
  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
- });
111
+ reason: `${f.card.name}: OpenWallet (${f.ow.name}) · ${x.reason ?? x.status}`,
112
+ });
113
+ }
114
+ }
115
+ return { rows, notMatched, assumptions, catalog, what: what.label };
116
+ }
117
+ export async function bestCard(l, asOf, ow, input) {
118
+ const date = input.date ?? asOf;
119
+ const amount = input.amount ?? 0;
120
+ let local = localBestCard(l, { category: input.category ?? "", amount, date });
121
+ if (input.accounts?.length) {
122
+ const known = new Set(local.map((r) => r.account));
123
+ const unknown = input.accounts.filter((a) => !known.has(a));
124
+ if (unknown.length)
125
+ throw new Error(`not a card that can be used: ${unknown.join(", ")}`);
126
+ local = local.filter((r) => input.accounts.includes(r.account));
124
127
  }
128
+ if (!local.length)
129
+ throw new Error("No open card to use (closed, cancelled or locked cards are left out, and cards without enough limit left).");
130
+ const hasTerms = (id) => {
131
+ const a = l.accounts.find((x) => x.id === id);
132
+ return termsOf(a, recordFor(l, id)).cashback !== null;
133
+ };
134
+ const assumptions = [];
135
+ if (!input.category)
136
+ assumptions.push("No category given: cards with your own terms use their base rate.");
137
+ const without = local.filter((r) => !hasTerms(r.account));
138
+ const status = cards(l, date);
139
+ const asking = without.map((r) => status.find((c) => c.account === r.account)).filter((c) => Boolean(c));
140
+ let fromOw = null;
141
+ if (ow && asking.length) {
142
+ if (!input.amount)
143
+ assumptions.push("OpenWallet not asked: give the amount.");
144
+ else if (!input.merchant && !input.kind)
145
+ assumptions.push("OpenWallet not asked: give a merchant (e.g. Shopee) or a kind (e.g. groceries) for the cards without your own terms.");
146
+ else
147
+ fromOw = await openWalletRows(l, asOf, ow, asking, { ...input, amount: input.amount }, date);
148
+ }
149
+ if (fromOw)
150
+ assumptions.push(...fromOw.assumptions);
151
+ const rows = local.map((r) => {
152
+ if (hasTerms(r.account))
153
+ return { ...r, source: "yours" };
154
+ const o = fromOw?.rows.get(r.account);
155
+ if (o)
156
+ return { ...r, ...o, source: "openwallet" };
157
+ return {
158
+ ...r,
159
+ source: "none",
160
+ earn: null,
161
+ rate: null,
162
+ reason: `${r.name}: no cashback terms set${ow ? " and not found in OpenWallet" : ""}${r.payBy ? ` · pay by ${r.payBy} (${r.freeDays} days)` : ""}`,
163
+ };
164
+ });
165
+ // most cashback first (a minimum still to reach counts half), then interest-free days, then limit left
166
+ const effective = (b) => (!b.earn ? -1 : b.minSpendShort > 0 ? b.earn / 2 : b.earn);
167
+ rows.sort((x, y) => effective(y) - effective(x) || (y.freeDays ?? -1) - (x.freeDays ?? -1) || (y.limitLeft ?? 0) - (x.limitLeft ?? 0));
125
168
  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 } : {}),
169
+ purchase: { amount: input.amount ?? null, date, category: input.category ?? null, merchant: input.merchant ?? null, kind: input.kind ?? null },
170
+ cards: rows.slice(0, 10),
171
+ ...(fromOw?.notMatched.length ? { not_matched: fromOw.notMatched } : {}),
130
172
  ...(input.category ? { budget: budgetFor(l, asOf, input.category) } : {}),
131
173
  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.",
174
+ ...(fromOw ? { openwallet: { url: ow.url, catalog: fromOw.catalog, what: fromOw.what } } : {}),
175
+ note: "source says where each cashback figure comes from: yours (your own terms), openwallet (its catalog, quoted with lastChecked or the catalog date), none (unknown, which is not 0).",
136
176
  };
137
177
  }
@@ -11,15 +11,26 @@ 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 { attention } from "../engine/attention.js";
15
+ import { dashboardPath, defaultWidgets, GRID_COLS, poolOf, writeDashboard } from "../engine/dashboard.js";
16
+ import { features } from "../engine/features.js";
17
+ import { series } from "../engine/insights.js";
18
+ import { yamlText } from "../engine/write.js";
19
+ import { dashboardOf } from "./api.js";
20
+ import { cardList } from "../modules/cards/index.js";
21
+ import { cashback, closeOnOrAfter, feeWaiver, lineKind, statements } from "../modules/cards/statements.js";
22
+ import { cardsData, STATEMENTS_FILE, termsOf, recordFor } from "../modules/cards/terms.js";
14
23
  import { bestCard } from "./bestcard.js";
15
24
  import { openWalletClient } from "./openwallet.js";
16
25
  const out = (v) => ({ content: [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v) }] });
17
26
  const fail = (msg) => ({ content: [{ type: "text", text: msg }], isError: true });
18
27
  const INSTRUCTIONS = `ownledger: the owner's personal finance ledger, kept in their private GitHub repo.
19
28
  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.
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.`;
29
+ Writes: the add_/edit_/void_/set_/remove_ 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.
30
+ Dashboard: when the owner asks to "track", "watch" or "put on my dashboard" something, offer a widget (add_widget), using the categories and accounts from rules.
31
+ Cards: for "which card should I use", call best_card; statements, cashback and fee waivers come from cards and card_statement.`;
21
32
  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.`;
33
+ best_card also asks OpenWallet (an outside card catalog the owner turned on) for cards without the owner's own cashback terms: give it the amount and a merchant or kind. It gets those cards' product names, the purchase and their spend this period. Quote OpenWallet's figures with its date and link (source: openwallet); unknown is not 0. If a card is in not_matched, say so and how to fix it.`;
23
34
  function compactTx(t) {
24
35
  return {
25
36
  id: t.id,
@@ -48,7 +59,7 @@ const txFields = {
48
59
  note: z.string().optional(),
49
60
  kind: z.enum(["expense", "income", "transfer"]).optional().describe("simple form; or give lines"),
50
61
  amount: z.number().int().positive().optional().describe("simple form: positive, whole base-currency units"),
51
- account: z.string().optional().describe("expense: paid from; income: received into; transfer: from"),
62
+ account: z.string().optional().describe("expense: paid from; income: received into; transfer: from. Omit to use the pool's default account (see rules)"),
52
63
  to_account: z.string().optional().describe("transfer: to"),
53
64
  category: z.string().optional().describe("category path, e.g. food/eating-out"),
54
65
  lines: z.array(lineSchema).optional().describe("full form: balanced lines (sum 0); for splits, assets with qty, etc."),
@@ -97,6 +108,13 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
97
108
  next: "Show this to the owner. Only after their explicit go, call apply with this preview_id.",
98
109
  };
99
110
  };
111
+ /** The signed-in person's "My money" pool: how writes pick an account when none is named. */
112
+ const poolRule = (files, L) => {
113
+ const p = poolOf(L, dashboardOf(files, props.login)?.prefs?.pool, now());
114
+ return p.on
115
+ ? { on: true, accounts: p.accounts, default_account: p.default_account, rule: `Everyday money (${p.accounts.join(", ")}) is one pool: when the owner doesn't name a wallet, spending and income go to ${p.default_account} and paying a card is one transfer ${p.default_account} → card. A named wallet ("paid by MoMo") is used as named.` }
116
+ : { on: false, rule: "Ask which account when it isn't named." };
117
+ };
100
118
  /* ---------------------------------------------------------------- read */
101
119
  server.registerTool("about", { description: "Version, data repo, last commit, base currency, counts, today's date.", annotations: ro }, wrap(async () => {
102
120
  const s = await snap();
@@ -112,6 +130,7 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
112
130
  accounts: s.ledger.accounts.length,
113
131
  transactions: s.ledger.transactions.filter((t) => !t.void).length,
114
132
  check: { errors: s.errors, warnings: s.warnings },
133
+ dashboard: `data/dashboards/${props.login.toLowerCase()}.yaml (dashboard / add_widget tools)`,
115
134
  };
116
135
  }));
117
136
  server.registerTool("rules", { description: "What to follow before writing, plus the category list and the accounts (ids). Call once before the first write.", annotations: ro }, wrap(async () => {
@@ -133,6 +152,7 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
133
152
  system: Object.entries(SYSTEM_CATEGORIES).map(([k, v]) => `${k}: ${v.en}`),
134
153
  },
135
154
  accounts: s.ledger.accounts.filter((a) => !a.closed).map((a) => `${a.id}: ${a.name} (${a.type})`),
155
+ pool: poolRule(s.files, s.ledger),
136
156
  };
137
157
  }));
138
158
  server.registerTool("accounts", {
@@ -229,35 +249,50 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
229
249
  ...(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 })) } : {}),
230
250
  };
231
251
  }));
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).",
252
+ server.registerTool("cards", { description: "Credit cards: owed, limit, last statement (to pay, due, paid or not), cashback this period, this statement period (spent by category, refunds, cashback booked), product name, annual fee waiver, terms still missing.", inputSchema: z.object({ date: z.string().optional(), include_closed: z.boolean().optional() }), annotations: ro }, wrap(async ({ date, include_closed }) => {
253
+ const s = await snap();
254
+ const asOf = date ?? now();
255
+ const per = new Map(cards(s.ledger, asOf).map((x) => [x.account, x]));
256
+ return cardList(s.ledger, asOf, { includeClosed: include_closed }).map((c) => ({
257
+ account: c.account,
258
+ name: c.name,
259
+ owed: c.owed,
260
+ limit: c.limit ?? (c.limitAtLeast ? `at least ${c.limitAtLeast} (most ever owed; limit not set)` : null),
261
+ last_statement: c.last ? { date: c.last.close, amount_due: c.last.amountDue, paid: c.last.paid, to_pay: c.last.toPay, due: c.last.due, status: c.last.status, ...(c.last.bank !== null ? { bank: c.last.bank, diff: c.last.bankDiff } : {}) } : null,
262
+ this_period: c.current ? { from: c.current.from, purchases: c.current.purchases } : null,
263
+ cashback: c.cashback ? { spend: c.cashback.spend, expected: c.cashback.expected, cap_left: c.cashback.capLeft, min_met: c.cashback.minMet, need_for_min: c.cashback.needForMin, ...(c.cashback.incomplete ? { note: "some rates not set" } : {}) } : null,
264
+ ...(c.bank ? { bank: c.bank } : {}),
265
+ ...(per.get(c.account)?.product ? { product: per.get(c.account).product } : {}),
266
+ ...(per.get(c.account) ? { period: (({ from, to, spent, refunds, byCategory, cashback }) => ({ from, to, spent, refunds, by_category: byCategory, cashback_booked: cashback }))(per.get(c.account).period) } : {}),
267
+ fee_waiver: feeWaiver(s.ledger, c.account, asOf),
268
+ ...(c.missing.length ? { missing: c.missing } : {}),
269
+ }));
270
+ }));
271
+ server.registerTool("card_statement", { description: "One card statement in detail (default: the last closed one): opening, purchases, refunds, cashback, fees, payments, closing, due, paid, and its transactions.", inputSchema: z.object({ account: z.string(), statement_date: z.string().optional().describe("yyyy-mm-dd") }), annotations: ro }, wrap(async ({ account, statement_date }) => {
272
+ const s = await snap();
273
+ const all = statements(s.ledger, account, now());
274
+ const st = statement_date ? all.find((x) => x.close === statement_date) : [...all].reverse().find((x) => !x.open);
275
+ if (!st)
276
+ throw new A.ActionError(`no statement${statement_date ? ` on ${statement_date}` : ""} for ${account} (statement dates: ${all.slice(-6).map((x) => x.close).join(", ")})`);
277
+ const { map } = flattenCategories(s.ledger.categories);
278
+ const txs = s.ledger.transactions.filter((t) => !t.void && t.date >= st.from && t.date <= st.close && t.lines.some((l) => l.account === account));
279
+ return { statement: st, transactions: txs.map((t) => ({ ...compactTx(t), kind: lineKind(t, account, map)?.kind })), cashback: cashback(s.ledger, account, now()).find((p) => p.close === st.close) ?? null };
280
+ }));
281
+ server.registerTool("best_card", {
282
+ description: "Which card to use for one purchase: open cards ranked by cashback (cap left, minimum spend), then interest-free days, then limit left, each with its source. Cards with the owner's own cashback terms are ranked here; with OpenWallet on, cards without terms are looked up there (needs amount and merchant or kind; sends those cards' product names and banks, the purchase, and their spend and cashback this period).",
234
283
  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."),
284
+ category: z.string().optional().describe("the owner's category path, e.g. food/groceries: picks the rate from the owner's terms, adds the budget left"),
285
+ amount: z.number().int().positive().optional().describe("the purchase, whole base-currency units"),
286
+ merchant: z.string().optional().describe("OpenWallet: where, e.g. Shopee, Co.opmart, Grab"),
287
+ kind: z.string().optional().describe("OpenWallet: what kind when no merchant, e.g. groceries, dining, fuel, travel"),
288
+ date: z.string().optional().describe("yyyy-mm-dd, default today"),
289
+ accounts: z.array(z.string()).optional().describe("only these card account ids"),
237
290
  }),
238
- annotations: ro,
239
- }, wrap(async ({ date, all }) => {
291
+ annotations: { readOnlyHint: true, openWorldHint: Boolean(ow) },
292
+ }, wrap(async (a) => {
240
293
  const s = await snap();
241
- const list = cards(s.ledger, date ?? now());
242
- return all ? list : list.filter((c) => c.owed !== 0 || (c.toPay ?? 0) > 0);
294
+ return bestCard(s.ledger, now(), ow, a);
243
295
  }));
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
- }
261
296
  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 }) => {
262
297
  const s = await snap();
263
298
  const asOf = now();
@@ -271,7 +306,8 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
271
306
  const s = await snap();
272
307
  const t = today(s.ledger, now());
273
308
  const m = report(s.ledger, now().slice(0, 7), { compare: false });
274
- return { ...t, this_month: { income: m.income, expense: m.expense } };
309
+ const needs = attention(s.ledger, now(), { files: s.files, check: { errors: s.errors, warnings: s.warnings } }).map((a) => ({ severity: a.severity, kind: a.kind, title: a.title, ...(a.amount !== undefined ? { amount: a.amount } : {}), date: a.date }));
310
+ return { ...t, needs_you: needs, this_month: { income: m.income, expense: m.expense } };
275
311
  }));
276
312
  /* ---------------------------------------------------------------- write (preview) */
277
313
  const pv = { readOnlyHint: true, openWorldHint: false }; // previews change nothing
@@ -279,7 +315,16 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
279
315
  description: "PREVIEW a new transaction (writes nothing). Simple form: kind + amount + account (+ category or to_account). Full form: lines.",
280
316
  inputSchema: z.object({ ...txFields, reason }),
281
317
  annotations: pv,
282
- }, wrap(async ({ reason, ...a }) => preview((f) => A.addTransaction(f, a, meta(reason)))));
318
+ }, wrap(async ({ reason, ...a }) => {
319
+ // with the pool on, an unnamed account is the pool's default account
320
+ if (!a.lines?.length && !a.account) {
321
+ const s = await snap();
322
+ const p = poolOf(s.ledger, dashboardOf(s.files, props.login)?.prefs?.pool, now());
323
+ if (p.on && p.default_account)
324
+ a = { ...a, account: p.default_account };
325
+ }
326
+ return preview((f) => A.addTransaction(f, a, meta(reason)));
327
+ }));
283
328
  server.registerTool("edit_transaction", { description: "PREVIEW changes to a transaction by id (only the fields given change).", inputSchema: z.object({ id: z.string(), ...txFields, date: z.string().optional(), reason }), annotations: pv }, wrap(async ({ id, reason, ...patch }) => preview((f) => A.editTransaction(f, id, patch, meta(reason)))));
284
329
  server.registerTool("void_transaction", { description: "PREVIEW voiding a transaction (kept in history, excluded everywhere).", inputSchema: z.object({ id: z.string(), reason }), annotations: pv }, wrap(async ({ id, reason }) => preview((f) => A.voidTransaction(f, id, reason, meta(reason)))));
285
330
  const accountFields = {
@@ -318,6 +363,140 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
318
363
  server.registerTool("add_price", { description: "PREVIEW a price for an asset (base currency per unit) on a date.", inputSchema: z.object({ date: z.string(), asset: z.string(), price: z.number() }), annotations: pv }, wrap(async (p) => preview((f) => A.addPrice(f, p))));
319
364
  server.registerTool("add_category", { description: "PREVIEW a new category.", inputSchema: z.object({ kind: z.enum(["income", "expense"]), parent: z.string().optional(), id: z.string(), name: z.string() }), annotations: pv }, wrap(async (c) => preview((f) => A.addCategory(f, c))));
320
365
  server.registerTool("edit_category", { description: "PREVIEW renaming a category, or moving it to a new path (every line using it is remapped).", inputSchema: z.object({ path: z.string(), name: z.string().optional(), new_path: z.string().optional() }), annotations: pv }, wrap(async ({ path, ...set }) => preview((f) => A.editCategory(f, path, set))));
366
+ /* ---------------------------------------------------------------- cards (preview) */
367
+ server.registerTool("set_card_details", {
368
+ description: "PREVIEW card terms on a credit card account: statement and due days, limit, annual fee and its month, fee waiver target, cashback rules. Only the fields given change; they're kept over codes read from wallet names.",
369
+ inputSchema: z.object({
370
+ account: z.string(),
371
+ statement_day: z.number().int().min(1).max(31).optional(),
372
+ due_day: z.number().int().min(1).max(31).optional(),
373
+ limit: z.number().int().positive().optional(),
374
+ annual_fee: z.number().int().min(0).optional(),
375
+ fee_month: z.number().int().min(1).max(12).optional(),
376
+ fee_waiver_spend: z.number().int().positive().optional().describe("spend per card year that waives the annual fee"),
377
+ free_days_max: z.number().int().optional(),
378
+ cashback: z.object({
379
+ base: z.number().min(0).max(100).optional(),
380
+ rules: z.array(z.object({ categories: z.array(z.string()), rate: z.number().min(0).max(100) })).optional(),
381
+ cap: z.object({ amount: z.number().int().positive(), per: z.enum(["statement", "month"]) }).optional(),
382
+ min_spend: z.object({ amount: z.number().int().positive(), per: z.enum(["statement", "month"]) }).optional(),
383
+ spend_max: z.object({ amount: z.number().int().positive(), per: z.enum(["statement", "month"]) }).optional(),
384
+ paid_on: z.string().optional().describe("next_statement or days_after:<n>"),
385
+ }).optional().describe("merged into the card's cashback terms"),
386
+ }),
387
+ annotations: pv,
388
+ }, wrap(async ({ account, fee_waiver_spend, cashback: cb, ...rest }) => preview((f) => {
389
+ const { ledger } = A.loadForAction(f);
390
+ const a = ledger.accounts.find((x) => x.id === account);
391
+ if (!a)
392
+ throw new A.ActionError(`no account ${account}`);
393
+ const details = { ...(a.details ?? {}) };
394
+ const set = Object.fromEntries(Object.entries(rest).filter(([, v]) => v !== undefined));
395
+ if (fee_waiver_spend !== undefined)
396
+ set.fee_waiver = { spend: fee_waiver_spend, within: "year" };
397
+ if (cb)
398
+ set.cashback = { ...(details.cashback ?? {}), ...Object.fromEntries(Object.entries(cb).filter(([, v]) => v !== undefined)) };
399
+ if (!Object.keys(set).length)
400
+ throw new A.ActionError("nothing to change");
401
+ Object.assign(details, set);
402
+ const fromName = Array.isArray(details.from_name) ? details.from_name.filter((k) => !(k in set)) : undefined;
403
+ if (fromName)
404
+ details.from_name = fromName.length ? fromName : undefined;
405
+ if (details.from_name === undefined)
406
+ delete details.from_name;
407
+ return A.editAccount(f, account, { details });
408
+ })));
409
+ server.registerTool("add_statement_amount", { description: "PREVIEW the bank's amount for a card statement (from the bank's statement), to compare with the computed one.", inputSchema: z.object({ account: z.string(), statement_date: z.string().describe("yyyy-mm-dd, the statement's closing date"), amount: z.number().int() }), annotations: pv }, wrap(async ({ account, statement_date, amount }) => preview((f) => {
410
+ const { ledger } = A.loadForAction(f);
411
+ if (!ledger.accounts.some((a) => a.id === account))
412
+ throw new A.ActionError(`no account ${account}`);
413
+ const list = cardsData(ledger).statements.filter((x) => !(x.account === account && x.statement_date === statement_date));
414
+ list.push({ account, statement_date, amount });
415
+ list.sort((x, y) => (x.statement_date < y.statement_date ? -1 : x.statement_date > y.statement_date ? 1 : x.account < y.account ? -1 : 1));
416
+ return A.plan(f, { putFiles: { [STATEMENTS_FILE]: yamlText(list) } }, `Card statement: ${account} ${statement_date}`);
417
+ })));
418
+ server.registerTool("add_instalment", { description: "PREVIEW turning a card purchase into a 0% instalment plan (trả góp 0%): each statement then counts only the monthly amount.", inputSchema: z.object({ transaction: z.string().describe("id of the purchase on the card"), count: z.number().int().min(2).max(60), fee: z.number().int().min(0).optional().describe("conversion fee per month, if any"), id: z.string().optional(), name: z.string().optional(), first_statement: z.string().optional().describe("yyyy-mm-dd; default the first statement after the purchase") }), annotations: pv }, wrap(async ({ transaction, count, fee, id, name, first_statement }) => preview((f) => {
419
+ const { ledger } = A.loadForAction(f);
420
+ const t = ledger.transactions.find((x) => x.id === transaction);
421
+ if (!t)
422
+ throw new A.ActionError(`no transaction ${transaction}`);
423
+ const line = t.lines.find((l) => l.account && ledger.accounts.find((a) => a.id === l.account)?.type === "credit_card" && l.amount < 0);
424
+ if (!line)
425
+ throw new A.ActionError("that transaction isn't a purchase on a credit card");
426
+ const acc = ledger.accounts.find((a) => a.id === line.account);
427
+ const sd = termsOf(acc, recordFor(ledger, acc.id)).statementDay;
428
+ if (!sd && !first_statement)
429
+ throw new A.ActionError(`${acc.id} has no statement_day: give first_statement`);
430
+ const start = first_statement ?? closeOnOrAfter(t.date, sd);
431
+ const principal = -line.amount;
432
+ return A.addPlan(f, { id: id ?? `${acc.id}-${t.date.replace(/-/g, "")}-0pct`, kind: "instalment", account: acc.id, name: name ?? (t.note || `Trả góp ${acc.name}`), principal, count, every: "month", start, ...(fee ? { fee } : {}), rate: 0, source: t.id });
433
+ })));
434
+ /* ---------------------------------------------------------------- dashboard (preview) */
435
+ const queryShape = z.object({
436
+ metric: z.enum(["spending", "income", "net", "balance", "count"]),
437
+ category: z.string().optional(),
438
+ account: z.string().optional(),
439
+ who: z.string().optional(),
440
+ event: z.string().optional(),
441
+ tag: z.string().optional(),
442
+ text: z.string().optional(),
443
+ period: z.string().optional().describe("this-month, last-month, last-3-months, last-6-months, this-year, last-year, last-12-months, all, yyyy-mm or yyyy"),
444
+ by: z.enum(["day", "week", "month", "category", "top", "account", "who", "event", "tag"]).optional(),
445
+ compare: z.enum(["previous", "usual"]).optional(),
446
+ });
447
+ const myDashboard = async () => {
448
+ const s = await snap();
449
+ const d = dashboardOf(s.files, props.login);
450
+ const widgets = d?.widgets ?? defaultWidgets(features(s.ledger, now(), s.files));
451
+ return { s, d: { version: 1, ...(d ?? {}), widgets } };
452
+ };
453
+ const saveLayout = (d, message) => (f) => A.plan(f, { putFiles: { [dashboardPath(props.login)]: writeDashboard(d) } }, message);
454
+ const firstNumbers = async (q) => {
455
+ const s = await snap();
456
+ const pool = poolOf(s.ledger, dashboardOf(s.files, props.login)?.prefs?.pool, now());
457
+ const r = series(s.ledger, q.account === "pool" ? { ...q, account: pool.accounts } : q, now());
458
+ return { period: r.period, total: r.total, ...(r.compareTotal !== undefined ? { compare: r.compareTotal } : {}), first: r.points.slice(0, 8).map((p) => [p.name, p.value]) };
459
+ };
460
+ server.registerTool("dashboard", { description: "The signed-in owner's dashboard layout: widgets with ids, types, titles, queries and positions (12-column grid), from data/dashboards/<login>.yaml (defaults when there is no file yet).", annotations: ro }, wrap(async () => {
461
+ const { s, d } = await myDashboard();
462
+ return { file: dashboardPath(props.login), saved: Boolean(dashboardOf(s.files, props.login)), grid_columns: GRID_COLS, widgets: d.widgets };
463
+ }));
464
+ server.registerTool("add_widget", {
465
+ description: "PREVIEW adding a widget to the owner's dashboard: a chart from a query (type chart), or a built-in widget by type (pace, left, attention, unusual, net_worth, by_category, income_spending, recent, account, upcoming, cards, cashback, which_card, cards_value, deposits). Shows the first numbers so the owner can see it's right.",
466
+ inputSchema: z.object({ type: z.string().default("chart"), title: z.string().max(80).optional(), query: queryShape.optional(), chart: z.enum(["stat", "line", "bar", "hbar", "table"]).optional(), account: z.string().optional(), period: z.string().optional(), w: z.number().int().min(1).max(12).optional(), h: z.number().int().min(1).max(24).optional(), id: z.string().optional() }),
467
+ annotations: pv,
468
+ }, wrap(async ({ type, title, query, chart, account, period, w, h, id }) => {
469
+ const { d } = await myDashboard();
470
+ if (type === "chart" && !query)
471
+ throw new A.ActionError("a chart widget needs a query");
472
+ const y = d.widgets.reduce((m, x) => Math.max(m, x.y + x.h), 0);
473
+ const base = (id ?? title ?? type).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/đ/gi, "d").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "widget";
474
+ let wid = base;
475
+ for (let i = 2; d.widgets.some((x) => x.id === wid); i++)
476
+ wid = `${base}-${i}`;
477
+ const widget = { id: wid, type, x: 0, y, w: w ?? 6, h: h ?? 3, ...(title ? { title } : {}), ...(query ? { query: query, chart: chart ?? "bar" } : {}), ...(account ? { account } : {}), ...(period ? { period } : {}), by_ai: true };
478
+ const next = { ...d, widgets: [...d.widgets, widget] };
479
+ const shows = query ? await firstNumbers(query) : undefined;
480
+ return { ...(await preview(saveLayout(next, `Dashboard: add widget ${title ?? type} (${props.login})`))), widget, ...(shows ? { shows } : {}) };
481
+ }));
482
+ server.registerTool("edit_widget", { description: "PREVIEW changing a dashboard widget by id (title, query, chart kind, size, options).", inputSchema: z.object({ id: z.string(), title: z.string().max(80).optional(), query: queryShape.optional(), chart: z.enum(["stat", "line", "bar", "hbar", "table"]).optional(), account: z.string().optional(), period: z.string().optional(), w: z.number().int().min(1).max(12).optional(), h: z.number().int().min(1).max(24).optional() }), annotations: pv }, wrap(async ({ id, ...set }) => {
483
+ const { d } = await myDashboard();
484
+ const w = d.widgets.find((x) => x.id === id);
485
+ if (!w)
486
+ throw new A.ActionError(`no widget ${id} (ids: ${d.widgets.map((x) => x.id).join(", ")})`);
487
+ const changed = { ...w, ...Object.fromEntries(Object.entries(set).filter(([, v]) => v !== undefined)) };
488
+ if (changed.x + changed.w > GRID_COLS)
489
+ changed.x = GRID_COLS - changed.w;
490
+ const next = { ...d, widgets: d.widgets.map((x) => (x.id === id ? changed : x)) };
491
+ const shows = changed.query ? await firstNumbers(changed.query) : undefined;
492
+ return { ...(await preview(saveLayout(next, `Dashboard: edit widget ${id} (${props.login})`))), widget: changed, ...(shows ? { shows } : {}) };
493
+ }));
494
+ server.registerTool("remove_widget", { description: "PREVIEW removing a dashboard widget by id.", inputSchema: z.object({ id: z.string() }), annotations: pv }, wrap(async ({ id }) => {
495
+ const { d } = await myDashboard();
496
+ if (!d.widgets.some((x) => x.id === id))
497
+ throw new A.ActionError(`no widget ${id} (ids: ${d.widgets.map((x) => x.id).join(", ")})`);
498
+ return preview(saveLayout({ ...d, widgets: d.widgets.filter((x) => x.id !== id) }, `Dashboard: remove widget ${id} (${props.login})`));
499
+ }));
321
500
  /* ---------------------------------------------------------------- apply */
322
501
  server.registerTool("apply", {
323
502
  description: "Commit a preview, ONLY after the owner explicitly said go. Refused if the data changed since the preview.",
@@ -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 = "2.0.0";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "1.2.0";
2
+ export const VERSION = "2.0.0";