ownledger 0.0.1 → 1.1.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 (94) hide show
  1. package/AGENTS.md +94 -0
  2. package/CHANGELOG.md +30 -0
  3. package/LICENSE +21 -0
  4. package/README.md +101 -1
  5. package/assets/_headers +5 -0
  6. package/assets/app.css +61 -0
  7. package/assets/app.js +369 -0
  8. package/assets/icon.svg +1 -0
  9. package/assets/index.html +30 -0
  10. package/assets/manifest.webmanifest +1 -0
  11. package/dist/cli/check.d.ts +3 -0
  12. package/dist/cli/check.js +21 -0
  13. package/dist/cli/deploy.d.ts +1 -0
  14. package/dist/cli/deploy.js +258 -0
  15. package/dist/cli/dev.d.ts +3 -0
  16. package/dist/cli/dev.js +107 -0
  17. package/dist/cli/import.d.ts +3 -0
  18. package/dist/cli/import.js +151 -0
  19. package/dist/cli/index.d.ts +2 -0
  20. package/dist/cli/index.js +47 -0
  21. package/dist/cli/init.d.ts +1 -0
  22. package/dist/cli/init.js +73 -0
  23. package/dist/cli/jsonc.d.ts +2 -0
  24. package/dist/cli/jsonc.js +39 -0
  25. package/dist/engine/actions.d.ts +61 -0
  26. package/dist/engine/actions.js +227 -0
  27. package/dist/engine/balances.d.ts +30 -0
  28. package/dist/engine/balances.js +75 -0
  29. package/dist/engine/categories.d.ts +17 -0
  30. package/dist/engine/categories.js +35 -0
  31. package/dist/engine/check.d.ts +11 -0
  32. package/dist/engine/check.js +229 -0
  33. package/dist/engine/dates.d.ts +15 -0
  34. package/dist/engine/dates.js +56 -0
  35. package/dist/engine/defaults.d.ts +2 -0
  36. package/dist/engine/defaults.js +61 -0
  37. package/dist/engine/index.d.ts +13 -0
  38. package/dist/engine/index.js +13 -0
  39. package/dist/engine/load.d.ts +23 -0
  40. package/dist/engine/load.js +129 -0
  41. package/dist/engine/networth.d.ts +12 -0
  42. package/dist/engine/networth.js +73 -0
  43. package/dist/engine/registry.d.ts +24 -0
  44. package/dist/engine/registry.js +41 -0
  45. package/dist/engine/reports.d.ts +68 -0
  46. package/dist/engine/reports.js +149 -0
  47. package/dist/engine/schedules.d.ts +75 -0
  48. package/dist/engine/schedules.js +208 -0
  49. package/dist/engine/types.d.ts +132 -0
  50. package/dist/engine/types.js +2 -0
  51. package/dist/engine/write.d.ts +30 -0
  52. package/dist/engine/write.js +105 -0
  53. package/dist/import/hash.d.ts +1 -0
  54. package/dist/import/hash.js +17 -0
  55. package/dist/import/index.d.ts +6 -0
  56. package/dist/import/index.js +6 -0
  57. package/dist/import/mapping.d.ts +96 -0
  58. package/dist/import/mapping.js +54 -0
  59. package/dist/import/profile.d.ts +39 -0
  60. package/dist/import/profile.js +125 -0
  61. package/dist/import/run.d.ts +101 -0
  62. package/dist/import/run.js +416 -0
  63. package/dist/import/workbook.d.ts +13 -0
  64. package/dist/import/workbook.js +168 -0
  65. package/dist/import/xlsx-write.d.ts +6 -0
  66. package/dist/import/xlsx-write.js +38 -0
  67. package/dist/node/files.d.ts +3 -0
  68. package/dist/node/files.js +26 -0
  69. package/dist/node/scaffold.d.ts +14 -0
  70. package/dist/node/scaffold.js +45 -0
  71. package/dist/worker/api.d.ts +3 -0
  72. package/dist/worker/api.js +139 -0
  73. package/dist/worker/auth.d.ts +11 -0
  74. package/dist/worker/auth.js +182 -0
  75. package/dist/worker/env.d.ts +27 -0
  76. package/dist/worker/env.js +6 -0
  77. package/dist/worker/github.d.ts +29 -0
  78. package/dist/worker/github.js +154 -0
  79. package/dist/worker/index.d.ts +5 -0
  80. package/dist/worker/index.js +64 -0
  81. package/dist/worker/mcp.d.ts +4 -0
  82. package/dist/worker/mcp.js +301 -0
  83. package/dist/worker/store.d.ts +42 -0
  84. package/dist/worker/store.js +92 -0
  85. package/dist/worker/tar.d.ts +2 -0
  86. package/dist/worker/tar.js +62 -0
  87. package/dist/worker/version.d.ts +1 -0
  88. package/dist/worker/version.js +2 -0
  89. package/package.json +66 -4
  90. package/presets/misa.mapping.yaml +48 -0
  91. package/templates/repo/.github/dependabot.yml +11 -0
  92. package/templates/repo/.github/workflows/check.yml +15 -0
  93. package/templates/repo/.github/workflows/deploy.yml +21 -0
  94. package/templates/repo/README.md +10 -0
@@ -0,0 +1,5 @@
1
+ import type { Env } from "./env.js";
2
+ declare const _default: {
3
+ fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
4
+ };
5
+ export default _default;
@@ -0,0 +1,64 @@
1
+ import { OAuthProvider } from "@cloudflare/workers-oauth-provider";
2
+ import { createMcpHandler } from "@modelcontextprotocol/server";
3
+ import { api } from "./api.js";
4
+ import { authorizeGet, authorizePost, dashboardCallback, dashboardLogin, dashboardLogout, oauthCallback } from "./auth.js";
5
+ import { allowed } from "./env.js";
6
+ import { buildServer } from "./mcp.js";
7
+ /** /mcp: reached only with a valid access token; ctx.props is what sign-in stored. */
8
+ const mcpHandler = {
9
+ async fetch(request, env, ctx) {
10
+ const props = ctx.props;
11
+ if (!props?.login || !allowed(env, props.login))
12
+ return new Response("forbidden", { status: 403 });
13
+ const handler = createMcpHandler(() => buildServer(env, props));
14
+ return handler.fetch(request);
15
+ },
16
+ };
17
+ const defaultHandler = {
18
+ async fetch(request, env) {
19
+ const url = new URL(request.url);
20
+ const p = url.pathname;
21
+ if (p === "/authorize")
22
+ return request.method === "POST" ? authorizePost(request, env) : authorizeGet(request, env);
23
+ if (p === "/oauth/callback")
24
+ return oauthCallback(request, env);
25
+ if (p === "/auth/login")
26
+ return dashboardLogin(request, env);
27
+ if (p === "/auth/callback")
28
+ return dashboardCallback(request, env);
29
+ if (p === "/auth/logout" && request.method === "POST")
30
+ return dashboardLogout();
31
+ if (p.startsWith("/api/"))
32
+ return api(request, env);
33
+ if (env.ASSETS)
34
+ return env.ASSETS.fetch(request);
35
+ return new Response("ownledger", { status: 200 });
36
+ },
37
+ };
38
+ function provider(env) {
39
+ const origin = env.PUBLIC_URL.replace(/\/$/, "");
40
+ return new OAuthProvider({
41
+ apiRoute: "/mcp",
42
+ apiHandler: mcpHandler,
43
+ defaultHandler: defaultHandler,
44
+ authorizeEndpoint: "/authorize",
45
+ tokenEndpoint: "/oauth/token",
46
+ clientRegistrationEndpoint: "/oauth/register",
47
+ scopesSupported: ["ledger", "offline_access"],
48
+ requiredScopes: ["ledger"],
49
+ resourceMetadata: { resource: `${origin}/mcp`, authorization_servers: [origin] },
50
+ accessTokenTTL: 60 * 60, // 1 hour
51
+ refreshTokenTTL: 60 * 60 * 24 * 30, // 30 days; revocable from the dashboard
52
+ });
53
+ }
54
+ // One provider per isolate, built on the first request (its URLs come from the Worker's vars).
55
+ let cached = null;
56
+ export default {
57
+ fetch(request, env, ctx) {
58
+ if (!env.PUBLIC_URL)
59
+ return Promise.resolve(new Response("ownledger: PUBLIC_URL is not set (run `ownledger deploy`)", { status: 500 }));
60
+ if (!cached || cached.url !== env.PUBLIC_URL)
61
+ cached = { url: env.PUBLIC_URL, p: provider(env) };
62
+ return cached.p.fetch(request, env, ctx);
63
+ },
64
+ };
@@ -0,0 +1,4 @@
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
+ import type { Env, Props } from "./env.js";
3
+ import { type DataSource } from "./store.js";
4
+ export declare function buildServer(env: Env, props: Props, src?: DataSource): McpServer;
@@ -0,0 +1,301 @@
1
+ import { McpServer } from "@modelcontextprotocol/server";
2
+ import { z } from "zod";
3
+ import * as A from "../engine/actions.js";
4
+ import { accountValues } from "../engine/balances.js";
5
+ import { flattenCategories, SYSTEM_CATEGORIES } from "../engine/categories.js";
6
+ import { addMonths, todayIn } from "../engine/dates.js";
7
+ import { netWorth, netWorthSeries } from "../engine/networth.js";
8
+ import { typeDef } from "../engine/registry.js";
9
+ import { queryTransactions, report } from "../engine/reports.js";
10
+ import { cards, deposits, planStatus, plansDue, today } from "../engine/schedules.js";
11
+ import { MainMovedError } from "./github.js";
12
+ import { applyPending, savePending, snapshot, sourceFor } from "./store.js";
13
+ import { VERSION } from "./version.js";
14
+ const out = (v) => ({ content: [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v) }] });
15
+ const fail = (msg) => ({ content: [{ type: "text", text: msg }], isError: true });
16
+ const INSTRUCTIONS = `ownledger: the owner's personal finance ledger, kept in their private GitHub repo.
17
+ 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
+ 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.`;
19
+ function compactTx(t) {
20
+ return {
21
+ id: t.id,
22
+ date: t.date,
23
+ ...(t.time ? { time: t.time } : {}),
24
+ note: t.note ?? "",
25
+ ...(t.who ? { who: t.who } : {}),
26
+ ...(t.event ? { event: t.event } : {}),
27
+ ...(t.tags?.length ? { tags: t.tags } : {}),
28
+ ...(t.plan ? { plan: t.plan } : {}),
29
+ ...(t.void ? { void: true } : {}),
30
+ ...(t.trail?.length ? { reason: t.trail[t.trail.length - 1].reason } : {}),
31
+ lines: t.lines.map((l) => [l.account ?? l.category, l.amount, ...(l.qty !== undefined ? [`${l.qty} ${l.asset ?? ""}`.trim()] : [])]),
32
+ };
33
+ }
34
+ const lineSchema = z.object({
35
+ account: z.string().optional(),
36
+ category: z.string().optional(),
37
+ amount: z.number().int(),
38
+ asset: z.string().optional(),
39
+ qty: z.number().optional(),
40
+ });
41
+ const txFields = {
42
+ date: z.string().describe("yyyy-mm-dd"),
43
+ time: z.string().optional().describe("HH:MM"),
44
+ note: z.string().optional(),
45
+ kind: z.enum(["expense", "income", "transfer"]).optional().describe("simple form; or give lines"),
46
+ amount: z.number().int().positive().optional().describe("simple form: positive, whole base-currency units"),
47
+ account: z.string().optional().describe("expense: paid from; income: received into; transfer: from"),
48
+ to_account: z.string().optional().describe("transfer: to"),
49
+ category: z.string().optional().describe("category path, e.g. food/eating-out"),
50
+ lines: z.array(lineSchema).optional().describe("full form: balanced lines (sum 0); for splits, assets with qty, etc."),
51
+ who: z.string().optional(),
52
+ event: z.string().optional(),
53
+ tags: z.array(z.string()).optional(),
54
+ plan: z.string().optional().describe("plan id this pays (instalment, loan, premium)"),
55
+ };
56
+ const reason = z
57
+ .string()
58
+ .trim()
59
+ .min(3)
60
+ .max(A.REASON_MAX)
61
+ .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 });
64
+ const tz = env.TIMEZONE || "Asia/Ho_Chi_Minh";
65
+ const now = () => todayIn(tz);
66
+ const snap = () => snapshot(env, src);
67
+ const ro = { readOnlyHint: true, openWorldHint: false };
68
+ const meta = (reason) => ({ via: "mcp", ...(props.client ? { client: props.client } : {}), reason });
69
+ const wrap = (fn) => async (args) => {
70
+ try {
71
+ return out(await fn(args));
72
+ }
73
+ catch (e) {
74
+ if (e instanceof A.ActionError || e instanceof MainMovedError)
75
+ return fail(e.message);
76
+ return fail(`error: ${e.message}`);
77
+ }
78
+ };
79
+ const preview = async (build) => {
80
+ const s = await snap();
81
+ const p = build(s.files);
82
+ const id = await savePending(env, { baseSha: s.sha, files: p.files, message: p.message, summary: p.summary, created: new Date().toISOString() });
83
+ const shown = [];
84
+ for (const t of [...(p.change.addTransactions ?? []), ...(p.change.replaceTransactions ?? [])].slice(0, 20))
85
+ shown.push(compactTx(t));
86
+ return {
87
+ preview_id: id,
88
+ will: p.summary,
89
+ commit_message: p.message,
90
+ ...(shown.length ? { transactions: shown } : {}),
91
+ ...(p.warnings.length ? { warnings: p.warnings.map((w) => w.message) } : {}),
92
+ next: "Show this to the owner. Only after their explicit go, call apply with this preview_id.",
93
+ };
94
+ };
95
+ /* ---------------------------------------------------------------- read */
96
+ server.registerTool("about", { description: "Version, data repo, last commit, base currency, counts, today's date.", annotations: ro }, wrap(async () => {
97
+ const s = await snap();
98
+ return {
99
+ ownledger: VERSION,
100
+ format: s.ledger.meta.format,
101
+ data: src.label,
102
+ commit: s.sha.slice(0, 12),
103
+ base: s.ledger.meta.base,
104
+ locale: s.ledger.meta.locale,
105
+ signed_in: props.login,
106
+ today: now(),
107
+ accounts: s.ledger.accounts.length,
108
+ transactions: s.ledger.transactions.filter((t) => !t.void).length,
109
+ check: { errors: s.errors, warnings: s.warnings },
110
+ };
111
+ }));
112
+ 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 () => {
113
+ const s = await snap();
114
+ const { map } = flattenCategories(s.ledger.categories);
115
+ return {
116
+ rules: [
117
+ "Every write: preview (add_/edit_/void_ tools) → show the owner → their explicit go → apply(preview_id).",
118
+ "Never invent amounts, dates, accounts or categories; ask when unsure.",
119
+ "Amounts are positive whole numbers in the base currency in the simple form; lines are signed and sum to 0.",
120
+ "Moves between the owner's accounts (card payments, savings, investments, loans) are transfers, never expense or income.",
121
+ "Correct a mistake with edit_transaction or void_transaction; never add a reversing entry unless asked.",
122
+ "Every add_/edit_/void_transaction needs reason: one line saying what the owner asked, close to their own words (it is kept on the transaction and in the commit).",
123
+ ],
124
+ base: s.ledger.meta.base,
125
+ categories: {
126
+ income: [...map.values()].filter((c) => c.kind === "income").map((c) => `${c.path}: ${c.name}`),
127
+ expense: [...map.values()].filter((c) => c.kind === "expense").map((c) => `${c.path}: ${c.name}`),
128
+ system: Object.entries(SYSTEM_CATEGORIES).map(([k, v]) => `${k}: ${v.en}`),
129
+ },
130
+ accounts: s.ledger.accounts.filter((a) => !a.closed).map((a) => `${a.id}: ${a.name} (${a.type})`),
131
+ };
132
+ }));
133
+ server.registerTool("accounts", {
134
+ description: "Accounts with balances (value for holdings), grouped by type. Closed accounts only when asked.",
135
+ inputSchema: z.object({ type: z.string().optional(), include_closed: z.boolean().optional(), date: z.string().optional() }),
136
+ annotations: ro,
137
+ }, wrap(async ({ type, include_closed, date }) => {
138
+ const s = await snap();
139
+ const asOf = date ?? now();
140
+ const vals = accountValues(s.ledger, asOf).filter((v) => (include_closed || !v.account.closed) && (!type || v.account.type === type));
141
+ const groups = {};
142
+ for (const v of vals) {
143
+ const g = (groups[v.account.type] ??= { total: 0, accounts: [] });
144
+ g.total += v.value;
145
+ g.accounts.push({
146
+ id: v.account.id,
147
+ name: v.account.name,
148
+ value: v.value,
149
+ ...(v.qty !== null ? { qty: v.qty, asset: v.asset, cost: v.cost, ...(v.priced ? {} : { unpriced: true }) } : {}),
150
+ ...(v.account.closed ? { closed: v.account.closed } : {}),
151
+ ...(typeDef(v.account.type) ? {} : { unknown_type: true }),
152
+ });
153
+ }
154
+ return { date: asOf, base: s.ledger.meta.base, by_type: groups };
155
+ }));
156
+ server.registerTool("transactions", {
157
+ description: "Search transactions (newest first, paginated). Lines are [account or category, signed amount].",
158
+ inputSchema: z.object({
159
+ from: z.string().optional(),
160
+ to: z.string().optional(),
161
+ account: z.string().optional(),
162
+ category: z.string().optional().describe("path prefix, e.g. food"),
163
+ text: z.string().optional().describe("in note, who, event, tags; accents ignored"),
164
+ min: z.number().optional(),
165
+ max: z.number().optional(),
166
+ plan: z.string().optional(),
167
+ include_void: z.boolean().optional(),
168
+ offset: z.number().int().optional(),
169
+ limit: z.number().int().max(200).optional(),
170
+ }),
171
+ annotations: ro,
172
+ }, wrap(async (q) => {
173
+ const s = await snap();
174
+ const r = queryTransactions(s.ledger, { ...q, includeVoid: q.include_void, limit: q.limit ?? 30 });
175
+ return { total: r.total, offset: q.offset ?? 0, items: r.items.map(compactTx) };
176
+ }));
177
+ server.registerTool("report", {
178
+ description: "Income and spending for a period, grouped, compared with the previous period. Transfers never count.",
179
+ inputSchema: z.object({
180
+ period: z.string().optional().describe("yyyy-mm or yyyy; default this month"),
181
+ from: z.string().optional(),
182
+ to: z.string().optional(),
183
+ by: z.enum(["category", "top", "account", "who", "event", "tag", "month"]).optional().describe("default top (top-level category)"),
184
+ kind: z.enum(["income", "expense"]).optional(),
185
+ category: z.string().optional(),
186
+ account: z.string().optional(),
187
+ compare: z.boolean().optional(),
188
+ limit: z.number().int().optional(),
189
+ }),
190
+ annotations: ro,
191
+ }, wrap(async (o) => {
192
+ const s = await snap();
193
+ const period = o.from && o.to ? { from: o.from, to: o.to } : (o.period ?? now().slice(0, 7));
194
+ const r = report(s.ledger, period, { by: (o.by ?? "top"), kind: o.kind, category: o.category, account: o.account, compare: o.compare });
195
+ const rows = r.rows.slice(0, o.limit ?? 25).map((x) => ({
196
+ key: x.key,
197
+ name: x.name,
198
+ ...(x.income ? { income: x.income } : {}),
199
+ ...(x.expense ? { expense: x.expense } : {}),
200
+ count: x.count,
201
+ ...(r.previous ? { prev: r.previous.rows[x.key] ? (x.income ? r.previous.rows[x.key].income : r.previous.rows[x.key].expense) : 0 } : {}),
202
+ }));
203
+ return {
204
+ period: r.period,
205
+ base: s.ledger.meta.base,
206
+ income: r.income,
207
+ expense: r.expense,
208
+ net: r.net,
209
+ ...(r.previous ? { previous: { period: r.previous.period, income: r.previous.income, expense: r.previous.expense, net: r.previous.net } } : {}),
210
+ rows,
211
+ ...(r.rows.length > rows.length ? { more_rows: r.rows.length - rows.length } : {}),
212
+ };
213
+ }));
214
+ server.registerTool("net_worth", {
215
+ description: "Net worth now (or at a date), by account type; optionally a monthly series.",
216
+ inputSchema: z.object({ date: z.string().optional(), months: z.number().int().max(240).optional().describe("monthly series length, e.g. 12") }),
217
+ annotations: ro,
218
+ }, wrap(async ({ date, months }) => {
219
+ const s = await snap();
220
+ const asOf = date ?? now();
221
+ const nw = netWorth(s.ledger, asOf);
222
+ return {
223
+ ...nw,
224
+ ...(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
+ };
226
+ }));
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 }) => {
228
+ const s = await snap();
229
+ return cards(s.ledger, date ?? now()).filter((c) => c.owed !== 0 || (c.toPay ?? 0) > 0);
230
+ }));
231
+ 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
+ const s = await snap();
233
+ const asOf = now();
234
+ return { due: plansDue(s.ledger, asOf, days ?? 30), plans: planStatus(s.ledger, asOf).filter((p) => !p.finished) };
235
+ }));
236
+ server.registerTool("deposits", { description: "Open term deposits: maturity, days left, expected interest.", inputSchema: z.object({ date: z.string().optional() }), annotations: ro }, wrap(async ({ date }) => {
237
+ const s = await snap();
238
+ return deposits(s.ledger, date ?? now());
239
+ }));
240
+ server.registerTool("today", { description: "One short block: due soon, cards to pay, deposits maturing, budgets over, anything odd.", annotations: ro }, wrap(async () => {
241
+ const s = await snap();
242
+ const t = today(s.ledger, now());
243
+ const m = report(s.ledger, now().slice(0, 7), { compare: false });
244
+ return { ...t, this_month: { income: m.income, expense: m.expense } };
245
+ }));
246
+ /* ---------------------------------------------------------------- write (preview) */
247
+ const pv = { readOnlyHint: true, openWorldHint: false }; // previews change nothing
248
+ server.registerTool("add_transaction", {
249
+ description: "PREVIEW a new transaction (writes nothing). Simple form: kind + amount + account (+ category or to_account). Full form: lines.",
250
+ inputSchema: z.object({ ...txFields, reason }),
251
+ annotations: pv,
252
+ }, wrap(async ({ reason, ...a }) => preview((f) => A.addTransaction(f, a, meta(reason)))));
253
+ 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)))));
254
+ 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)))));
255
+ const accountFields = {
256
+ name: z.string(),
257
+ type: z.string().describe("cash, bank, ewallet, credit_card, bnpl, deposit, savings_goal, gold, fund, stock, etf, crypto, insurance, loan_given, loan_taken, other (or a new one)"),
258
+ asset: z.string().optional().describe("non-base asset id for holdings (gold, fund...)"),
259
+ opened: z.string().optional(),
260
+ group: z.string().optional(),
261
+ note: z.string().optional(),
262
+ details: z.record(z.string(), z.unknown()).optional().describe("credit_card: statement_day, due_day, limit; deposit: principal, rate, term_months, start, maturity"),
263
+ };
264
+ server.registerTool("add_account", { description: "PREVIEW a new account.", inputSchema: z.object({ id: z.string().describe("short, kebab-case"), ...accountFields }), annotations: pv }, wrap(async (a) => preview((f) => A.addAccount(f, a))));
265
+ server.registerTool("edit_account", {
266
+ description: "PREVIEW changes to an account (name, type, details, group, note), or close it (closed: yyyy-mm-dd).",
267
+ inputSchema: z.object({ id: z.string(), ...Object.fromEntries(Object.entries(accountFields).map(([k, v]) => [k, v.optional()])), closed: z.string().optional() }),
268
+ annotations: pv,
269
+ }, wrap(async ({ id, ...set }) => preview((f) => A.editAccount(f, id, Object.fromEntries(Object.entries(set).filter(([, v]) => v !== undefined))))));
270
+ server.registerTool("add_plan", {
271
+ description: "PREVIEW a schedule: instalment, bnpl, loan_taken, loan_given, insurance_premium or deposit. Payments name it with plan: <id>.",
272
+ inputSchema: z.object({
273
+ id: z.string(),
274
+ kind: z.string(),
275
+ account: z.string(),
276
+ name: z.string().optional(),
277
+ principal: z.number().int().optional(),
278
+ count: z.number().int().optional(),
279
+ every: z.enum(["month", "quarter", "year"]),
280
+ start: z.string().describe("first due date"),
281
+ amount: z.number().int().optional().describe("per payment; default principal / count"),
282
+ fee: z.number().int().optional(),
283
+ rate: z.number().optional(),
284
+ note: z.string().optional(),
285
+ }),
286
+ annotations: pv,
287
+ }, wrap(async (p) => preview((f) => A.addPlan(f, p))));
288
+ 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))));
289
+ 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))));
290
+ 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))));
291
+ /* ---------------------------------------------------------------- apply */
292
+ server.registerTool("apply", {
293
+ description: "Commit a preview, ONLY after the owner explicitly said go. Refused if the data changed since the preview.",
294
+ inputSchema: z.object({ preview_id: z.string() }),
295
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
296
+ }, wrap(async ({ preview_id }) => {
297
+ const r = await applyPending(env, src, preview_id);
298
+ return { done: true, commit: r.sha.slice(0, 12), message: r.message, changed: r.summary };
299
+ }));
300
+ return server;
301
+ }
@@ -0,0 +1,42 @@
1
+ import type { FileMap } from "../engine/load.js";
2
+ import type { Ledger } from "../engine/types.js";
3
+ import { type CommitFile } from "./github.js";
4
+ import type { Env } from "./env.js";
5
+ /** Where the data lives: the user's GitHub repo, or (in `ownledger dev`) the local folder. */
6
+ export interface DataSource {
7
+ head(): Promise<string>;
8
+ files(sha: string): Promise<FileMap>;
9
+ commit(baseSha: string, files: CommitFile[], message: string): Promise<string>;
10
+ label: string;
11
+ }
12
+ export declare function githubSource(env: Env): DataSource;
13
+ /** `ownledger dev`: the CLI serves the local data folder at DEV_DATA_URL. */
14
+ export declare function devSource(env: Env): DataSource;
15
+ export declare function sourceFor(env: Env): DataSource;
16
+ export interface Snapshot {
17
+ sha: string;
18
+ files: FileMap;
19
+ ledger: Ledger;
20
+ errors: number;
21
+ warnings: number;
22
+ }
23
+ export declare function snapshot(env: Env, src: DataSource, sha?: string): Promise<Snapshot>;
24
+ export interface Pending {
25
+ baseSha: string;
26
+ files: FileMap;
27
+ binary?: {
28
+ path: string;
29
+ base64: string;
30
+ }[];
31
+ message: string;
32
+ summary: string[];
33
+ created: string;
34
+ }
35
+ export declare function fingerprint(baseSha: string, files: FileMap): Promise<string>;
36
+ export declare function savePending(env: Env, p: Pending): Promise<string>;
37
+ export declare function takePending(env: Env, fp: string): Promise<Pending | null>;
38
+ export declare function applyPending(env: Env, src: DataSource, fp: string): Promise<{
39
+ sha: string;
40
+ message: string;
41
+ summary: string[];
42
+ }>;
@@ -0,0 +1,92 @@
1
+ import { checkFiles } from "../engine/check.js";
2
+ import { commit, filesAt, headSha } from "./github.js";
3
+ export function githubSource(env) {
4
+ const c = { appId: env.GITHUB_APP_ID, privateKey: env.GITHUB_APP_PRIVATE_KEY, repo: env.DATA_REPO, branch: env.DATA_BRANCH || "main" };
5
+ return {
6
+ label: `github.com/${c.repo}@${c.branch}`,
7
+ head: () => headSha(c),
8
+ files: (sha) => filesAt(c, sha),
9
+ commit: (base, files, message) => commit(c, base, files, message),
10
+ };
11
+ }
12
+ /** `ownledger dev`: the CLI serves the local data folder at DEV_DATA_URL. */
13
+ export function devSource(env) {
14
+ const base = env.DEV_DATA_URL.replace(/\/$/, "");
15
+ return {
16
+ label: `local ${base}`,
17
+ head: async () => (await (await fetch(`${base}/head`)).text()).trim(),
18
+ files: async () => (await (await fetch(`${base}/files`)).json()),
19
+ commit: async (baseSha, files, message) => {
20
+ const r = await fetch(`${base}/commit`, { method: "POST", body: JSON.stringify({ baseSha, files, message }) });
21
+ if (r.status === 409) {
22
+ const { MainMovedError } = await import("./github.js");
23
+ throw new MainMovedError();
24
+ }
25
+ if (!r.ok)
26
+ throw new Error(`dev commit failed: ${r.status} ${await r.text()}`);
27
+ return (await r.text()).trim();
28
+ },
29
+ };
30
+ }
31
+ export function sourceFor(env) {
32
+ return env.DEV_DATA_URL ? devSource(env) : githubSource(env);
33
+ }
34
+ // Parsed ledgers live in the isolate's memory (keyed by commit); raw files also in KV, so a cold isolate
35
+ // needs no GitHub tarball for a commit it has seen. Both are safe to drop: GitHub is the only store.
36
+ const memory = new Map();
37
+ const KV_PREFIX = "ownledger:files:";
38
+ export async function snapshot(env, src, sha) {
39
+ const head = sha ?? (await src.head());
40
+ const hit = memory.get(head);
41
+ if (hit)
42
+ return hit;
43
+ let files = null;
44
+ if (!env.DEV_DATA_URL)
45
+ files = (await env.OAUTH_KV.get(KV_PREFIX + head, "json")) ?? null;
46
+ if (!files) {
47
+ files = await src.files(head);
48
+ if (!env.DEV_DATA_URL)
49
+ await env.OAUTH_KV.put(KV_PREFIX + head, JSON.stringify(files), { expirationTtl: 60 * 60 * 24 * 30 });
50
+ }
51
+ const r = checkFiles(files);
52
+ const snap = { sha: head, files, ledger: r.ledger, errors: r.errors.length, warnings: r.warnings.length };
53
+ memory.clear(); // keep one: the newest
54
+ memory.set(head, snap);
55
+ return snap;
56
+ }
57
+ const PENDING = "ownledger:pending:";
58
+ export async function fingerprint(baseSha, files) {
59
+ const data = new TextEncoder().encode(baseSha + "\n" + JSON.stringify(Object.entries(files).sort()));
60
+ const h = new Uint8Array(await crypto.subtle.digest("SHA-256", data));
61
+ return [...h.slice(0, 8)].map((x) => x.toString(16).padStart(2, "0")).join("");
62
+ }
63
+ export async function savePending(env, p) {
64
+ const fp = await fingerprint(p.baseSha, p.files);
65
+ await env.OAUTH_KV.put(PENDING + fp, JSON.stringify(p), { expirationTtl: 3600 });
66
+ return fp;
67
+ }
68
+ export async function takePending(env, fp) {
69
+ const p = await env.OAUTH_KV.get(PENDING + fp, "json");
70
+ if (p)
71
+ await env.OAUTH_KV.delete(PENDING + fp);
72
+ return p;
73
+ }
74
+ export async function applyPending(env, src, fp) {
75
+ const p = await env.OAUTH_KV.get(PENDING + fp, "json");
76
+ if (!p)
77
+ throw new Error("no such preview (it expires after an hour, and works once). Preview again.");
78
+ const head = await src.head();
79
+ if (head !== p.baseSha) {
80
+ await env.OAUTH_KV.delete(PENDING + fp);
81
+ const { MainMovedError } = await import("./github.js");
82
+ throw new MainMovedError();
83
+ }
84
+ // check again against the exact base (defence in depth: the preview was checked too)
85
+ const snap = await snapshot(env, src, head);
86
+ const r = checkFiles({ ...snap.files, ...p.files });
87
+ if (!r.ok)
88
+ throw new Error(`refused: the data would not pass check: ${r.errors[0]?.message}`);
89
+ const sha = await src.commit(p.baseSha, [...Object.entries(p.files).map(([path, content]) => ({ path, content })), ...(p.binary ?? []).map((b) => ({ path: b.path, base64: b.base64 }))], p.message);
90
+ await env.OAUTH_KV.delete(PENDING + fp);
91
+ return { sha, message: p.message, summary: p.summary };
92
+ }
@@ -0,0 +1,2 @@
1
+ /** Minimal streaming tar reader (ustar + pax path headers), enough for GitHub's tarballs. */
2
+ export declare function untar(stream: ReadableStream<Uint8Array>, keep: (path: string) => boolean): Promise<Record<string, string>>;
@@ -0,0 +1,62 @@
1
+ /** Minimal streaming tar reader (ustar + pax path headers), enough for GitHub's tarballs. */
2
+ export async function untar(stream, keep) {
3
+ const out = {};
4
+ const reader = stream.getReader();
5
+ let buf = new Uint8Array(0);
6
+ let done = false;
7
+ const need = async (n) => {
8
+ while (buf.length < n && !done) {
9
+ const r = await reader.read();
10
+ if (r.done)
11
+ done = true;
12
+ else {
13
+ const nb = new Uint8Array(buf.length + r.value.length);
14
+ nb.set(buf);
15
+ nb.set(r.value, buf.length);
16
+ buf = nb;
17
+ }
18
+ }
19
+ return buf.length >= n;
20
+ };
21
+ const take = (n) => {
22
+ const v = buf.subarray(0, n);
23
+ buf = buf.subarray(n);
24
+ return v;
25
+ };
26
+ const dec = new TextDecoder();
27
+ const str = (b) => {
28
+ const z = b.indexOf(0);
29
+ return dec.decode(z >= 0 ? b.subarray(0, z) : b);
30
+ };
31
+ let paxPath = null;
32
+ for (;;) {
33
+ if (!(await need(512)))
34
+ break;
35
+ const h = take(512);
36
+ if (h.every((x) => x === 0))
37
+ break;
38
+ const name = str(h.subarray(0, 100));
39
+ const size = parseInt(str(h.subarray(124, 136)).trim() || "0", 8);
40
+ const type = String.fromCharCode(h[156]);
41
+ const prefix = str(h.subarray(345, 500));
42
+ const padded = Math.ceil(size / 512) * 512;
43
+ await need(padded);
44
+ const body = take(padded).slice(0, size);
45
+ if (type === "x") {
46
+ const m = /\d+ path=([^\n]*)\n/.exec(dec.decode(body));
47
+ paxPath = m ? m[1] : null;
48
+ continue;
49
+ }
50
+ if (type === "g")
51
+ continue;
52
+ const full = paxPath ?? (prefix ? `${prefix}/${name}` : name);
53
+ paxPath = null;
54
+ if (type !== "0" && type !== "\0")
55
+ continue;
56
+ const rel = full.slice(full.indexOf("/") + 1); // strip "<repo>-<sha>/"
57
+ if (keep(rel))
58
+ out[rel] = dec.decode(body);
59
+ }
60
+ reader.cancel().catch(() => undefined);
61
+ return out;
62
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION = "1.1.0";
@@ -0,0 +1,2 @@
1
+ // generated by scripts/version.mjs
2
+ export const VERSION = "1.1.0";
package/package.json CHANGED
@@ -1,8 +1,70 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "0.0.1",
4
- "description": "Placeholder. Personal finance ledger used through MCP connectors; your data in your own GitHub repo, served by your own Cloudflare Worker.",
3
+ "version": "1.1.0",
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
- "repository": { "type": "git", "url": "git+https://github.com/phucbm/ownledger.git" },
7
- "homepage": "https://github.com/phucbm/ownledger"
6
+ "author": "phucbm",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/phucbm/ownledger.git"
10
+ },
11
+ "homepage": "https://github.com/phucbm/ownledger#readme",
12
+ "keywords": [
13
+ "finance",
14
+ "ledger",
15
+ "mcp",
16
+ "cloudflare-workers",
17
+ "personal-finance"
18
+ ],
19
+ "type": "module",
20
+ "packageManager": "pnpm@10.22.0",
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/engine/index.d.ts",
27
+ "default": "./dist/engine/index.js"
28
+ },
29
+ "./import": {
30
+ "types": "./dist/import/index.d.ts",
31
+ "default": "./dist/import/index.js"
32
+ },
33
+ "./worker": {
34
+ "default": "./dist/worker/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "assets",
40
+ "presets",
41
+ "templates",
42
+ "AGENTS.md",
43
+ "CHANGELOG.md"
44
+ ],
45
+ "scripts": {
46
+ "build": "node scripts/version.mjs && rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/cli/index.js",
47
+ "typecheck": "node scripts/version.mjs && tsc --noEmit",
48
+ "test": "vitest run",
49
+ "fixtures": "tsx scripts/make-fixtures.ts && tsx scripts/make-misa-fixture.ts",
50
+ "prepublishOnly": "pnpm typecheck && pnpm test && pnpm build"
51
+ },
52
+ "dependencies": {
53
+ "@cloudflare/workers-oauth-provider": "1.2.4",
54
+ "@modelcontextprotocol/server": "2.4.0",
55
+ "fflate": "0.8.3",
56
+ "yaml": "2.9.1",
57
+ "zod": "4.6.7"
58
+ },
59
+ "devDependencies": {
60
+ "@cloudflare/workers-types": "5.20261121.1",
61
+ "@types/node": "26.6.6",
62
+ "tsx": "4.23.15",
63
+ "typescript": "7.0.2",
64
+ "vitest": "5.1.1",
65
+ "wrangler": "4.166.0"
66
+ },
67
+ "bin": {
68
+ "ownledger": "./dist/cli/index.js"
69
+ }
8
70
  }