@artesian/tides-mcp 0.2.0 → 0.3.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 (2) hide show
  1. package/dist/tides-mcp.js +297 -155
  2. package/package.json +1 -1
package/dist/tides-mcp.js CHANGED
@@ -15557,7 +15557,7 @@ function browserOpener(platform = process.platform, run = spawn) {
15557
15557
  // package.json
15558
15558
  var package_default = {
15559
15559
  name: "@artesian/tides-mcp",
15560
- version: "0.2.0",
15560
+ version: "0.3.0",
15561
15561
  description: "Tides for your AI assistant: decrypts your ledger on this computer.",
15562
15562
  type: "module",
15563
15563
  bin: {
@@ -15717,7 +15717,14 @@ function deviceClient(http, token) {
15717
15717
  }
15718
15718
  });
15719
15719
  },
15720
- dismissRun: (id) => json("POST", `/api/v1/mail/runs/${id}/dismiss`)
15720
+ dismissRun: (id) => json("POST", `/api/v1/mail/runs/${id}/dismiss`),
15721
+ restoreRun: (id) => json("POST", `/api/v1/mail/runs/${id}/restore`),
15722
+ dismissInbox: (ids) => json("POST", "/api/v1/inbox/dismiss", {
15723
+ body: { ids }
15724
+ }),
15725
+ restoreInbox: (ids) => json("POST", "/api/v1/inbox/restore", {
15726
+ body: { ids }
15727
+ })
15721
15728
  },
15722
15729
  tides: {
15723
15730
  dayPrices: (on) => json("GET", "/api/v1/market/day-prices", { query: { on } }),
@@ -27160,6 +27167,58 @@ var EMPTY_COMPLETION_RESULT = {
27160
27167
  }
27161
27168
  };
27162
27169
 
27170
+ // ../../packages/app/src/account-match.ts
27171
+ function isDate(run) {
27172
+ if (!/^(19|20)\d{6}$/.test(run))
27173
+ return false;
27174
+ const iso = `${run.slice(0, 4)}-${run.slice(4, 6)}-${run.slice(6)}`;
27175
+ const date = new Date(`${iso}T00:00:00Z`);
27176
+ return !Number.isNaN(date.getTime()) && date.toISOString().startsWith(iso);
27177
+ }
27178
+ function numbersInName(name) {
27179
+ return (name.match(/\d+/g) ?? []).filter((run) => run.length >= 6 && run.length <= 16 && !isDate(run));
27180
+ }
27181
+ var digitsOf = (accountNumber) => {
27182
+ const digits = accountNumber?.replace(/[\s-]/g, "") ?? "";
27183
+ return /^\d{4,}$/.test(digits) ? digits : null;
27184
+ };
27185
+ function closeness(run, accountNumber) {
27186
+ const digits = digitsOf(accountNumber);
27187
+ if (!digits || !run.endsWith(digits))
27188
+ return 0;
27189
+ return digits.length === run.length ? Number.POSITIVE_INFINITY : digits.length;
27190
+ }
27191
+ function byFileName(accounts, fileName) {
27192
+ let best;
27193
+ let bestScore = 0;
27194
+ let tied = false;
27195
+ for (const run of numbersInName(fileName))
27196
+ for (const account of accounts) {
27197
+ const score = closeness(run, account.accountNumber);
27198
+ if (!score || account.id === best?.id)
27199
+ continue;
27200
+ if (score > bestScore) {
27201
+ best = account;
27202
+ bestScore = score;
27203
+ tied = false;
27204
+ } else if (score === bestScore)
27205
+ tied = true;
27206
+ }
27207
+ return tied ? undefined : best;
27208
+ }
27209
+ function matchAccount(accounts, input) {
27210
+ const ofKind = accounts.filter((account) => account.kind === input.kind);
27211
+ if (input.accountNumber) {
27212
+ const found = ofKind.find((account) => account.accountNumber === input.accountNumber);
27213
+ return found ? { accountId: found.id, why: "number" } : null;
27214
+ }
27215
+ const open = ofKind.filter((account) => account.closedOn === null);
27216
+ const named = input.fileName ? byFileName(open, input.fileName) : undefined;
27217
+ if (named)
27218
+ return { accountId: named.id, why: "file_name" };
27219
+ const used = input.recipeId ? open.find((account) => (account.recipes ?? []).includes(input.recipeId)) : undefined;
27220
+ return used ? { accountId: used.id, why: "recipe" } : null;
27221
+ }
27163
27222
  // ../../packages/core/src/money/currency.ts
27164
27223
  var builtIns = {
27165
27224
  ZAR: 2,
@@ -27500,6 +27559,26 @@ var BudgetReset = discriminatedUnion("kind", [
27500
27559
  day: int().min(1).max(31)
27501
27560
  })
27502
27561
  ]).describe("When the period starts: weekday for weekly; day, last-day, working-day or nth-weekday for monthly; date for yearly. Days past a month's end move to its last day.");
27562
+ // ../../packages/core/src/colors.ts
27563
+ var COLORS = [
27564
+ "grey",
27565
+ "blue",
27566
+ "red",
27567
+ "yellow",
27568
+ "green",
27569
+ "pink",
27570
+ "purple",
27571
+ "cyan",
27572
+ "orange"
27573
+ ];
27574
+ function freshColor(taken) {
27575
+ const free = COLORS.filter((color) => !taken.includes(color));
27576
+ const from = free.length ? free : COLORS;
27577
+ return from[Math.floor(Math.random() * from.length)];
27578
+ }
27579
+
27580
+ // ../../packages/schemas/src/color.ts
27581
+ var Color = _enum(COLORS);
27503
27582
  // ../../packages/schemas/src/health.ts
27504
27583
  var Health = object({ status: literal("ok") });
27505
27584
  var HealthError = object({
@@ -27572,12 +27651,14 @@ var CategoryJson = object({
27572
27651
  id: uuid2(),
27573
27652
  name: string2(),
27574
27653
  parentId: uuid2().nullable(),
27575
- bucket: _enum(["needs", "wants", "savings"]).nullable()
27654
+ bucket: _enum(["needs", "wants", "savings"]).nullable(),
27655
+ color: Color.nullable()
27576
27656
  });
27577
27657
  var NewCategory = object({
27578
27658
  name: string2().trim().min(1).max(60),
27579
27659
  parentId: uuid2().nullish(),
27580
- bucket: _enum(["needs", "wants", "savings"]).nullish()
27660
+ bucket: _enum(["needs", "wants", "savings"]).nullish(),
27661
+ color: Color.nullish()
27581
27662
  });
27582
27663
  var CategoryPatch = NewCategory.partial();
27583
27664
  var TransactionJson = object({
@@ -27609,18 +27690,6 @@ var TransactionPatch = object({
27609
27690
  notes: string2().max(2000).nullable().optional()
27610
27691
  });
27611
27692
  // ../../packages/schemas/src/views.ts
27612
- var ACCOUNT_COLORS = [
27613
- "grey",
27614
- "blue",
27615
- "red",
27616
- "yellow",
27617
- "green",
27618
- "pink",
27619
- "purple",
27620
- "cyan",
27621
- "orange"
27622
- ];
27623
- var AccountColor = _enum(ACCOUNT_COLORS);
27624
27693
  var AccountJson = object({
27625
27694
  id: uuid2(),
27626
27695
  name: string2(),
@@ -27630,7 +27699,7 @@ var AccountJson = object({
27630
27699
  currency: string2(),
27631
27700
  closedOn: IsoDate.nullable(),
27632
27701
  opening: object({ amount: MoneyJson, on: IsoDate }).nullable(),
27633
- color: AccountColor.nullable().optional(),
27702
+ color: Color.nullable().optional(),
27634
27703
  excludeFromNetWorth: boolean2().optional(),
27635
27704
  createdAt: string2()
27636
27705
  });
@@ -27640,7 +27709,7 @@ var NewAccount = object({
27640
27709
  kind: _enum(["bank", "broker"]),
27641
27710
  accountNumber: string2().trim().min(1).max(50).nullish(),
27642
27711
  currency: string2().refine(isCurrency, "Unsupported currency.").optional(),
27643
- color: AccountColor.nullable().optional(),
27712
+ color: Color.nullable().optional(),
27644
27713
  excludeFromNetWorth: boolean2().optional()
27645
27714
  });
27646
27715
  var AccountPatch = NewAccount.pick({
@@ -27700,8 +27769,6 @@ var BudgetStatusJson = object({
27700
27769
  budgets: array(object({
27701
27770
  budgetId: uuid2(),
27702
27771
  name: string2(),
27703
- categoryIds: array(uuid2()),
27704
- categoryId: uuid2(),
27705
27772
  category: string2(),
27706
27773
  period: BudgetPeriod,
27707
27774
  reset: BudgetReset.nullable(),
@@ -27834,7 +27901,11 @@ var HoldingJson = object({
27834
27901
  value: MoneyJson.nullable(),
27835
27902
  gain: MoneyJson.nullable()
27836
27903
  });
27837
- var LabelJson = object({ id: uuid2(), name: string2() });
27904
+ var LabelJson = object({
27905
+ id: uuid2(),
27906
+ name: string2(),
27907
+ color: Color.nullable().optional()
27908
+ });
27838
27909
  var LabelCountJson = LabelJson.extend({
27839
27910
  documentCount: number2().int(),
27840
27911
  transactionCount: number2().int(),
@@ -27898,7 +27969,7 @@ var PAYLOADS = {
27898
27969
  closedOn: IsoDate.nullable(),
27899
27970
  opening: object({ amount: MoneyJson, on: IsoDate }).nullable(),
27900
27971
  bankBalance: object({ amount: MoneyJson, on: IsoDate }).nullable().optional(),
27901
- color: AccountColor.nullable().optional(),
27972
+ color: Color.nullable().optional(),
27902
27973
  excludeFromNetWorth: boolean2().optional(),
27903
27974
  recipes: array(string2()).optional()
27904
27975
  }),
@@ -27943,10 +28014,11 @@ var PAYLOADS = {
27943
28014
  }),
27944
28015
  budget: object({
27945
28016
  name: string2(),
27946
- categoryIds: array(string2()).min(1),
28017
+ categoryIds: array(string2()).optional(),
27947
28018
  amount: MoneyJson,
27948
28019
  period: BudgetPeriod2,
27949
- reset: BudgetReset.nullable()
28020
+ reset: BudgetReset.nullable(),
28021
+ color: Color.nullable().optional()
27950
28022
  }),
27951
28023
  document: object({
27952
28024
  fileId: Id.nullable(),
@@ -27981,7 +28053,11 @@ var PAYLOADS = {
27981
28053
  set: RuleSet,
27982
28054
  replace: boolean2()
27983
28055
  }),
27984
- document_type: object({ name: string2(), takesTransaction: boolean2() }),
28056
+ document_type: object({
28057
+ name: string2(),
28058
+ takesTransaction: boolean2(),
28059
+ color: Color.nullable().optional()
28060
+ }),
27985
28061
  correspondent: object({ name: string2() }),
27986
28062
  instrument: object({
27987
28063
  symbol: string2().min(1),
@@ -28000,7 +28076,10 @@ var PAYLOADS = {
28000
28076
  exponent: int().min(0).max(4),
28001
28077
  rate: object({ units: DecimalString, zar: DecimalString })
28002
28078
  }),
28003
- tag: object({ name: string2() }),
28079
+ tag: object({
28080
+ name: string2(),
28081
+ color: Color.nullable().optional()
28082
+ }),
28004
28083
  import: object({
28005
28084
  accountId: Id.nullable(),
28006
28085
  fileId: Id.nullable(),
@@ -28266,7 +28345,13 @@ var Arrival = discriminatedUnion("kind", [
28266
28345
  ImportFileArrival
28267
28346
  ]);
28268
28347
  function openArrival(entry, publicKey, privateKey) {
28269
- const unreadable = (reason) => ({ status: "unreadable", id: entry.id, reason });
28348
+ const dismissed = entry.dismissedAt ? { dismissedAt: entry.dismissedAt } : {};
28349
+ const unreadable = (reason) => ({
28350
+ status: "unreadable",
28351
+ id: entry.id,
28352
+ reason,
28353
+ ...dismissed
28354
+ });
28270
28355
  let value;
28271
28356
  try {
28272
28357
  value = JSON.parse(new TextDecoder().decode(openSealed(entry.sealed, publicKey, privateKey)));
@@ -28279,7 +28364,7 @@ function openArrival(entry, publicKey, privateKey) {
28279
28364
  if (typeof version === "number" && version < ARRIVAL_VERSION)
28280
28365
  return unreadable("old_version");
28281
28366
  const parsed = Arrival.safeParse(value);
28282
- return parsed.success ? { status: "ok", id: entry.id, arrival: parsed.data } : unreadable("invalid");
28367
+ return parsed.success ? { status: "ok", id: entry.id, arrival: parsed.data, ...dismissed } : unreadable("invalid");
28283
28368
  }
28284
28369
  // ../../packages/ledger/src/codec.ts
28285
28370
  var encoder = new TextEncoder;
@@ -28817,22 +28902,23 @@ async function setBudget(ctx, input) {
28817
28902
  const limit = fromMoneyJson(input.amount);
28818
28903
  if (limit.currency !== "ZAR" || limit.amountMinor <= 0n)
28819
28904
  throw new Error("A budget is a positive amount in rand.");
28820
- if (input.categoryIds.length === 0)
28821
- throw new Error("A budget needs at least one category.");
28905
+ const name = input.name.trim();
28906
+ if (!name)
28907
+ throw new Error("A budget needs a name.");
28822
28908
  const saved = await withRetry(ctx, () => {
28823
28909
  const budgets = ctx.store.all("budget");
28824
- const [only] = input.categoryIds;
28825
- const existing = input.budgetId ? budgets.find((b) => b.id === input.budgetId) : input.categoryIds.length === 1 ? budgets.find((b) => b.payload.categoryIds.length === 1 && b.payload.categoryIds[0] === only) : undefined;
28910
+ const existing = input.budgetId ? budgets.find((b) => b.id === input.budgetId) : undefined;
28911
+ const color = input.color !== undefined ? input.color : existing ? existing.payload.color ?? null : freshColor(budgets.map((b) => b.payload.color));
28826
28912
  return [
28827
28913
  {
28828
28914
  kind: "budget",
28829
28915
  ...existing ? { id: existing.id } : {},
28830
28916
  payload: {
28831
- name: input.name ?? existing?.payload.name ?? "",
28832
- categoryIds: input.categoryIds,
28917
+ name,
28833
28918
  amount: input.amount,
28834
28919
  period: input.period,
28835
- reset: input.reset ?? null
28920
+ reset: input.reset ?? null,
28921
+ color
28836
28922
  }
28837
28923
  }
28838
28924
  ];
@@ -29229,12 +29315,13 @@ function ruleTransaction(t, rules) {
29229
29315
  const free = (field) => !t.handSet.includes(field);
29230
29316
  const next = { ...t };
29231
29317
  const categoryId = firstSet(matched, "categoryId");
29232
- if (categoryId && free("category"))
29233
- next.categoryId = categoryId;
29318
+ const applied = categoryId && free("category") ? categoryId : undefined;
29319
+ if (applied)
29320
+ next.categoryId = applied;
29234
29321
  const description = firstSet(matched, "description");
29235
29322
  if (description && free("description"))
29236
29323
  next.description = description;
29237
- const budgetId = firstSet(matched, "budgetId");
29324
+ const budgetId = matched.find(({ payload: { set } }) => set.budgetId !== undefined && (set.categoryId === undefined || set.categoryId === applied))?.payload.set.budgetId;
29238
29325
  if (budgetId && free("budget"))
29239
29326
  next.budgetId = budgetId;
29240
29327
  const changed = next.categoryId !== t.categoryId || next.description !== t.description || next.budgetId !== t.budgetId;
@@ -29398,8 +29485,6 @@ async function budgetStatusOf(set, spentIn, options) {
29398
29485
  return {
29399
29486
  budgetId: budget.id,
29400
29487
  name: budget.category,
29401
- categoryIds: budget.categoryIds,
29402
- categoryId: budget.categoryIds[0],
29403
29488
  category: budget.category,
29404
29489
  period: budget.period,
29405
29490
  reset: budget.reset,
@@ -29671,28 +29756,11 @@ var uncategorised = (ctx, matches) => ctx.store.all("transaction").filter((row)
29671
29756
  }));
29672
29757
  async function deleteCategory(ctx, id) {
29673
29758
  await ctx.api.deleteCategory(id);
29674
- return withRetry(ctx, () => {
29675
- const covering = ctx.store.all("budget").filter((b) => b.payload.categoryIds.includes(id));
29676
- const trimmed = covering.filter((b) => b.payload.categoryIds.length > 1).map((b) => ({
29677
- id: b.id,
29678
- kind: "budget",
29679
- payload: {
29680
- ...b.payload,
29681
- categoryIds: b.payload.categoryIds.filter((c) => c !== id)
29682
- }
29683
- }));
29684
- return {
29685
- save: [...uncategorised(ctx, (c) => c === id), ...trimmed],
29686
- remove: covering.filter((b) => b.payload.categoryIds.length === 1).map((b) => b.id)
29687
- };
29688
- });
29759
+ return withRetry(ctx, () => uncategorised(ctx, (c) => c === id));
29689
29760
  }
29690
29761
  async function clearCategories(ctx) {
29691
29762
  const result = await ctx.api.clearCategories();
29692
- const saved = await withRetry(ctx, () => ({
29693
- save: uncategorised(ctx, () => true),
29694
- remove: ctx.store.all("budget").map((budget) => budget.id)
29695
- }));
29763
+ const saved = await withRetry(ctx, () => uncategorised(ctx, () => true));
29696
29764
  return { ...saved, ...result };
29697
29765
  }
29698
29766
  async function addStarterCategories(ctx) {
@@ -29803,13 +29871,12 @@ function bankOfFile(ledger, fileId) {
29803
29871
  const correspondent = document?.payload.correspondentId ? ledger.get(document.payload.correspondentId) : null;
29804
29872
  return bankFor(correspondent?.status === "ok" && correspondent.kind === "correspondent" ? correspondent.payload.name : null);
29805
29873
  }
29806
- function accountFor(ledger, accountNumber, kind, choice, recipeId) {
29874
+ function accountFor(ledger, stated, kind, choice, recipeId) {
29807
29875
  const accounts = ledger.all("account");
29808
29876
  if (choice)
29809
29877
  return accounts.find((account) => account.id === choice.accountId && account.payload.kind === kind);
29810
- if (!accountNumber)
29811
- return accounts.find((account) => account.payload.kind === kind && account.payload.closedOn === null && (account.payload.recipes ?? []).includes(recipeId));
29812
- return accounts.find((account) => account.payload.kind === kind && account.payload.accountNumber === accountNumber);
29878
+ const match = matchAccount(accounts.map((account) => ({ id: account.id, ...account.payload })), { ...stated, kind, recipeId });
29879
+ return match ? accounts.find((account) => account.id === match.accountId) : undefined;
29813
29880
  }
29814
29881
  function placeArrival(ledger, { id, arrival }, choice) {
29815
29882
  let account;
@@ -29819,9 +29886,9 @@ function placeArrival(ledger, { id, arrival }, choice) {
29819
29886
  claimed = Boolean(claim);
29820
29887
  if (claim && !resumable)
29821
29888
  return { status: "folded" };
29822
- account = claim ? ledger.all("account").find((a) => a.id === claim.payload.accountId) : accountFor(ledger, arrival.accountNumber, "bank", choice, arrival.parser);
29889
+ account = claim ? ledger.all("account").find((a) => a.id === claim.payload.accountId) : accountFor(ledger, arrival, "bank", choice, arrival.parser);
29823
29890
  } else
29824
- account = accountFor(ledger, arrival.accountNumber, "broker", choice, arrival.recipeId);
29891
+ account = accountFor(ledger, { accountNumber: arrival.accountNumber, fileName: null }, "broker", choice, arrival.recipeId);
29825
29892
  return account ? { status: "account", account, claimed } : {
29826
29893
  status: "needs_account",
29827
29894
  accountNumber: arrival.accountNumber,
@@ -30192,7 +30259,7 @@ function oldArrivals(entries) {
30192
30259
  return entries.flatMap((entry) => entry.status === "unreadable" && entry.reason === "old_version" ? [{ entryId: entry.id, message: OLD_VERSION }] : []);
30193
30260
  }
30194
30261
  function waitingToFold(entries, holding = false) {
30195
- return entries.filter((entry) => entry.status === "ok" && entry.arrival.kind !== "held_mail" && entry.arrival.kind !== "held_source" && entry.arrival.kind !== "failed" && entry.arrival.kind !== "import_file" && (!holding || entry.arrival.kind !== "document" && entry.arrival.kind !== "statement"));
30262
+ return entries.filter((entry) => entry.status === "ok" && !entry.dismissedAt && entry.arrival.kind !== "held_mail" && entry.arrival.kind !== "held_source" && entry.arrival.kind !== "failed" && entry.arrival.kind !== "import_file" && (!holding || entry.arrival.kind !== "document" && entry.arrival.kind !== "statement"));
30196
30263
  }
30197
30264
  async function inboxStatus(ctx, keys, options = {}) {
30198
30265
  const entries = options.entries ?? await openInbox(ctx, keys);
@@ -30220,7 +30287,7 @@ async function inboxStatus(ctx, keys, options = {}) {
30220
30287
  });
30221
30288
  }
30222
30289
  for (const entry of entries) {
30223
- if (entry.status !== "ok")
30290
+ if (entry.status !== "ok" || entry.dismissedAt)
30224
30291
  continue;
30225
30292
  const { arrival } = entry;
30226
30293
  if (arrival.kind === "held_mail")
@@ -30343,8 +30410,14 @@ async function readArrivalFile(ctx, keys, fileId) {
30343
30410
  await ctx.api.rewrapItemFile(fileId, wrapFileKey(fileId, fileKey, keys.ledgerKey));
30344
30411
  return bytes;
30345
30412
  }
30346
- function heldMail(entries) {
30347
- return entries.flatMap((entry) => entry.status === "ok" && entry.arrival.kind === "held_mail" ? [{ id: entry.id, mail: entry.arrival }] : []);
30413
+ function heldMail(entries, dismissed = false) {
30414
+ return entries.flatMap((entry) => entry.status === "ok" && entry.arrival.kind === "held_mail" && Boolean(entry.dismissedAt) === dismissed ? [
30415
+ {
30416
+ id: entry.id,
30417
+ mail: entry.arrival,
30418
+ dismissedAt: entry.dismissedAt ?? null
30419
+ }
30420
+ ] : []);
30348
30421
  }
30349
30422
  async function runAgain(ctx, keys, entry) {
30350
30423
  if (!entry.mail.fileId)
@@ -30371,13 +30444,12 @@ async function retryRuns(ctx, keys, runIds, allowed, options = {}) {
30371
30444
  async function clearHeld(ctx, keys, entryIds, options = {}) {
30372
30445
  const entries = options.entries ?? await openInbox(ctx, keys);
30373
30446
  const chosen = heldMail(entries).filter((entry) => entryIds.includes(entry.id));
30374
- for (const { mail } of chosen) {
30447
+ if (!chosen.length)
30448
+ return;
30449
+ for (const { mail } of chosen)
30375
30450
  if (mail.runId)
30376
30451
  await ctx.api.dismissRun(mail.runId).catch(() => {});
30377
- if (mail.fileId)
30378
- await ctx.api.deleteItemFile(mail.fileId);
30379
- }
30380
- await ctx.api.ackInbox(chosen.map((entry) => entry.id));
30452
+ await ctx.api.dismissInbox(chosen.map((entry) => entry.id));
30381
30453
  }
30382
30454
  async function retrySource(ctx, keys, entryId, options = {}) {
30383
30455
  const entries = options.entries ?? await openInbox(ctx, keys);
@@ -30551,7 +30623,11 @@ function isSourceFile(doc, sources) {
30551
30623
  // ../../packages/app/src/documents.ts
30552
30624
  var NO_TYPE = "none";
30553
30625
  var list = (value) => value ? value.split(",").filter(Boolean) : [];
30554
- var label = (row) => ({ id: row.id, name: row.payload.name });
30626
+ var label = (row) => ({
30627
+ id: row.id,
30628
+ name: row.payload.name,
30629
+ ..."color" in row.payload ? { color: row.payload.color ?? null } : {}
30630
+ });
30555
30631
  function labelRows(ledger, field) {
30556
30632
  if (field === "correspondent")
30557
30633
  return ledger.correspondents;
@@ -30623,6 +30699,10 @@ function labelCounts(labels, documents, transactions, field) {
30623
30699
  })).sort((a, b) => a.name.localeCompare(b.name));
30624
30700
  }
30625
30701
  var sameName = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
30702
+ var freshTagColor = (ledger, changes) => freshColor([
30703
+ ...ledger.tags.map((t) => t.payload.color),
30704
+ ...changes.filter((c) => c.kind === "tag").map((c) => c.payload.color)
30705
+ ]);
30626
30706
  function editDocument(ledger, documentId, edit) {
30627
30707
  const row = ledger.documents.find((d) => d.id === documentId);
30628
30708
  if (!row)
@@ -30663,7 +30743,11 @@ function editDocument(ledger, documentId, edit) {
30663
30743
  const known = ledger.tags.find((t) => sameName(t.payload.name, name)) ?? changes.find((c) => c.kind === "tag" && sameName(c.payload.name, name));
30664
30744
  const id = known?.id ?? crypto.randomUUID();
30665
30745
  if (!known)
30666
- changes.push({ id, kind: "tag", payload: { name } });
30746
+ changes.push({
30747
+ id,
30748
+ kind: "tag",
30749
+ payload: { name, color: freshTagColor(ledger, changes) }
30750
+ });
30667
30751
  if (!ids.includes(id))
30668
30752
  ids.push(id);
30669
30753
  }
@@ -30708,7 +30792,11 @@ function editDocuments(ledger, ids, edit) {
30708
30792
  if (known)
30709
30793
  return known.id;
30710
30794
  const id = crypto.randomUUID();
30711
- changes.push({ id, kind, payload: { name } });
30795
+ changes.push(kind === "tag" ? {
30796
+ id,
30797
+ kind,
30798
+ payload: { name, color: freshTagColor(ledger, changes) }
30799
+ } : { id, kind, payload: { name } });
30712
30800
  return id;
30713
30801
  };
30714
30802
  const correspondentId = edit.correspondent === undefined ? undefined : edit.correspondent?.trim() ? labelId("correspondent", edit.correspondent) : null;
@@ -30850,14 +30938,18 @@ function taken(ctx, field, name, except) {
30850
30938
  return labelRows(documentLedger(ctx.store), field).some((r) => r.id !== except && r.payload.name.trim().toLowerCase() === name.trim().toLowerCase());
30851
30939
  }
30852
30940
  var clash = (field) => new Error(`That ${NOUN[field]} already exists.`);
30941
+ var colorOf = (row) => row.payload.color;
30853
30942
  async function createLabel(ctx, input) {
30854
30943
  const { field } = input;
30855
30944
  const name = input.name.trim();
30856
30945
  const saved = await withRetry(ctx, () => {
30857
30946
  if (taken(ctx, field, name))
30858
30947
  throw clash(field);
30948
+ if (field === "correspondent")
30949
+ return [{ kind: field, payload: { name } }];
30950
+ const color = input.color === undefined ? freshColor(labelRows(documentLedger(ctx.store), field).map(colorOf)) : input.color;
30859
30951
  return [
30860
- field === "document_type" ? { kind: field, payload: { name, takesTransaction: true } } : { kind: field, payload: { name } }
30952
+ field === "document_type" ? { kind: field, payload: { name, takesTransaction: true, color } } : { kind: field, payload: { name, color } }
30861
30953
  ];
30862
30954
  });
30863
30955
  return { ...saved, id: saved.saved[0] ?? "" };
@@ -30874,7 +30966,11 @@ async function renameLabel(ctx, input) {
30874
30966
  {
30875
30967
  kind: field,
30876
30968
  id,
30877
- payload: { ...row.payload, name: input.name.trim() }
30969
+ payload: {
30970
+ ...row.payload,
30971
+ name: input.name.trim(),
30972
+ ...input.color === undefined ? {} : { color: input.color }
30973
+ }
30878
30974
  }
30879
30975
  ];
30880
30976
  });
@@ -31267,7 +31363,13 @@ function tagIdsFor(names, tags) {
31267
31363
  const known = tags.find((t) => sameName2(t.payload.name, name)) ?? created.find((c) => sameName2(c.payload.name, name));
31268
31364
  const id = known?.id ?? crypto.randomUUID();
31269
31365
  if (!known)
31270
- created.push({ id, payload: { name } });
31366
+ created.push({
31367
+ id,
31368
+ payload: {
31369
+ name,
31370
+ color: freshColor([...tags, ...created].map((t) => t.payload.color))
31371
+ }
31372
+ });
31271
31373
  if (!ids.includes(id))
31272
31374
  ids.push(id);
31273
31375
  }
@@ -31525,36 +31627,6 @@ async function markTransfers(ctx, input) {
31525
31627
  function movesBalance(row) {
31526
31628
  return !row.payload.hidden || row.payload.transferCounterpartId !== null;
31527
31629
  }
31528
- // ../../packages/app/src/budget-of.ts
31529
- function budgetOf(tx, budgets, parents = new Map) {
31530
- if (tx.budgetId)
31531
- return tx.budgetId;
31532
- if (!tx.categoryId)
31533
- return null;
31534
- const covering = (id) => id ? budgets.find((b) => b.categoryIds.includes(id))?.id : undefined;
31535
- return covering(tx.categoryId) ?? covering(parents.get(tx.categoryId)) ?? null;
31536
- }
31537
- // ../../packages/app/src/category-tree.ts
31538
- var byName2 = (a, b) => a.name.localeCompare(b.name);
31539
- function categoryTree(categories) {
31540
- const ids = new Set(categories.map((c) => c.id));
31541
- const topLevel = categories.filter((c) => !c.parentId || !ids.has(c.parentId)).sort(byName2);
31542
- return topLevel.flatMap((parent) => [
31543
- { category: parent, parent: null },
31544
- ...categories.filter((c) => c.parentId === parent.id).sort(byName2).map((category) => ({ category, parent }))
31545
- ]);
31546
- }
31547
- function categoryForest(categories) {
31548
- const tree = categoryTree(categories);
31549
- return tree.filter((entry) => !entry.parent).map(({ category }) => ({
31550
- ...category,
31551
- children: tree.filter((entry) => entry.parent?.id === category.id).map((entry) => entry.category)
31552
- }));
31553
- }
31554
- function parentsOf(categories) {
31555
- return new Map(categories.flatMap((c) => c.parentId ? [[c.id, c.parentId]] : []));
31556
- }
31557
-
31558
31630
  // ../../packages/app/src/totals.ts
31559
31631
  function totalsRows(rows) {
31560
31632
  return rows.map(({ payload: t }) => ({
@@ -31569,42 +31641,26 @@ function totalsRows(rows) {
31569
31641
  }
31570
31642
 
31571
31643
  // ../../packages/app/src/budgets.ts
31572
- var budgetName = (budget, categoryNames) => budget.name || budget.categoryIds.flatMap((id) => categoryNames.get(id) ?? []).join(", ");
31573
- function budgetsOf(budgets, categories) {
31574
- const names = new Map(categories.map((c) => [c.id, c.name]));
31575
- return budgets.flatMap((row) => {
31576
- const categoryIds = row.payload.categoryIds.filter((id) => names.has(id));
31577
- if (categoryIds.length === 0)
31578
- return [];
31579
- return [
31580
- {
31581
- id: row.id,
31582
- name: row.payload.name,
31583
- categoryIds,
31584
- category: budgetName(row.payload, names),
31585
- limit: fromMoneyJson(row.payload.amount),
31586
- period: row.payload.period,
31587
- reset: normaliseReset(row.payload.period, row.payload.reset),
31588
- createdAt: new Date(row.createdAt),
31589
- updatedAt: new Date(row.updatedAt)
31590
- }
31591
- ];
31592
- }).sort((a, b) => a.category.localeCompare(b.category));
31644
+ function budgetsOf(budgets) {
31645
+ return budgets.map((row) => ({
31646
+ id: row.id,
31647
+ name: row.payload.name,
31648
+ category: row.payload.name,
31649
+ limit: fromMoneyJson(row.payload.amount),
31650
+ period: row.payload.period,
31651
+ reset: normaliseReset(row.payload.period, row.payload.reset),
31652
+ createdAt: new Date(row.createdAt),
31653
+ updatedAt: new Date(row.updatedAt)
31654
+ })).sort((a, b) => a.category.localeCompare(b.category));
31593
31655
  }
31594
- var byCreation = (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id);
31595
31656
  async function budgetStatus(budgets, rows, categories, options = {}) {
31596
31657
  const today = options.today ?? todayInJohannesburg();
31597
- const order = [...budgets].sort(byCreation).map((b) => ({ id: b.id, categoryIds: b.payload.categoryIds }));
31598
- const parents = parentsOf(categories);
31599
31658
  const shaped = totalsRows(rows).map((row, n) => ({
31600
31659
  ...row,
31601
- budgetId: budgetOf({
31602
- budgetId: rows[n]?.payload.budgetId ?? null,
31603
- categoryId: row.categoryId
31604
- }, order, parents)
31660
+ budgetId: rows[n]?.payload.budgetId ?? null
31605
31661
  }));
31606
31662
  const names = new Map(categories.map((c) => [c.id, c.name]));
31607
- const status = await budgetStatusOf(budgetsOf(budgets, categories), (bounds, into) => budgetSpendOver(shaped, names, bounds, into), {
31663
+ const status = await budgetStatusOf(budgetsOf(budgets), (bounds, into) => budgetSpendOver(shaped, names, bounds, into), {
31608
31664
  month: options.month ?? today.slice(0, 7),
31609
31665
  today,
31610
31666
  ...options.rate ? { rate: options.rate } : {}
@@ -31636,6 +31692,26 @@ async function budgetStatus(budgets, rows, categories, options = {}) {
31636
31692
  leftOut: status.leftOut
31637
31693
  };
31638
31694
  }
31695
+ // ../../packages/app/src/category-tree.ts
31696
+ var byName2 = (a, b) => a.name.localeCompare(b.name);
31697
+ function categoryTree(categories) {
31698
+ const ids = new Set(categories.map((c) => c.id));
31699
+ const topLevel = categories.filter((c) => !c.parentId || !ids.has(c.parentId)).sort(byName2);
31700
+ return topLevel.flatMap((parent) => [
31701
+ { category: parent, parent: null },
31702
+ ...categories.filter((c) => c.parentId === parent.id).sort(byName2).map((category) => ({ category, parent }))
31703
+ ]);
31704
+ }
31705
+ function categoryForest(categories) {
31706
+ const tree = categoryTree(categories);
31707
+ return tree.filter((entry) => !entry.parent).map(({ category }) => ({
31708
+ ...category,
31709
+ children: tree.filter((entry) => entry.parent?.id === category.id).map((entry) => entry.category)
31710
+ }));
31711
+ }
31712
+ function parentsOf(categories) {
31713
+ return new Map(categories.flatMap((c) => c.parentId ? [[c.id, c.parentId]] : []));
31714
+ }
31639
31715
  // ../../packages/app/src/custom-instruments.ts
31640
31716
  function latest(candidates, on) {
31641
31717
  let best = null;
@@ -31894,12 +31970,10 @@ function documentSearch(store, filter) {
31894
31970
  })
31895
31971
  }, filter);
31896
31972
  }
31897
- function budgetList(store, categories) {
31898
- const names = new Map(categories.map((c) => [c.id, c.name]));
31973
+ function budgetList(store) {
31899
31974
  return store.all("budget").map(({ id, payload }) => ({
31900
31975
  id,
31901
- name: budgetName(payload, names),
31902
- categoryIds: payload.categoryIds,
31976
+ name: payload.name,
31903
31977
  amount: payload.amount,
31904
31978
  period: payload.period,
31905
31979
  reset: payload.reset
@@ -31908,6 +31982,73 @@ function budgetList(store, categories) {
31908
31982
  function currentBudgetStatus(store, categories, options) {
31909
31983
  return budgetStatus(store.all("budget"), confirmed(store.all("transaction")), categories, options);
31910
31984
  }
31985
+ // ../../packages/app/src/retire-budget-categories.ts
31986
+ var byCreation = (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id);
31987
+ function retireBudgetCategories(input) {
31988
+ const retiring = input.budgets.filter((b) => b.payload.categoryIds !== undefined).sort(byCreation);
31989
+ if (!retiring.length)
31990
+ return { save: [], remove: [] };
31991
+ const names = new Map(input.categories.map((c) => [c.id, c.name]));
31992
+ const direct = new Map;
31993
+ for (const b of retiring)
31994
+ for (const id of b.payload.categoryIds ?? [])
31995
+ if (names.has(id) && !direct.has(id))
31996
+ direct.set(id, b.id);
31997
+ const parents = parentsOf(input.categories);
31998
+ const budgetFor = (categoryId) => {
31999
+ if (!categoryId)
32000
+ return;
32001
+ const parent = parents.get(categoryId);
32002
+ return direct.get(categoryId) ?? (parent ? direct.get(parent) : undefined);
32003
+ };
32004
+ const rules = input.rules.flatMap((r) => {
32005
+ if (r.payload.target !== "transaction" || r.payload.set.budgetId)
32006
+ return [];
32007
+ const budgetId = budgetFor(r.payload.set.categoryId);
32008
+ if (!budgetId)
32009
+ return [];
32010
+ return [
32011
+ {
32012
+ id: r.id,
32013
+ kind: "rule",
32014
+ payload: { ...r.payload, set: { ...r.payload.set, budgetId } }
32015
+ }
32016
+ ];
32017
+ });
32018
+ const transactions = input.transactions.flatMap((t) => {
32019
+ if (t.payload.budgetId)
32020
+ return [];
32021
+ const budgetId = budgetFor(t.payload.categoryId);
32022
+ if (!budgetId)
32023
+ return [];
32024
+ return [
32025
+ { id: t.id, kind: "transaction", payload: { ...t.payload, budgetId } }
32026
+ ];
32027
+ });
32028
+ const remove = [];
32029
+ const budgets = retiring.flatMap((b) => {
32030
+ const { categoryIds = [], ...rest } = b.payload;
32031
+ const name = rest.name.trim() || categoryIds.flatMap((id) => names.get(id) ?? []).join(", ");
32032
+ if (!name) {
32033
+ remove.push(b.id);
32034
+ return [];
32035
+ }
32036
+ return [{ id: b.id, kind: "budget", payload: { ...rest, name } }];
32037
+ });
32038
+ return { save: [...rules, ...transactions, ...budgets], remove };
32039
+ }
32040
+ var budgetsNeedRetiring = (budgets) => budgets.some((b) => b.payload.categoryIds !== undefined);
32041
+ async function retireBudgets(ctx) {
32042
+ if (!budgetsNeedRetiring(ctx.store.all("budget")))
32043
+ return null;
32044
+ const categories = await ctx.api.categories();
32045
+ return withRetry(ctx, () => retireBudgetCategories({
32046
+ budgets: ctx.store.all("budget"),
32047
+ rules: ctx.store.all("rule"),
32048
+ transactions: ctx.store.all("transaction"),
32049
+ categories
32050
+ }));
32051
+ }
31911
32052
  // ../../packages/app/src/triage-week.ts
31912
32053
  var SAST_OFFSET_MS = 2 * 3600000;
31913
32054
  // src/version-guard.ts
@@ -32090,9 +32231,9 @@ var Id4 = uuid2();
32090
32231
  var budgetTools = [
32091
32232
  tool({
32092
32233
  name: "list_budgets",
32093
- description: "Lists the budgets with their categories, amount and period.",
32234
+ description: "Lists the budgets with their amount and period.",
32094
32235
  input: {},
32095
- run: async (_args, session) => json2(budgetList(session.ctx.store, await session.ctx.api.categories()))
32236
+ run: async (_args, session) => json2(budgetList(session.ctx.store))
32096
32237
  }),
32097
32238
  tool({
32098
32239
  name: "budget_status",
@@ -32116,11 +32257,10 @@ var budgetTools = [
32116
32257
  }),
32117
32258
  tool({
32118
32259
  name: "set_budget",
32119
- description: "Creates or changes a budget. Without budgetId, a budget for a single category replaces that category's budget. The amount is a positive rand amount.",
32260
+ description: "Creates a budget, or changes the one budgetId names. The name is required and the amount is a positive rand amount. Spending counts towards a budget only when a transaction's budget is set, by hand or by a rule.",
32120
32261
  input: {
32121
32262
  budgetId: Id4.optional(),
32122
- name: string2().optional(),
32123
- categoryIds: array(Id4),
32263
+ name: string2(),
32124
32264
  amount: MoneyJson,
32125
32265
  period: BudgetPeriod,
32126
32266
  reset: BudgetReset.nullable().optional()
@@ -32146,10 +32286,11 @@ var categoryTools = [
32146
32286
  }),
32147
32287
  tool({
32148
32288
  name: "create_category",
32149
- description: "Creates a category, optionally under a parent and in a bucket (needs, wants or savings).",
32289
+ description: "Creates a category, optionally under a parent, in a bucket (needs, wants or savings) and with a colour. Without a colour it gets one not yet in use.",
32150
32290
  input: NewCategory.shape,
32151
32291
  run: async (input, session) => {
32152
- const created = await session.api.createCategory(input);
32292
+ const color = input.color === undefined ? freshColor((await session.ctx.api.categories()).map((c) => c.color)) : input.color;
32293
+ const created = await session.api.createCategory({ ...input, color });
32153
32294
  return json2({
32154
32295
  summary: `Created ${created.name}.`,
32155
32296
  changed: [{ kind: "category", id: created.id }]
@@ -32158,7 +32299,7 @@ var categoryTools = [
32158
32299
  }),
32159
32300
  tool({
32160
32301
  name: "update_category",
32161
- description: "Renames a category, moves it under another parent (null makes it top-level) or changes its bucket.",
32302
+ description: "Renames a category, moves it under another parent (null makes it top-level), or changes its bucket or colour (null clears it).",
32162
32303
  input: { id: Id5, ...CategoryPatch.shape },
32163
32304
  run: async ({ id, ...patch }, session) => {
32164
32305
  const updated = await session.api.updateCategory(id, patch);
@@ -32170,7 +32311,7 @@ var categoryTools = [
32170
32311
  }),
32171
32312
  tool({
32172
32313
  name: "delete_category",
32173
- description: "Deletes a category. Its transactions become uncategorised and budgets that covered only it go too.",
32314
+ description: "Deletes a category. Its transactions become uncategorised.",
32174
32315
  input: { id: Id5 },
32175
32316
  run: async ({ id }, session) => written(session, "Category deleted.", await deleteCategory(session.ctx, id), { also: [{ kind: "category", id }] })
32176
32317
  }),
@@ -32189,7 +32330,7 @@ var categoryTools = [
32189
32330
  }),
32190
32331
  tool({
32191
32332
  name: "clear_categories",
32192
- description: "Deletes every category and every budget, leaving all transactions uncategorised. Categories can't be brought back; the budgets go to Recently deleted for 30 days.",
32333
+ description: "Deletes every category, leaving all transactions uncategorised. Categories can't be brought back.",
32193
32334
  input: {},
32194
32335
  run: async (_args, session) => {
32195
32336
  const { categories, ...saved } = await clearCategories(session.ctx);
@@ -32608,12 +32749,12 @@ var mailTools = [
32608
32749
  }),
32609
32750
  tool({
32610
32751
  name: "delete_held_mail",
32611
- description: "Deletes held emails (from inbox_status) and their files.",
32752
+ description: "Moves held emails (from inbox_status) to Recently deleted, where they stay for 30 days and can be restored in the web app.",
32612
32753
  input: { entryIds: array(Id8).min(1) },
32613
32754
  run: async ({ entryIds }, session) => {
32614
32755
  await clearHeld(session.ctx, session.keys, entryIds);
32615
32756
  return json2({
32616
- summary: `${plural(entryIds.length, "email")} deleted.`,
32757
+ summary: `${plural(entryIds.length, "email")} moved to Recently deleted.`,
32617
32758
  changed: entryIds.map((id) => ({ kind: "arrival", id }))
32618
32759
  });
32619
32760
  }
@@ -33245,6 +33386,7 @@ function buildServer(state, http, secrets, options) {
33245
33386
  try {
33246
33387
  const active = await activeSession();
33247
33388
  await active.ctx.store.sync();
33389
+ await retireBudgets(active.ctx);
33248
33390
  const text = await definition.run(args, active);
33249
33391
  const notice = leftOutNotice(active.ctx.store);
33250
33392
  return reply(text, false, notice ? [notice] : []);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@artesian/tides-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Tides for your AI assistant: decrypts your ledger on this computer.",
5
5
  "type": "module",
6
6
  "bin": {