earnrate 0.1.2 → 0.1.3

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.
@@ -3,20 +3,24 @@ import { z } from 'zod';
3
3
  import { MCP_SERVER_NAME } from "../brand.js";
4
4
  import { formatCardInfo, formatNotes } from "../cli/cards.js";
5
5
  import { formatRecommendation } from "../cli/format.js";
6
+ import { formatAdditions, formatCatalogSimulation, formatExploration, } from "../cli/explore.js";
6
7
  import { formatOffers } from "../cli/offers.js";
7
8
  import { walletProblems } from "../data/integrity.js";
8
9
  import { loadWallet } from "../data/load.js";
9
10
  import { withWalletLock, writeBonusSpent, writeCapBooking, } from "../data/wallet-write.js";
10
11
  import { addCard, removeCard, setMemberships, updateCard, } from "../data/wallet-setup.js";
11
12
  import { bonusStatus, countsTowardBonus } from "../engine/bonus.js";
13
+ import { ALL_PERSONAL_CARDS, exploreCards } from "../engine/explore.js";
12
14
  import { compareOffers } from "../engine/offers.js";
15
+ import { VALUATION_PROFILES } from "../engine/profiles.js";
13
16
  import { capBooking } from "../engine/record.js";
14
17
  import { recommend } from "../engine/recommend.js";
18
+ import { resolveSpendLines, simulateAdditions, simulateCatalog, } from "../engine/simulate.js";
15
19
  import { knownMemberships, searchCards } from "../engine/setup.js";
16
20
  import { walletSummary } from "../engine/wallet-summary.js";
17
21
  import { resolveMerchant, withCallerCategory } from "../merchants/resolve.js";
18
22
  import { IsoDate } from "../schema/common.js";
19
- import { CardSearchSchema, MerchantResolutionSchema, RecommendationSchema, OfferComparisonSchema, RecordResultSchema, WalletChangeSchema, WalletSummarySchema, } from "./schemas.js";
23
+ import { CardSearchSchema, ExplorationSchema, MerchantResolutionSchema, SpendingSimulationSchema, RecommendationSchema, OfferComparisonSchema, RecordResultSchema, WalletChangeSchema, WalletSummarySchema, } from "./schemas.js";
20
24
  const Merchant = z
21
25
  .string()
22
26
  .min(1)
@@ -26,7 +30,7 @@ const ChannelInput = z
26
30
  .optional()
27
31
  .describe('How the purchase is made. Omit if unknown; the answer says what it assumed.');
28
32
  const DateInput = IsoDate.optional().describe('Purchase date, YYYY-MM-DD. Defaults to today.');
29
- const INSTRUCTIONS = `earnrate picks which of the user's credit cards earns the most for a purchase. Its wallet lists the cards they hold by product id, never card numbers; never ask for card numbers, expiry dates or security codes.
33
+ const INSTRUCTIONS = `earnrate picks which of the user's credit cards earns the most for a purchase. best_cards_for and simulate_spending compare every card earnrate knows and need no wallet, for questions like "what's the best grocery card?" or "which cards fit my spending?". Its wallet lists the cards they hold by product id, never card numbers; never ask for card numbers, expiry dates or security codes.
30
34
 
31
35
  If a tool says there's no wallet yet, ask the user which cards they have, find each with search_cards, and add it with add_card. add_card and update_card reply with what a card still needs, such as category picks, memberships like Amazon Prime, or activated bonus categories. Ask the user about those and set them with update_card or set_memberships.`;
32
36
  const fail = (text) => ({
@@ -211,6 +215,153 @@ export function createEarnrateServer(deps) {
211
215
  structuredContent: comparison,
212
216
  };
213
217
  });
218
+ const CatalogCategory = z
219
+ .enum(ids)
220
+ .describe(`A spending category: ${catalog.categories.map((c) => `${c.id} (${c.name})`).join(', ')}.`);
221
+ const issuers = [...new Set(catalog.cards.map((c) => c.issuer))].sort();
222
+ const membershipIds = knownMemberships(catalog);
223
+ const CatalogFilters = {
224
+ kind: z
225
+ .enum(['any', 'cash', 'points'])
226
+ .optional()
227
+ .describe('cash: cash back cards only. points: points and miles cards only.'),
228
+ noAnnualFee: z
229
+ .boolean()
230
+ .optional()
231
+ .describe('Only cards with no annual fee.'),
232
+ business: z
233
+ .boolean()
234
+ .optional()
235
+ .describe('Business cards instead of personal ones.'),
236
+ issuer: z.enum(issuers).optional().describe("Only this issuer's cards."),
237
+ memberships: z
238
+ .array(z.enum(membershipIds))
239
+ .optional()
240
+ .describe("Memberships the user has, such as amazon-prime. Rates that need one they don't have are listed separately."),
241
+ valuation: z
242
+ .enum(['flat', 'points-heavy'])
243
+ .optional()
244
+ .describe('flat (default): points at their cash-out value, about 1¢. points-heavy: Amex MR and Chase UR at 1.7¢, for people who transfer points to airlines and hotels.'),
245
+ };
246
+ const settings = (args) => ({
247
+ filters: {
248
+ ...ALL_PERSONAL_CARDS,
249
+ kind: args.kind ?? 'any',
250
+ noAnnualFee: args.noAnnualFee ?? false,
251
+ business: args.business ?? false,
252
+ issuer: args.issuer ?? null,
253
+ },
254
+ memberships: args.memberships ?? [],
255
+ valuations: args.valuation ? VALUATION_PROFILES[args.valuation] : {},
256
+ });
257
+ server.registerTool('best_cards_for', {
258
+ title: 'Best cards for a purchase',
259
+ description: 'Ranks every card earnrate knows, not only the user\'s, for one purchase or category, each set up at its best (the right category pick, activated, cap unused), with its annual fee and what earning the rate takes. Use it for questions like "what\'s the best card for groceries?" or "which card should I get for Amazon?". It needs no wallet. For which of the user\'s own cards to use, call best_card_for_purchase instead. Mention the annual fee and any conditions alongside each card.',
260
+ inputSchema: z.object({
261
+ merchant: Merchant.optional(),
262
+ category: CatalogCategory.optional(),
263
+ amount: z
264
+ .number()
265
+ .positive()
266
+ .optional()
267
+ .describe('Purchase amount in US dollars, if known.'),
268
+ channel: ChannelInput,
269
+ ...CatalogFilters,
270
+ }),
271
+ outputSchema: ExplorationSchema,
272
+ annotations: { readOnlyHint: true, openWorldHint: false },
273
+ }, (args) => {
274
+ if (args.merchant === undefined && args.category === undefined)
275
+ return fail('Give a merchant or a category.');
276
+ const result = exploreCards(catalog, {
277
+ merchant: args.merchant ?? null,
278
+ category: args.merchant === undefined ? (args.category ?? null) : null,
279
+ amount: args.amount ?? null,
280
+ channel: args.channel ?? null,
281
+ date: deps.today(),
282
+ }, settings(args));
283
+ const trimmed = { ...result, ranked: result.ranked.slice(0, 10) };
284
+ return {
285
+ content: [{ type: 'text', text: formatExploration(trimmed, true) }],
286
+ structuredContent: trimmed,
287
+ };
288
+ });
289
+ server.registerTool('simulate_spending', {
290
+ title: 'Simulate a year of spending',
291
+ description: 'Spends the user\'s monthly amounts for a year across every card earnrate knows, and ranks single cards and two-card pairs by rewards minus annual fees. With compareToWallet, it starts from the user\'s wallet and ranks the cards that would add the most to it. Use it for "which card fits my spending?" or "is it worth adding a card?". Ask for rough monthly amounts if the user hasn\'t given them. It leaves out welcome bonuses.',
292
+ inputSchema: z.object({
293
+ spending: z
294
+ .array(z.object({
295
+ merchant: Merchant.optional(),
296
+ category: CatalogCategory.optional(),
297
+ monthly: z.number().positive().describe('US dollars a month.'),
298
+ }))
299
+ .min(1)
300
+ .describe('Monthly spending lines, each a category (grocery.supermarket, dining, gas, other) or a merchant (Amazon, Costco).'),
301
+ compareToWallet: z
302
+ .boolean()
303
+ .optional()
304
+ .describe("Rank the cards that would add the most to the user's wallet."),
305
+ ...CatalogFilters,
306
+ }),
307
+ outputSchema: SpendingSimulationSchema,
308
+ annotations: { readOnlyHint: true, openWorldHint: false },
309
+ }, async (args) => {
310
+ if (args.spending.some((l) => l.merchant === undefined && l.category === undefined))
311
+ return fail('Each spending line needs a merchant or a category.');
312
+ const lines = resolveSpendLines(catalog, args.spending.map((l) => ({
313
+ merchant: l.merchant ?? null,
314
+ category: l.merchant === undefined ? (l.category ?? null) : null,
315
+ monthly: l.monthly,
316
+ })));
317
+ const unknown = lines.filter((l) => l.merchant.source === 'none');
318
+ if (unknown.length > 0)
319
+ return fail(`earnrate doesn't know ${unknown.map((l) => `"${l.merchant.input}"`).join(', ')}. Give a category for those lines instead.`);
320
+ const options = { ...settings(args), start: deps.today() };
321
+ if (args.compareToWallet) {
322
+ const w = await wallet();
323
+ if (typeof w === 'string')
324
+ return fail(w);
325
+ const valued = args.valuation
326
+ ? {
327
+ ...w,
328
+ valuations: {
329
+ ...w.valuations,
330
+ ...VALUATION_PROFILES[args.valuation],
331
+ },
332
+ }
333
+ : w;
334
+ const result = simulateAdditions(catalog, valued, lines, options);
335
+ return {
336
+ content: [
337
+ { type: 'text', text: formatAdditions(result, catalog, false) },
338
+ ],
339
+ structuredContent: {
340
+ singles: [],
341
+ pairs: [],
342
+ current: result.current,
343
+ additions: result.additions
344
+ .slice(0, 10)
345
+ .map(({ simulation: _, ...a }) => a),
346
+ },
347
+ };
348
+ }
349
+ const result = simulateCatalog(catalog, lines, options);
350
+ return {
351
+ content: [
352
+ {
353
+ type: 'text',
354
+ text: formatCatalogSimulation(result, catalog, false),
355
+ },
356
+ ],
357
+ structuredContent: {
358
+ singles: result.singles.slice(0, 10),
359
+ pairs: result.pairs.slice(0, 5),
360
+ current: null,
361
+ additions: [],
362
+ },
363
+ };
364
+ });
214
365
  server.registerTool('record_purchase', {
215
366
  title: 'Record a purchase',
216
367
  description: "Records a purchase the user has already made, so spending caps and welcome-bonus progress stay accurate for future recommendations. It updates the user's wallet file. Only call it after the purchase has happened, and only once per purchase: calling it twice counts the spend twice. Purchases with no cap and no open welcome bonus are acknowledged and nothing is written.",
@@ -441,14 +592,13 @@ export function createEarnrateServer(deps) {
441
592
  openWorldHint: false,
442
593
  },
443
594
  }, ({ cardId }) => withWalletLock(deps.walletFile, async () => changed(await removeCard(deps.walletFile, catalog, cardId), `Removed ${cardName(cardId)} (${cardId}).`, false)));
444
- const memberships = knownMemberships(catalog);
445
595
  server.registerTool('set_memberships', {
446
596
  title: 'Set memberships',
447
597
  description: "Sets the memberships that unlock some cards' rates, such as amazon-prime for Prime Visa's 5% or a Bank of America Preferred Rewards tier. Replaces the whole list, so include the ones to keep.",
448
598
  inputSchema: z.object({
449
599
  memberships: z
450
- .array(z.enum(memberships))
451
- .describe(`Every membership the user has. Known: ${memberships.join(', ')}.`),
600
+ .array(z.enum(membershipIds))
601
+ .describe(`Every membership the user has. Known: ${membershipIds.join(', ')}.`),
452
602
  }),
453
603
  outputSchema: WalletChangeSchema,
454
604
  annotations: {
@@ -133,6 +133,8 @@ export const CardSchema = z
133
133
  source_urls: z.array(z.url()).min(1),
134
134
  base_rate: z.number().nonnegative(),
135
135
  business: z.boolean().default(false),
136
+ // When the issuer stopped taking applications; cardholders keep earning.
137
+ applications_closed: IsoDate.optional(),
136
138
  annual_fee: z.number().nonnegative().optional(), // dollars
137
139
  // When the first year differs, usually a waived fee.
138
140
  first_year_fee: z.number().nonnegative().optional(),
@@ -6,6 +6,8 @@ export const CategorySchema = z.strictObject({
6
6
  // Typical MCCs, as hints for explanations and the LLM fallback. Matching is
7
7
  // by category, not by these.
8
8
  mccs: z.array(Mcc).default([]),
9
+ // Everyday words people search by ("groceries"), besides the name.
10
+ aliases: z.array(z.string().min(1)).default([]),
9
11
  note: z.string().optional(),
10
12
  });
11
13
  export const CategoriesFileSchema = z.array(CategorySchema).min(1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "earnrate",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Picks the best credit card from your wallet for a merchant, and explains why",
5
5
  "keywords": [
6
6
  "credit cards",
@@ -40,11 +40,13 @@
40
40
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
41
41
  "prepack": "yarn build",
42
42
  "smoke:pack": "node scripts/smoke-pack.ts",
43
- "site:deploy": "WRANGLER_SEND_METRICS=false wrangler deploy",
43
+ "site:build": "vite build site",
44
+ "site:dev": "vite site",
45
+ "site:deploy": "yarn site:build && WRANGLER_SEND_METRICS=false wrangler deploy",
44
46
  "test": "vitest run",
45
47
  "test:watch": "vitest",
46
48
  "coverage": "vitest run --coverage --coverage.include=src/**",
47
- "typecheck": "tsc",
49
+ "typecheck": "tsc && tsc -p site",
48
50
  "lint": "eslint",
49
51
  "format": "prettier --write .",
50
52
  "format:check": "prettier --check .",
@@ -64,6 +66,7 @@
64
66
  "eslint": "^10.13.0",
65
67
  "eslint-config-prettier": "^10.1.8",
66
68
  "playwright": "1.64.1",
69
+ "preact": "^10.29.8",
67
70
  "prettier": "^3.9.10",
68
71
  "typescript": "~6.0.3",
69
72
  "typescript-eslint": "^8.72.0",