1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
|
import Anthropic from "@anthropic-ai/sdk"
import * as actualApi from "@actual-app/api"
import * as p from "@clack/prompts"
import { loadConfig } from "../config"
import { initActual } from "../actual"
import type { Config } from "../config"
const api = actualApi as any
export async function aiCommand(args: string[]) {
const config = loadConfig()
if (!config.anthropicApiKey) {
console.error("Error: No Anthropic API key configured. Run `sb1-actual init` to add one.")
process.exit(1)
}
const subcommand = args[0]
if (!subcommand) {
printHelp()
process.exit(1)
}
const client = new Anthropic({ apiKey: config.anthropicApiKey })
p.intro(`sb1-actual ai ${subcommand}`)
await initActual(config.actual)
switch (subcommand) {
case "consolidate-payees":
await consolidatePayees(client)
break
case "summarize":
await summarize(client, config, args.slice(1))
break
case "insights":
await insights(client, config, args.slice(1))
break
case "add-notes":
await addNotes(client, config, args.slice(1))
break
case "query":
await query(client, config, args.slice(1))
break
default:
console.error(`Unknown subcommand: ${subcommand}`)
printHelp()
process.exit(1)
}
}
function printHelp() {
console.log("Usage: sb1-actual ai <subcommand> [options]")
console.log("")
console.log("Subcommands:")
console.log(" query [--since=YYYY-MM-DD] [question] Ask a free-form question about your data")
console.log(" consolidate-payees Identify and merge duplicate/similar payees")
console.log(" summarize [--since=YYYY-MM-DD] Summarize spending by category and payee")
console.log(" insights [--since=YYYY-MM-DD] Get AI insights into spending patterns")
console.log(" add-notes [--since=YYYY-MM-DD] Add descriptive notes to transactions")
console.log(" add-notes --dry-run Preview notes without applying them")
}
function extractJson(text: string): any {
// Strip markdown code fences: ```json ... ``` or ``` ... ```
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/)
const raw = fenced ? fenced[1] : text
// Find the first [...] or {...} block
const match = raw.match(/(\[[\s\S]*\]|\{[\s\S]*\})/)
if (!match) throw new Error("No JSON found in response")
return JSON.parse(match[1])
}
function defaultSince(): string {
const d = new Date()
d.setDate(d.getDate() - 90)
return d.toISOString().split("T")[0]
}
async function loadTransactions(config: Config, since?: string) {
const startDate = since ?? defaultSince()
const allTxns: any[] = []
for (const mapping of config.mappings) {
const txns = await api.getTransactions(mapping.actualId, startDate, undefined)
allTxns.push(...txns)
}
return allTxns
}
async function resolveNames(transactions: any[]) {
const payees: Array<{ id: string; name: string }> = await api.getPayees()
const categories: Array<{ id: string; name: string }> = await api.getCategories()
const payeeMap = new Map(payees.map(p => [p.id, p.name]))
const categoryMap = new Map(categories.map(c => [c.id, c.name]))
return {
payees,
payeeMap,
categoryMap,
formatted: transactions
.filter(t => !t.is_parent)
.map(t => ({
id: t.id,
date: t.date,
amount: (t.amount / 100).toFixed(2),
payee: payeeMap.get(t.payee) ?? t.imported_payee ?? "Unknown",
category: categoryMap.get(t.category) ?? "Uncategorized",
notes: t.notes ?? "",
})),
}
}
// ─── consolidate-payees ────────────────────────────────────────────────────
async function consolidatePayees(client: Anthropic) {
const spinner = p.spinner()
spinner.start("Loading payees...")
const payees: Array<{ id: string; name: string; transfer_acct?: string }> = await api.getPayees()
const realPayees = payees.filter(p => !p.transfer_acct && p.name?.trim())
spinner.stop(`Loaded ${realPayees.length} payees`)
if (realPayees.length === 0) {
p.outro("No payees found.")
return
}
spinner.start("Analyzing payees with Claude...")
const payeeList = realPayees.map(p => `${p.id}: ${p.name}`).join("\n")
const response = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 4096,
tools: [{
name: "submit_merge_groups",
description: "Submit groups of payees that should be merged together",
input_schema: {
type: "object" as const,
properties: {
groups: {
type: "array",
items: {
type: "object",
properties: {
keepId: { type: "string", description: "ID of the payee whose name to keep" },
keepName: { type: "string", description: "The canonical display name" },
mergeIds: { type: "array", items: { type: "string" }, description: "IDs to merge in" },
},
required: ["keepId", "keepName", "mergeIds"],
},
description: "Merge groups. Empty array if no duplicates found.",
},
},
required: ["groups"],
},
}],
tool_choice: { type: "tool", name: "submit_merge_groups" },
system: "You are a personal finance assistant. Identify payees that represent the same merchant (e.g. 'Rema 1000', 'REMA 1000 OSLO', 'REMA1000'). Only group clear duplicates/variants.",
messages: [{
role: "user",
content: `Payees:\n${payeeList}`,
}]
})
spinner.stop("Analysis complete")
const toolUse = response.content.find(b => b.type === "tool_use") as any
const groups: Array<{ keepId: string; keepName: string; mergeIds: string[] }> =
toolUse?.input?.groups?.filter((g: any) => g.mergeIds?.length > 0) ?? []
if (groups.length === 0) {
p.outro("No duplicate or similar payees found.")
return
}
console.log(`\nFound ${groups.length} merge group(s):\n`)
for (const group of groups) {
const keep = realPayees.find(p => p.id === group.keepId)
const merging = group.mergeIds.map(id => realPayees.find(p => p.id === id)?.name ?? id)
console.log(` Keep: "${keep?.name ?? group.keepName}"`)
console.log(` Merge: ${merging.map(n => `"${n}"`).join(", ")}`)
console.log()
}
const confirm = await p.confirm({ message: "Apply these merges?" })
if (p.isCancel(confirm) || !confirm) {
p.cancel("Cancelled.")
return
}
const applySpinner = p.spinner()
applySpinner.start("Applying merges...")
let mergedCount = 0
for (const group of groups) {
await api.mergePayees(group.keepId, group.mergeIds)
mergedCount += group.mergeIds.length
}
await actualApi.sync()
applySpinner.stop(`Merged ${mergedCount} payees into ${groups.length} groups`)
p.outro("Done!")
}
// ─── summarize ────────────────────────────────────────────────────────────
async function summarize(client: Anthropic, config: Config, args: string[]) {
const since = args.find(a => a.startsWith("--since="))?.split("=")[1]
const spinner = p.spinner()
spinner.start("Loading transactions...")
const transactions = await loadTransactions(config, since)
const { formatted } = await resolveNames(transactions)
spinner.stop(`Loaded ${formatted.length} transactions`)
if (formatted.length === 0) {
p.outro("No transactions found.")
return
}
const txnText = formatted
.map(t => `${t.date} | ${Number(t.amount) >= 0 ? "+" : ""}${t.amount} NOK | ${t.payee} | ${t.category}${t.notes ? ` | ${t.notes}` : ""}`)
.join("\n")
console.log("")
const stream = client.messages.stream({
model: "claude-haiku-4-5",
max_tokens: 4096,
system: "You are a personal finance assistant. Summarize transaction data clearly. Group by category and list top payees with totals. Use NOK currency. Use markdown formatting.",
messages: [{
role: "user",
content: `Summarize my spending${since ? ` since ${since}` : ` (last 90 days)`}.\n\nTransactions:\n${txnText}`
}]
})
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text)
}
}
console.log("\n")
p.outro("Done!")
}
// ─── insights ─────────────────────────────────────────────────────────────
async function insights(client: Anthropic, config: Config, args: string[]) {
const since = args.find(a => a.startsWith("--since="))?.split("=")[1]
const spinner = p.spinner()
spinner.start("Loading transactions...")
const transactions = await loadTransactions(config, since)
const { formatted } = await resolveNames(transactions)
spinner.stop(`Loaded ${formatted.length} transactions`)
if (formatted.length === 0) {
p.outro("No transactions found.")
return
}
const txnText = formatted
.map(t => `${t.date} | ${Number(t.amount) >= 0 ? "+" : ""}${t.amount} NOK | ${t.payee} | ${t.category}${t.notes ? ` | ${t.notes}` : ""}`)
.join("\n")
console.log("")
const stream = client.messages.stream({
model: "claude-haiku-4-5",
max_tokens: 8192,
system: "You are a personal finance advisor. Analyze transactions and give actionable insights: spending patterns, trends, anomalies, potential savings, and notable observations. Use NOK currency. Use markdown. Be specific and helpful.",
messages: [{
role: "user",
content: `Analyze my spending${since ? ` since ${since}` : ` (last 90 days)`} and give me insights.\n\nTransactions:\n${txnText}`
}]
})
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text)
}
}
console.log("\n")
p.outro("Done!")
}
// ─── add-notes ────────────────────────────────────────────────────────────
async function addNotes(client: Anthropic, config: Config, args: string[]) {
const since = args.find(a => a.startsWith("--since="))?.split("=")[1]
const dryRun = args.includes("--dry-run")
const spinner = p.spinner()
spinner.start("Loading transactions...")
const transactions = await loadTransactions(config, since)
const { payeeMap } = await resolveNames(transactions)
const withoutNotes = transactions
.filter(t => !t.is_parent && (!t.notes || !t.notes.trim()))
.slice(0, 50)
spinner.stop(`Found ${withoutNotes.length} transactions without notes (processing up to 50)`)
if (withoutNotes.length === 0) {
p.outro("All transactions already have notes!")
return
}
const toProcess = withoutNotes.map(t => ({
id: t.id,
date: t.date,
amount: (t.amount / 100).toFixed(2),
payee: payeeMap.get(t.payee) ?? t.imported_payee ?? "Unknown",
}))
spinner.start("Generating notes with Claude...")
const response = await client.messages.create({
model: "claude-haiku-4-5",
max_tokens: 4096,
system: `You are a personal finance assistant. For each transaction, suggest a brief helpful note (max 60 chars) adding context not obvious from the payee name alone.
If the transaction is already self-explanatory, return null for the note.
Return ONLY a JSON array: [{"id": "...", "note": "..." | null}]`,
messages: [{
role: "user",
content: `Add helpful notes to these transactions:\n${JSON.stringify(toProcess, null, 2)}`
}]
})
spinner.stop("Notes generated")
const text = response.content.find(b => b.type === "text") as any
const rawText = text?.text ?? ""
let suggestions: Array<{ id: string; note: string | null }> = []
try {
suggestions = extractJson(rawText)
} catch {
console.error("Failed to parse Claude's response:")
console.log(rawText)
return
}
const toUpdate = suggestions.filter(s => s.note !== null && s.note?.trim())
if (toUpdate.length === 0) {
p.outro("No notes to add — all transactions are self-explanatory.")
return
}
console.log(`\nWill add notes to ${toUpdate.length} transaction(s):`)
const preview = toUpdate.slice(0, 10)
for (const s of preview) {
const t = toProcess.find(f => f.id === s.id)
console.log(` ${t?.date} ${t?.payee}: "${s.note}"`)
}
if (toUpdate.length > 10) console.log(` ... and ${toUpdate.length - 10} more`)
if (dryRun) {
console.log("\nDry run — no changes applied.")
p.outro("Done!")
return
}
const confirm = await p.confirm({ message: `Apply ${toUpdate.length} note(s)?` })
if (p.isCancel(confirm) || !confirm) {
p.cancel("Cancelled.")
return
}
const applySpinner = p.spinner()
applySpinner.start("Applying notes...")
for (const s of toUpdate) {
await api.updateTransaction(s.id, { notes: s.note })
}
await actualApi.sync()
applySpinner.stop(`Added notes to ${toUpdate.length} transactions`)
p.outro("Done!")
}
// ─── query ────────────────────────────────────────────────────────────────
async function query(client: Anthropic, config: Config, args: string[]) {
const since = args.find(a => a.startsWith("--since="))?.split("=")[1]
const inlineQuestion = args.filter(a => !a.startsWith("--")).join(" ").trim()
const question = inlineQuestion || (await p.text({
message: "What do you want to know about your transactions?",
placeholder: "e.g. How much did I spend on groceries last month?",
validate: v => v?.trim() ? undefined : "Please enter a question",
}) as string)
if (p.isCancel(question)) {
p.cancel("Cancelled.")
return
}
const spinner = p.spinner()
spinner.start("Loading transactions...")
const transactions = await loadTransactions(config, since)
const { formatted } = await resolveNames(transactions)
spinner.stop(`Loaded ${formatted.length} transactions`)
if (formatted.length === 0) {
p.outro("No transactions found.")
return
}
const txnText = formatted
.map(t => `${t.date} | ${Number(t.amount) >= 0 ? "+" : ""}${t.amount} NOK | ${t.payee} | ${t.category}${t.notes ? ` | ${t.notes}` : ""}`)
.join("\n")
console.log("")
const stream = client.messages.stream({
model: "claude-haiku-4-5",
max_tokens: 4096,
system: "You are a personal finance assistant with access to the user's transaction data. Answer questions clearly and concisely. Use NOK currency. Use markdown where helpful.",
messages: [{
role: "user",
content: `My transactions${since ? ` since ${since}` : ` (last 90 days)`}:\n\n${txnText}\n\n${question}`,
}]
})
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text)
}
}
console.log("\n")
p.outro("Done!")
}
|