@rfc0/patty 0.0.0-stage → 1.0.2

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 (465) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +214 -2
  3. package/dist/adapters/access-tokens.js +7 -0
  4. package/dist/adapters/accounts.js +37 -0
  5. package/dist/adapters/auth.js +11 -0
  6. package/dist/adapters/bills.js +32 -0
  7. package/dist/adapters/budgets.js +29 -0
  8. package/dist/adapters/categories.js +32 -0
  9. package/dist/adapters/client-grants.js +7 -0
  10. package/dist/adapters/credit-cards.js +33 -0
  11. package/dist/adapters/currencies.js +2 -0
  12. package/dist/adapters/currency-rates.js +18 -0
  13. package/dist/adapters/dashboards.js +43 -0
  14. package/dist/adapters/demo.js +13 -0
  15. package/dist/adapters/instance-settings.js +7 -0
  16. package/dist/adapters/invites.js +7 -0
  17. package/dist/adapters/recurring.js +55 -0
  18. package/dist/adapters/sessions.js +7 -0
  19. package/dist/adapters/settings.js +4 -0
  20. package/dist/adapters/setup-codes.js +7 -0
  21. package/dist/adapters/tags.js +9 -0
  22. package/dist/adapters/transactions.js +95 -0
  23. package/dist/adapters/users.js +7 -0
  24. package/dist/common/build-version.js +5 -0
  25. package/dist/common/errors.js +118 -0
  26. package/dist/common/net.js +71 -0
  27. package/dist/common/result.js +7 -0
  28. package/dist/composition/auth.js +106 -0
  29. package/dist/composition/boot.js +27 -0
  30. package/dist/composition/cli.js +86 -0
  31. package/dist/composition/demo/seed.js +92 -0
  32. package/dist/composition/demo/shell.js +107 -0
  33. package/dist/composition/export.js +89 -0
  34. package/dist/composition/http.js +110 -0
  35. package/dist/composition/import.js +55 -0
  36. package/dist/composition/lazy-modules.js +2 -0
  37. package/dist/composition/runtime.js +115 -0
  38. package/dist/composition/sign-in/interpreter.js +154 -0
  39. package/dist/composition/sign-in/server.js +36 -0
  40. package/dist/composition/sign-in/wiring.js +23 -0
  41. package/dist/composition/stdio.js +69 -0
  42. package/dist/config.js +136 -0
  43. package/dist/controllers/account/account.js +88 -0
  44. package/dist/controllers/account/transaction.js +119 -0
  45. package/dist/controllers/account/transfer.js +34 -0
  46. package/dist/controllers/aggregate.js +40 -0
  47. package/dist/controllers/auth/access-tokens.js +61 -0
  48. package/dist/controllers/auth/grants.js +136 -0
  49. package/dist/controllers/auth/key-export.js +20 -0
  50. package/dist/controllers/auth/owner.js +80 -0
  51. package/dist/controllers/auth/password.js +35 -0
  52. package/dist/controllers/auth/session.js +50 -0
  53. package/dist/controllers/auth/step-up.js +8 -0
  54. package/dist/controllers/auth/users.js +183 -0
  55. package/dist/controllers/budgets.js +87 -0
  56. package/dist/controllers/categories.js +67 -0
  57. package/dist/controllers/correlations.js +112 -0
  58. package/dist/controllers/credit-card/bill.js +105 -0
  59. package/dist/controllers/credit-card/credit-card.js +129 -0
  60. package/dist/controllers/credit-card/transaction.js +181 -0
  61. package/dist/controllers/currencies.js +1 -0
  62. package/dist/controllers/currency-rates.js +40 -0
  63. package/dist/controllers/dashboards.js +68 -0
  64. package/dist/controllers/demo/seed.js +31 -0
  65. package/dist/controllers/demo/tour.js +12 -0
  66. package/dist/controllers/deps.js +6 -0
  67. package/dist/controllers/instance.js +6 -0
  68. package/dist/controllers/merchants.js +12 -0
  69. package/dist/controllers/recurring.js +70 -0
  70. package/dist/controllers/resolve.js +37 -0
  71. package/dist/controllers/settings.js +47 -0
  72. package/dist/controllers/status.js +19 -0
  73. package/dist/controllers/summary.js +21 -0
  74. package/dist/controllers/tags.js +19 -0
  75. package/dist/controllers/transaction/bulk.js +6 -0
  76. package/dist/controllers/transaction/core.js +49 -0
  77. package/dist/controllers/transaction/read.js +28 -0
  78. package/dist/diplomat/auth/credentials.js +58 -0
  79. package/dist/diplomat/auth/sign-in-store.js +18 -0
  80. package/dist/diplomat/cli/commands/auth.js +100 -0
  81. package/dist/diplomat/cli/commands/db.js +72 -0
  82. package/dist/diplomat/cli/commands/demo.js +68 -0
  83. package/dist/diplomat/cli/commands/key.js +119 -0
  84. package/dist/diplomat/cli/commands/login.js +151 -0
  85. package/dist/diplomat/cli/commands/setup.js +132 -0
  86. package/dist/diplomat/cli/commands/users.js +123 -0
  87. package/dist/diplomat/cli/commands.js +61 -0
  88. package/dist/diplomat/cli/export-file.js +37 -0
  89. package/dist/diplomat/cli/import-file.js +44 -0
  90. package/dist/diplomat/cli/io.js +61 -0
  91. package/dist/diplomat/cli/key-export-approval.js +37 -0
  92. package/dist/diplomat/cli/messages.js +96 -0
  93. package/dist/diplomat/cli/prompt.js +74 -0
  94. package/dist/diplomat/cli/terminal.js +81 -0
  95. package/dist/diplomat/client-config/clients.js +150 -0
  96. package/dist/diplomat/client-config/merge.js +41 -0
  97. package/dist/diplomat/db/bootstrap.js +98 -0
  98. package/dist/diplomat/db/database-files.js +147 -0
  99. package/dist/diplomat/db/driver.js +167 -0
  100. package/dist/diplomat/db/effects.js +101 -0
  101. package/dist/diplomat/db/engine.js +9 -0
  102. package/dist/diplomat/db/export.js +22 -0
  103. package/dist/diplomat/db/file-lock.js +82 -0
  104. package/dist/diplomat/db/key-lock.js +14 -0
  105. package/dist/diplomat/db/locale-cache.js +23 -0
  106. package/dist/diplomat/db/migration-barrier.js +57 -0
  107. package/dist/diplomat/db/migration-journal.js +18 -0
  108. package/dist/diplomat/db/migration-lock.js +15 -0
  109. package/dist/diplomat/db/migrations.js +11 -0
  110. package/dist/diplomat/db/present.js +17 -0
  111. package/dist/diplomat/db/queries/aggregate-whitelist.js +35 -0
  112. package/dist/diplomat/db/queries/filters.js +59 -0
  113. package/dist/diplomat/db/queries/fts.js +18 -0
  114. package/dist/diplomat/db/queries/scope.js +8 -0
  115. package/dist/diplomat/db/queries/transaction-select.js +26 -0
  116. package/dist/diplomat/db/queries/tx-predicates.js +13 -0
  117. package/dist/diplomat/db/repos/access-tokens.js +27 -0
  118. package/dist/diplomat/db/repos/accounts.js +91 -0
  119. package/dist/diplomat/db/repos/bills.js +93 -0
  120. package/dist/diplomat/db/repos/budgets.js +72 -0
  121. package/dist/diplomat/db/repos/categories.js +53 -0
  122. package/dist/diplomat/db/repos/client-grants.js +67 -0
  123. package/dist/diplomat/db/repos/correlations.js +66 -0
  124. package/dist/diplomat/db/repos/credit-cards.js +67 -0
  125. package/dist/diplomat/db/repos/currencies.js +8 -0
  126. package/dist/diplomat/db/repos/currency-rates.js +40 -0
  127. package/dist/diplomat/db/repos/dashboards.js +123 -0
  128. package/dist/diplomat/db/repos/health.js +12 -0
  129. package/dist/diplomat/db/repos/instance-settings.js +14 -0
  130. package/dist/diplomat/db/repos/instance.js +58 -0
  131. package/dist/diplomat/db/repos/invites.js +43 -0
  132. package/dist/diplomat/db/repos/merchants.js +121 -0
  133. package/dist/diplomat/db/repos/recurring.js +29 -0
  134. package/dist/diplomat/db/repos/sessions.js +19 -0
  135. package/dist/diplomat/db/repos/settings.js +41 -0
  136. package/dist/diplomat/db/repos/setup-codes.js +28 -0
  137. package/dist/diplomat/db/repos/sub-categories.js +67 -0
  138. package/dist/diplomat/db/repos/tags.js +51 -0
  139. package/dist/diplomat/db/repos/transaction-tags.js +57 -0
  140. package/dist/diplomat/db/repos/transactions.js +163 -0
  141. package/dist/diplomat/db/repos/users.js +47 -0
  142. package/dist/diplomat/db/safety-copy.js +87 -0
  143. package/dist/diplomat/db/schema.js +348 -0
  144. package/dist/diplomat/db/seed/categories.js +112 -0
  145. package/dist/diplomat/db/seed/currencies.js +9 -0
  146. package/dist/diplomat/db/seed/demo/br.js +98 -0
  147. package/dist/diplomat/db/seed/demo/co.js +89 -0
  148. package/dist/diplomat/db/seed/demo/index.js +12 -0
  149. package/dist/diplomat/db/seed/demo/mx.js +90 -0
  150. package/dist/diplomat/db/seed/demo/shared.js +39 -0
  151. package/dist/diplomat/db/seed/demo/us.js +90 -0
  152. package/dist/diplomat/db/seed/merchant-rules.js +188 -0
  153. package/dist/diplomat/db/sqlite-errors.js +40 -0
  154. package/dist/diplomat/db/tenancy-integrity.js +45 -0
  155. package/dist/diplomat/db/version-guard.js +16 -0
  156. package/dist/diplomat/http/auth-pages.js +41 -0
  157. package/dist/diplomat/http/auth-paths.js +46 -0
  158. package/dist/diplomat/http/bearer.js +15 -0
  159. package/dist/diplomat/http/connect-pages.js +51 -0
  160. package/dist/diplomat/http/context.js +17 -0
  161. package/dist/diplomat/http/cookies.js +27 -0
  162. package/dist/diplomat/http/form-pages.js +38 -0
  163. package/dist/diplomat/http/hooks/auth.js +106 -0
  164. package/dist/diplomat/http/hooks/demo-marker.js +59 -0
  165. package/dist/diplomat/http/openapi.js +73 -0
  166. package/dist/diplomat/http/principal.js +1 -0
  167. package/dist/diplomat/http/rate-limiter.js +78 -0
  168. package/dist/diplomat/http/remedy.js +26 -0
  169. package/dist/diplomat/http/respond.js +50 -0
  170. package/dist/diplomat/http/routes/account.js +226 -0
  171. package/dist/diplomat/http/routes/aggregate.js +28 -0
  172. package/dist/diplomat/http/routes/auth.js +105 -0
  173. package/dist/diplomat/http/routes/budget.js +34 -0
  174. package/dist/diplomat/http/routes/category.js +109 -0
  175. package/dist/diplomat/http/routes/connect.js +124 -0
  176. package/dist/diplomat/http/routes/credit-card.js +263 -0
  177. package/dist/diplomat/http/routes/currency-rates.js +60 -0
  178. package/dist/diplomat/http/routes/currency.js +16 -0
  179. package/dist/diplomat/http/routes/dashboard.js +93 -0
  180. package/dist/diplomat/http/routes/invite.js +63 -0
  181. package/dist/diplomat/http/routes/recurring.js +65 -0
  182. package/dist/diplomat/http/routes/settings.js +38 -0
  183. package/dist/diplomat/http/routes/summary.js +23 -0
  184. package/dist/diplomat/http/routes/system.js +29 -0
  185. package/dist/diplomat/http/routes/tag.js +51 -0
  186. package/dist/diplomat/http/routes/tokens.js +72 -0
  187. package/dist/diplomat/http/routes/transaction.js +55 -0
  188. package/dist/diplomat/http/routes/transfer.js +35 -0
  189. package/dist/diplomat/http/routes/ui.js +110 -0
  190. package/dist/diplomat/http/routes/users.js +156 -0
  191. package/dist/diplomat/http/routes/well-known.js +26 -0
  192. package/dist/diplomat/http/routes.js +85 -0
  193. package/dist/diplomat/http/session.js +34 -0
  194. package/dist/diplomat/http/token-pages.js +75 -0
  195. package/dist/diplomat/http/ui-files.js +21 -0
  196. package/dist/diplomat/http/user-pages.js +93 -0
  197. package/dist/diplomat/mcp/annotations.js +8 -0
  198. package/dist/diplomat/mcp/auth-info.js +20 -0
  199. package/dist/diplomat/mcp/context.js +14 -0
  200. package/dist/diplomat/mcp/definition.js +3 -0
  201. package/dist/diplomat/mcp/gate.js +15 -0
  202. package/dist/diplomat/mcp/instructions.js +19 -0
  203. package/dist/diplomat/mcp/prompts.js +125 -0
  204. package/dist/diplomat/mcp/register.js +12 -0
  205. package/dist/diplomat/mcp/remedy.js +17 -0
  206. package/dist/diplomat/mcp/resources.js +93 -0
  207. package/dist/diplomat/mcp/respond.js +20 -0
  208. package/dist/diplomat/mcp/route.js +62 -0
  209. package/dist/diplomat/mcp/scopes.js +53 -0
  210. package/dist/diplomat/mcp/server.js +26 -0
  211. package/dist/diplomat/mcp/shared.js +5 -0
  212. package/dist/diplomat/mcp/stdio-session.js +94 -0
  213. package/dist/diplomat/mcp/stdio.js +23 -0
  214. package/dist/diplomat/mcp/tool-name.js +59 -0
  215. package/dist/diplomat/mcp/tools/account.js +218 -0
  216. package/dist/diplomat/mcp/tools/aggregate.js +32 -0
  217. package/dist/diplomat/mcp/tools/budget.js +99 -0
  218. package/dist/diplomat/mcp/tools/category.js +103 -0
  219. package/dist/diplomat/mcp/tools/correlations.js +70 -0
  220. package/dist/diplomat/mcp/tools/credit-card.js +239 -0
  221. package/dist/diplomat/mcp/tools/currency-rates.js +62 -0
  222. package/dist/diplomat/mcp/tools/dashboard.js +75 -0
  223. package/dist/diplomat/mcp/tools/index.js +31 -0
  224. package/dist/diplomat/mcp/tools/recurring.js +62 -0
  225. package/dist/diplomat/mcp/tools/summary.js +30 -0
  226. package/dist/diplomat/mcp/tools/system.js +83 -0
  227. package/dist/diplomat/mcp/tools/tag.js +48 -0
  228. package/dist/diplomat/mcp/tools/transaction.js +53 -0
  229. package/dist/diplomat/mcp/tools/transfer.js +28 -0
  230. package/dist/diplomat/mcp/tour.js +87 -0
  231. package/dist/logic/account.js +79 -0
  232. package/dist/logic/aggregate.js +37 -0
  233. package/dist/logic/auth/bearer.js +35 -0
  234. package/dist/logic/auth/grant.js +126 -0
  235. package/dist/logic/auth/key-export.js +10 -0
  236. package/dist/logic/auth/keychain.js +3 -0
  237. package/dist/logic/auth/message.js +22 -0
  238. package/dist/logic/auth/origin.js +57 -0
  239. package/dist/logic/auth/owner.js +22 -0
  240. package/dist/logic/auth/password.js +3 -0
  241. package/dist/logic/auth/redact.js +25 -0
  242. package/dist/logic/auth/revoke.js +28 -0
  243. package/dist/logic/auth/scope.js +17 -0
  244. package/dist/logic/auth/session.js +30 -0
  245. package/dist/logic/auth/sign-in-flow.js +305 -0
  246. package/dist/logic/auth/time.js +2 -0
  247. package/dist/logic/auth/token.js +74 -0
  248. package/dist/logic/auth/user-plans.js +84 -0
  249. package/dist/logic/auth/users.js +78 -0
  250. package/dist/logic/balance.js +2 -0
  251. package/dist/logic/bill.js +74 -0
  252. package/dist/logic/budget.js +78 -0
  253. package/dist/logic/category.js +37 -0
  254. package/dist/logic/classify.js +21 -0
  255. package/dist/logic/correlations.js +147 -0
  256. package/dist/logic/credit-card.js +2 -0
  257. package/dist/logic/currency-rate.js +69 -0
  258. package/dist/logic/dashboard.js +40 -0
  259. package/dist/logic/demo/database.js +30 -0
  260. package/dist/logic/demo/plan.js +308 -0
  261. package/dist/logic/demo/tour.js +33 -0
  262. package/dist/logic/export-destination.js +12 -0
  263. package/dist/logic/key-import.js +15 -0
  264. package/dist/logic/locale.js +5 -0
  265. package/dist/logic/localize.js +12 -0
  266. package/dist/logic/merchant.js +31 -0
  267. package/dist/logic/migration.js +1 -0
  268. package/dist/logic/money.js +12 -0
  269. package/dist/logic/period.js +45 -0
  270. package/dist/logic/persistence.js +48 -0
  271. package/dist/logic/recurring.js +51 -0
  272. package/dist/logic/resolve.js +44 -0
  273. package/dist/logic/summary.js +29 -0
  274. package/dist/logic/tag.js +13 -0
  275. package/dist/logic/transaction.js +197 -0
  276. package/dist/main.js +42 -0
  277. package/dist/models/account.js +197 -0
  278. package/dist/models/aggregate.js +61 -0
  279. package/dist/models/auth/bearer.js +11 -0
  280. package/dist/models/auth/entity.js +17 -0
  281. package/dist/models/auth/errors.js +42 -0
  282. package/dist/models/auth/grant.js +58 -0
  283. package/dist/models/auth/key-export.js +11 -0
  284. package/dist/models/auth/message.js +50 -0
  285. package/dist/models/auth/mode.js +7 -0
  286. package/dist/models/auth/origin.js +16 -0
  287. package/dist/models/auth/owner.js +36 -0
  288. package/dist/models/auth/password.js +24 -0
  289. package/dist/models/auth/principal.js +26 -0
  290. package/dist/models/auth/redact.js +4 -0
  291. package/dist/models/auth/scope.js +9 -0
  292. package/dist/models/auth/session.js +19 -0
  293. package/dist/models/auth/sign-in-flow.js +102 -0
  294. package/dist/models/auth/sign-in.js +41 -0
  295. package/dist/models/auth/time.js +5 -0
  296. package/dist/models/auth/token.js +50 -0
  297. package/dist/models/auth/users.js +52 -0
  298. package/dist/models/bill.js +55 -0
  299. package/dist/models/budget.js +106 -0
  300. package/dist/models/category.js +52 -0
  301. package/dist/models/client-config.js +18 -0
  302. package/dist/models/correlations.js +215 -0
  303. package/dist/models/credit-card.js +156 -0
  304. package/dist/models/currency-rate.js +83 -0
  305. package/dist/models/dashboard.js +54 -0
  306. package/dist/models/database.js +16 -0
  307. package/dist/models/date.js +8 -0
  308. package/dist/models/demo/core.js +58 -0
  309. package/dist/models/demo/tour.js +41 -0
  310. package/dist/models/encryption-key.js +2 -0
  311. package/dist/models/error.js +13 -0
  312. package/dist/models/export.js +9 -0
  313. package/dist/models/id.js +2 -0
  314. package/dist/models/instance.js +7 -0
  315. package/dist/models/key-import.js +6 -0
  316. package/dist/models/locale.js +25 -0
  317. package/dist/models/merchant.js +12 -0
  318. package/dist/models/money.js +14 -0
  319. package/dist/models/package.js +12 -0
  320. package/dist/models/page.js +56 -0
  321. package/dist/models/persistence.js +1 -0
  322. package/dist/models/prompts.js +5 -0
  323. package/dist/models/recurring.js +54 -0
  324. package/dist/models/remedy.js +17 -0
  325. package/dist/models/resolution.js +1 -0
  326. package/dist/models/startup.js +7 -0
  327. package/dist/models/summary.js +24 -0
  328. package/dist/models/tag.js +14 -0
  329. package/dist/models/tenancy.js +10 -0
  330. package/dist/models/transaction-tag.js +6 -0
  331. package/dist/models/transaction.js +275 -0
  332. package/dist/wire/db/access-tokens.js +1 -0
  333. package/dist/wire/db/accounts.js +7 -0
  334. package/dist/wire/db/aggregate.js +16 -0
  335. package/dist/wire/db/bills.js +14 -0
  336. package/dist/wire/db/budgets.js +33 -0
  337. package/dist/wire/db/categories.js +14 -0
  338. package/dist/wire/db/client-grants.js +1 -0
  339. package/dist/wire/db/correlations.js +49 -0
  340. package/dist/wire/db/credit-cards.js +1 -0
  341. package/dist/wire/db/currencies.js +1 -0
  342. package/dist/wire/db/currency-rates.js +1 -0
  343. package/dist/wire/db/dashboards.js +1 -0
  344. package/dist/wire/db/instance-settings.js +1 -0
  345. package/dist/wire/db/invites.js +1 -0
  346. package/dist/wire/db/merchants.js +18 -0
  347. package/dist/wire/db/recurring.js +19 -0
  348. package/dist/wire/db/sessions.js +1 -0
  349. package/dist/wire/db/settings.js +1 -0
  350. package/dist/wire/db/setup-codes.js +1 -0
  351. package/dist/wire/db/tags.js +1 -0
  352. package/dist/wire/db/tenancy.js +1 -0
  353. package/dist/wire/db/transactions.js +89 -0
  354. package/dist/wire/db/users.js +1 -0
  355. package/dist/wire/in/accounts.js +26 -0
  356. package/dist/wire/in/aggregate.js +10 -0
  357. package/dist/wire/in/auth.js +107 -0
  358. package/dist/wire/in/bills.js +11 -0
  359. package/dist/wire/in/budgets.js +11 -0
  360. package/dist/wire/in/categories.js +9 -0
  361. package/dist/wire/in/cli.js +106 -0
  362. package/dist/wire/in/coerce.js +6 -0
  363. package/dist/wire/in/common.js +17 -0
  364. package/dist/wire/in/credit-cards.js +16 -0
  365. package/dist/wire/in/currency-rates.js +8 -0
  366. package/dist/wire/in/period.js +7 -0
  367. package/dist/wire/in/recurring.js +6 -0
  368. package/dist/wire/in/settings.js +5 -0
  369. package/dist/wire/in/summary.js +5 -0
  370. package/dist/wire/in/tags.js +2 -0
  371. package/dist/wire/in/transactions.js +31 -0
  372. package/dist/wire/out/bills.js +9 -0
  373. package/dist/wire/out/budgets.js +10 -0
  374. package/dist/wire/out/client-config.js +2 -0
  375. package/dist/wire/out/common.js +4 -0
  376. package/dist/wire/out/credit-cards.js +15 -0
  377. package/dist/wire/out/currency-rates.js +11 -0
  378. package/dist/wire/out/errors.js +58 -0
  379. package/dist/wire/out/recurring.js +6 -0
  380. package/dist/wire/out/status.js +10 -0
  381. package/dist/wire/out/summary.js +9 -0
  382. package/dist/wire/out/transactions.js +52 -0
  383. package/drizzle/0000_futuristic_umar.sql +124 -0
  384. package/drizzle/0001_fts5_search.sql +23 -0
  385. package/drizzle/0002_rename_graph_to_history.sql +7 -0
  386. package/drizzle/0003_lyrical_hairball.sql +2 -0
  387. package/drizzle/0004_misty_ikaris.sql +7 -0
  388. package/drizzle/0005_credit-liability-accounts.sql +14 -0
  389. package/drizzle/0006_smart_aqueduct.sql +1 -0
  390. package/drizzle/0007_add_dashboards.sql +5 -0
  391. package/drizzle/0008_yummy_madripoor.sql +1 -0
  392. package/drizzle/0009_version_groundwork.sql +9 -0
  393. package/drizzle/0010_category_merchant_association_cascade.sql +16 -0
  394. package/drizzle/0011_dashboard_id_normalization.sql +16 -0
  395. package/drizzle/0012_hot_the_spike.sql +12 -0
  396. package/drizzle/0013_recurring_rules_merchant.sql +1 -0
  397. package/drizzle/0014_dashboard_source_discriminator.sql +17 -0
  398. package/drizzle/0015_currencies_decimals.sql +1 -0
  399. package/drizzle/0016_unusual_zaran.sql +13 -0
  400. package/drizzle/0017_premium_blur.sql +1 -0
  401. package/drizzle/0018_auth_identity.sql +39 -0
  402. package/drizzle/0019_access_tokens.sql +16 -0
  403. package/drizzle/0020_stdio_sign_in.sql +27 -0
  404. package/drizzle/0021_tenancy_data.sql +289 -0
  405. package/drizzle/0022_user_management.sql +17 -0
  406. package/drizzle/0023_instance_settings_row.sql +2 -0
  407. package/drizzle/0024_credentials_changed_at.sql +2 -0
  408. package/drizzle/0025_instance_kind.sql +2 -0
  409. package/drizzle/0026_demo_seeded_at.sql +2 -0
  410. package/drizzle/0027_demo_country.sql +2 -0
  411. package/drizzle/0028_reset_sign_ins.sql +2 -0
  412. package/drizzle/meta/0000_snapshot.json +894 -0
  413. package/drizzle/meta/0003_snapshot.json +910 -0
  414. package/drizzle/meta/0004_snapshot.json +951 -0
  415. package/drizzle/meta/0005_snapshot.json +991 -0
  416. package/drizzle/meta/0006_snapshot.json +998 -0
  417. package/drizzle/meta/0007_snapshot.json +1029 -0
  418. package/drizzle/meta/0008_snapshot.json +1049 -0
  419. package/drizzle/meta/0009_snapshot.json +1121 -0
  420. package/drizzle/meta/0010_snapshot.json +1121 -0
  421. package/drizzle/meta/0011_snapshot.json +1136 -0
  422. package/drizzle/meta/0012_snapshot.json +1227 -0
  423. package/drizzle/meta/0013_snapshot.json +1247 -0
  424. package/drizzle/meta/0014_snapshot.json +1267 -0
  425. package/drizzle/meta/0015_snapshot.json +1275 -0
  426. package/drizzle/meta/0016_snapshot.json +1371 -0
  427. package/drizzle/meta/0017_snapshot.json +1392 -0
  428. package/drizzle/meta/0018_snapshot.json +1603 -0
  429. package/drizzle/meta/0019_snapshot.json +1713 -0
  430. package/drizzle/meta/0020_snapshot.json +1904 -0
  431. package/drizzle/meta/0021_snapshot.json +2186 -0
  432. package/drizzle/meta/0022_snapshot.json +2311 -0
  433. package/drizzle/meta/0023_snapshot.json +2311 -0
  434. package/drizzle/meta/0024_snapshot.json +2318 -0
  435. package/drizzle/meta/0025_snapshot.json +2326 -0
  436. package/drizzle/meta/0026_snapshot.json +2333 -0
  437. package/drizzle/meta/0027_snapshot.json +2340 -0
  438. package/drizzle/meta/0028_snapshot.json +2340 -0
  439. package/drizzle/meta/_journal.json +209 -0
  440. package/package.json +106 -4
  441. package/skills/dashboard-building/SKILL.md +201 -0
  442. package/skills/patty-tour/SKILL.md +34 -0
  443. package/ui/app.css +758 -0
  444. package/ui/app.js +543 -0
  445. package/ui/connect-result.html +16 -0
  446. package/ui/connect.html +53 -0
  447. package/ui/dashboards/accounts.html +3189 -0
  448. package/ui/dashboards/budget.html +1734 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2475 -0
  452. package/ui/dashboards/dashboards.html +839 -0
  453. package/ui/dashboards/overview.html +2405 -0
  454. package/ui/dashboards/pending.html +2973 -0
  455. package/ui/dashboards/projections.html +2528 -0
  456. package/ui/dashboards/tags.html +1365 -0
  457. package/ui/invite.html +44 -0
  458. package/ui/login.html +26 -0
  459. package/ui/money.js +175 -0
  460. package/ui/setup.html +29 -0
  461. package/ui/shell.html +96 -0
  462. package/ui/token-created.html +24 -0
  463. package/ui/tokens.html +58 -0
  464. package/ui/user-invited.html +27 -0
  465. package/ui/users.html +60 -0
@@ -0,0 +1,30 @@
1
+ import { ToolName } from '../tool-name.js';
2
+ import { z } from 'zod';
3
+ import { getSpendingSummary } from '../../../controllers/summary.js';
4
+ import { CurrencyCode } from '../../../models/money.js';
5
+ import { defineTool } from '../definition.js';
6
+ import { json } from '../respond.js';
7
+ import { READ_ONLY } from '../annotations.js';
8
+ const getSpendingSummaryDescription = 'Income, expenses, balance and per-category totals for a month — ' +
9
+ 'grouped per currency (BRL/USD are never mixed). Optional displayCurrency adds a top-level ' +
10
+ 'converted block: a read-time grand total of expenses across currencies, converted against ' +
11
+ 'currency_rates (as_of-stamped, stale-flagged; a currency with no rate to displayCurrency is ' +
12
+ 'listed in converted.excluded and left out of the total, never fabricated). Per-currency lines ' +
13
+ 'are unaffected either way.';
14
+ const getSpendingSummaryTool = defineTool({
15
+ name: ToolName.enum.get_spending_summary,
16
+ config: {
17
+ annotations: READ_ONLY,
18
+ title: 'Get spending summary',
19
+ description: getSpendingSummaryDescription,
20
+ inputSchema: {
21
+ month: z.number().int().min(1).max(12),
22
+ year: z.number().int().min(2000).max(2100),
23
+ displayCurrency: CurrencyCode.optional().describe('Also return a converted grand total of expenses in this currency'),
24
+ },
25
+ },
26
+ handle: async (args, { deps }) => {
27
+ return json(await getSpendingSummary(deps, args, args.displayCurrency));
28
+ },
29
+ });
30
+ export const summaryTools = [getSpendingSummaryTool];
@@ -0,0 +1,83 @@
1
+ import { ToolName } from '../tool-name.js';
2
+ import { getPreferences, setBaseCurrency, setLocale } from '../../../controllers/settings.js';
3
+ import { getStatus } from '../../../controllers/status.js';
4
+ import { Locale, LocaleSource } from '../../../models/locale.js';
5
+ import { CurrencyCode } from '../../../models/money.js';
6
+ import * as settingsAdapters from '../../../adapters/settings.js';
7
+ import { defineTool } from '../definition.js';
8
+ import { fromResult, json } from '../respond.js';
9
+ import { MUTATING, READ_ONLY } from '../annotations.js';
10
+ const setLocaleDescription = 'Set the display language for default categories (en/es/pt). The AI agent should call this ' +
11
+ 'when it detects the user\'s language from conversation — use source "inferred". ' +
12
+ 'When the user explicitly requests a locale change, use source "explicit". ' +
13
+ 'GUARDRAILS: (1) Anti-churn — only switch on a clear, sustained language change, not on ' +
14
+ 'isolated foreign words, merchant names, or proper nouns. (2) Respect explicit — if the ' +
15
+ 'current locale_source is "explicit", do not auto-switch with source "inferred"; the user ' +
16
+ 'must explicitly request the change. Use get_preferences to check the current locale and source.';
17
+ const setLocaleTool = defineTool({
18
+ name: ToolName.enum.set_locale,
19
+ config: {
20
+ annotations: MUTATING,
21
+ title: 'Set locale',
22
+ description: setLocaleDescription,
23
+ inputSchema: {
24
+ locale: Locale,
25
+ source: LocaleSource.exclude([LocaleSource.enum.default]),
26
+ },
27
+ },
28
+ handle: async (args, { deps, runEffects, resetLocale }) => {
29
+ const flow = () => setLocale(deps, args).map(settingsAdapters.outcomeToDb);
30
+ const result = await runEffects(flow);
31
+ if (result.isOk())
32
+ resetLocale();
33
+ return fromResult(result);
34
+ },
35
+ });
36
+ const getPreferencesDescription = 'Returns the stored locale preference, locale_source, and the resolved base currency. Use this to ' +
37
+ 'check whether the user set the locale explicitly before attempting an inferred switch. Note: the ' +
38
+ 'PATTY_LOCALE env var can override the effective display locale used by list_categories; ' +
39
+ 'this tool reports the stored preference, not the effective override. base_currency is either an ' +
40
+ 'explicit override (set_base_currency) or derived from locale (pt→BRL, en/es→USD) when unset.';
41
+ const getPreferencesTool = defineTool({
42
+ name: ToolName.enum.get_preferences,
43
+ config: {
44
+ annotations: READ_ONLY,
45
+ title: 'Get user preferences',
46
+ description: getPreferencesDescription,
47
+ inputSchema: {},
48
+ },
49
+ handle: async (_args, { deps }) => {
50
+ return json(await getPreferences(deps));
51
+ },
52
+ });
53
+ const setBaseCurrencyDescription = 'Set the explicit base currency — the default target for future read-time valuation (ADR-026). ' +
54
+ "Unset, it's derived from locale (pt→BRL, en/es→USD); this tool overrides that derivation. " +
55
+ 'Use get_preferences to check the currently resolved value.';
56
+ const setBaseCurrencyTool = defineTool({
57
+ name: ToolName.enum.set_base_currency,
58
+ config: {
59
+ annotations: MUTATING,
60
+ title: 'Set base currency',
61
+ description: setBaseCurrencyDescription,
62
+ inputSchema: { baseCurrency: CurrencyCode },
63
+ },
64
+ handle: async (args, { deps, runEffects }) => {
65
+ const flow = () => setBaseCurrency(deps, args).map(settingsAdapters.outcomeToDb);
66
+ return fromResult(await runEffects(flow));
67
+ },
68
+ });
69
+ const getStatusDescription = 'Returns server name, version, database reachability, and active locale. ' +
70
+ 'A convenience for tool-only callers (the AI agent / chat user) — complements the ' +
71
+ 'protocol-native initialize serverInfo (version) and ping (liveness), which are not ' +
72
+ 'accessible via tools.';
73
+ const getStatusTool = defineTool({
74
+ name: ToolName.enum.get_status,
75
+ config: {
76
+ annotations: READ_ONLY,
77
+ title: 'Get server status',
78
+ description: getStatusDescription,
79
+ inputSchema: {},
80
+ },
81
+ handle: async (_args, { deps }, { version }) => json(await getStatus(deps, version)),
82
+ });
83
+ export const systemTools = [setLocaleTool, getPreferencesTool, setBaseCurrencyTool, getStatusTool];
@@ -0,0 +1,48 @@
1
+ import { ToolName } from '../tool-name.js';
2
+ import { z } from 'zod';
3
+ import { createTag, deleteTag, listTags } from '../../../controllers/tags.js';
4
+ import { CreateTagSchema } from '../../../wire/in/tags.js';
5
+ import * as tagAdapters from '../../../adapters/tags.js';
6
+ import { defineTool } from '../definition.js';
7
+ import { fromResult, json } from '../respond.js';
8
+ import { MUTATING, READ_ONLY } from '../annotations.js';
9
+ const listTagsTool = defineTool({
10
+ name: ToolName.enum.list_tags,
11
+ config: {
12
+ annotations: READ_ONLY,
13
+ title: 'List tags',
14
+ description: 'List all tags.',
15
+ inputSchema: {},
16
+ },
17
+ handle: async (_args, { deps }) => {
18
+ return json(await listTags(deps));
19
+ },
20
+ });
21
+ const createTagDescription = 'Create a tag. Tags can be attached to transactions to label them ' + '(e.g. "work", "travel", "reembolsável").';
22
+ const createTagTool = defineTool({
23
+ name: ToolName.enum.create_tag,
24
+ config: {
25
+ annotations: MUTATING,
26
+ title: 'Create tag',
27
+ description: createTagDescription,
28
+ inputSchema: CreateTagSchema.shape,
29
+ },
30
+ handle: async (args, { deps, runEffects }) => {
31
+ const flow = () => createTag(deps, args.name).map(tagAdapters.outcomeToDb);
32
+ return fromResult(await runEffects(flow));
33
+ },
34
+ });
35
+ const deleteTagTool = defineTool({
36
+ name: ToolName.enum.delete_tag,
37
+ config: {
38
+ annotations: MUTATING,
39
+ title: 'Delete tag',
40
+ description: 'Delete a tag by id. Removes the tag and all its associations with transactions.',
41
+ inputSchema: { id: z.string().min(1) },
42
+ },
43
+ handle: async (args, { deps, runEffects }) => {
44
+ const flow = () => deleteTag(deps, args.id).map(tagAdapters.outcomeToDb);
45
+ return fromResult(await runEffects(flow));
46
+ },
47
+ });
48
+ export const tagTools = [listTagsTool, createTagTool, deleteTagTool];
@@ -0,0 +1,53 @@
1
+ import { ToolName } from '../tool-name.js';
2
+ import { confirmTransaction } from '../../../controllers/transaction/core.js';
3
+ import { searchTransactions } from '../../../controllers/transaction/read.js';
4
+ import { SortDirection } from '../../../models/page.js';
5
+ import { ConfirmTransactionSchema, SearchTransactionsSchema, TransactionSortField, } from '../../../models/transaction.js';
6
+ import { outcomeToDb } from '../../../adapters/transactions.js';
7
+ import { defineTool } from '../definition.js';
8
+ import { fromResult } from '../respond.js';
9
+ import { MUTATING, READ_ONLY } from '../annotations.js';
10
+ const confirmTransactionDescription = 'Mark a pending transaction as effective (cleared). ' +
11
+ 'Pending transactions are excluded from balances and spending summaries; confirming one makes it count. ' +
12
+ 'Optionally correct amount/date in the same call — account/card movements only, rejected for a ' +
13
+ 'transfer/bill-payment (a plain status-only confirm of one is still fine). The resolved date (the ' +
14
+ 'given date, or the existing date if omitted) must not be in the future. ' +
15
+ 'If the transaction is already effective, this is a no-op.';
16
+ const confirmTransactionTool = defineTool({
17
+ name: ToolName.enum.confirm_transaction,
18
+ config: {
19
+ annotations: MUTATING,
20
+ title: 'Confirm (clear) a pending transaction',
21
+ description: confirmTransactionDescription,
22
+ inputSchema: ConfirmTransactionSchema.shape,
23
+ },
24
+ handle: async (args, { deps, runEffects }) => {
25
+ const flow = () => confirmTransaction(deps, args).map(outcomeToDb);
26
+ return fromResult(await runEffects(flow));
27
+ },
28
+ });
29
+ const searchTransactionsDescription = 'Search transactions by period (month/year or from/to), type (including transfers), ' +
30
+ 'category/account name, or free text. With an account filter this is the full account ' +
31
+ 'statement (extrato): expenses, income, and transfers in either direction. Returns a page ' +
32
+ '`{ items, nextCursor?, total? }` (ADR-014) — pass the previous `nextCursor` back as `cursor` ' +
33
+ 'to keep walking; `nextCursor` is absent on the last page. `sort`/`dir` must stay the same ' +
34
+ 'across a walk (they are bound to the cursor); set `includeTotal: true` on the first call ' +
35
+ 'only if you need the total count of matching transactions.';
36
+ const searchTransactionsTool = defineTool({
37
+ name: ToolName.enum.search_transactions,
38
+ config: {
39
+ annotations: READ_ONLY,
40
+ title: 'Search transactions',
41
+ description: searchTransactionsDescription,
42
+ inputSchema: {
43
+ ...SearchTransactionsSchema.shape,
44
+ limit: SearchTransactionsSchema.shape.limit.optional().default(50),
45
+ sort: SearchTransactionsSchema.shape.sort.optional().default(TransactionSortField.enum.date),
46
+ dir: SearchTransactionsSchema.shape.dir.optional().default(SortDirection.enum.desc),
47
+ },
48
+ },
49
+ handle: async (args, { deps }) => {
50
+ return fromResult(await searchTransactions(deps, args));
51
+ },
52
+ });
53
+ export const transactionTools = [confirmTransactionTool, searchTransactionsTool];
@@ -0,0 +1,28 @@
1
+ import { ToolName } from '../tool-name.js';
2
+ import { createTransfer } from '../../../controllers/account/transfer.js';
3
+ import { TransactionSource } from '../../../models/transaction.js';
4
+ import { CreateTransferSchema } from '../../../wire/in/accounts.js';
5
+ import { outcomeToDb } from '../../../adapters/transactions.js';
6
+ import { defineTool } from '../definition.js';
7
+ import { fromResult } from '../respond.js';
8
+ import { MUTATING } from '../annotations.js';
9
+ const createTransferDescription = 'Move value between two accounts (e.g. conta corrente → investimentos). Creates a transaction ' +
10
+ "with type 'transfer' (FROM + TO accounts): debits one balance, credits the other, never appears " +
11
+ 'in spending summaries, and shows in both account histories (search_transactions). Both accounts ' +
12
+ 'must share the same currency (FX not available yet). Idempotent automatically — a repeat call with ' +
13
+ 'the same from/to/description/date/amount is deduped; pass discriminator to record a genuinely ' +
14
+ 'separate transfer that would otherwise look identical.';
15
+ const createTransferTool = defineTool({
16
+ name: ToolName.enum.create_transfer,
17
+ config: {
18
+ annotations: MUTATING,
19
+ title: 'Transfer between accounts',
20
+ description: createTransferDescription,
21
+ inputSchema: CreateTransferSchema.shape,
22
+ },
23
+ handle: async (args, { deps, runEffects }) => {
24
+ const flow = () => createTransfer(deps, args, TransactionSource.enum.mcp).map(outcomeToDb);
25
+ return fromResult(await runEffects(flow));
26
+ },
27
+ });
28
+ export const transferTools = [createTransferTool];
@@ -0,0 +1,87 @@
1
+ import { DEMO_SERVER_NAME } from '../../models/demo/core.js';
2
+ import { InstanceKind } from '../../models/instance.js';
3
+ import { Locale } from '../../models/locale.js';
4
+ import { NPX_COMMAND, PRODUCT_NAME } from '../../models/package.js';
5
+ import { ToolName } from './tool-name.js';
6
+ const T = ToolName.enum;
7
+ const SETUP_DEMO = `${NPX_COMMAND} setup <client> --demo`;
8
+ const REMOVE_DEMO = `${NPX_COMMAND} setup <client> --remove-demo`;
9
+ const DEMO_COMMAND = `${NPX_COMMAND} demo`;
10
+ const TOUR_COPY = {
11
+ [Locale.enum.en]: {
12
+ intro: `You are guiding the person through a short tour of ${PRODUCT_NAME} on its sample data. Do the six steps in order, one ` +
13
+ 'at a time: run the tools, tell them what you found in a few sentences, and wait for them before the next step. ' +
14
+ `Group every figure by currency and never sum across currencies.`,
15
+ balances: `What are my balances? Call ${T.get_account_balances} (accounts and cards, and the total converted to the base currency).`,
16
+ lastMonth: `Where did my money go last month? Call ${T.get_spending_summary} for last month, by category.`,
17
+ budgets: `Am I over budget? Call ${T.get_budget_status} for the current month, counting what is still pending.`,
18
+ importStep: (statement) => `Import this statement. Show the lines below, import them into the checking account with ${T.import_account_statement}, ` +
19
+ `and walk through the result: what was classified, and the line flagged needs_review.\n${statement}`,
20
+ income: 'income',
21
+ trip: (destination) => `Tag everything from my trip to ${destination} as travel, then build me a travel dashboard. The trip is in the ` +
22
+ `data but untagged and spread over several categories and accounts: find it with ${T.search_transactions} by dates ` +
23
+ `and descriptions, create the tag with ${T.create_tag}, tag the purchases, then build the dashboard with ${T.save_dashboard}.`,
24
+ closing: `Ready for your own data? Tell them how to install ${PRODUCT_NAME} for real, and that this demo is sample data. To remove ` +
25
+ `the demo from their AI client: \`${REMOVE_DEMO}\`.`,
26
+ step: (n) => `Step ${n}`,
27
+ notDemo: `The tour is for the ${PRODUCT_NAME} demo, and this server holds real data, so do not run it here. Tell the person to ` +
28
+ `start the demo with \`${DEMO_COMMAND}\` and to add it to their AI client with \`${SETUP_DEMO}\`, then run the ` +
29
+ `tour prompt on the \`${DEMO_SERVER_NAME}\` server.`,
30
+ },
31
+ [Locale.enum.pt]: {
32
+ intro: `Você vai guiar a pessoa por um tour curto do ${PRODUCT_NAME} com dados de exemplo. Faça os seis passos em ordem, um ` +
33
+ 'de cada vez: execute as ferramentas, conte em poucas frases o que encontrou e espere a pessoa antes do passo ' +
34
+ 'seguinte. Agrupe todo valor por moeda e nunca some moedas diferentes.',
35
+ balances: `Quais são meus saldos? Chame ${T.get_account_balances} (contas e cartões, e o total convertido para a moeda base).`,
36
+ lastMonth: `Para onde foi meu dinheiro no mês passado? Chame ${T.get_spending_summary} do mês passado, por categoria.`,
37
+ budgets: `Estou acima do orçamento? Chame ${T.get_budget_status} do mês atual, contando o que ainda está pendente.`,
38
+ importStep: (statement) => `Importe este extrato. Mostre as linhas abaixo, importe-as na conta corrente com ${T.import_account_statement} ` +
39
+ `e comente o resultado: o que foi classificado e a linha marcada como needs_review.\n${statement}`,
40
+ income: 'receita',
41
+ trip: (destination) => `Marque tudo da minha viagem a ${destination} como viagem e monte um dashboard de viagem. A viagem está nos ` +
42
+ `dados, sem tag e espalhada por várias categorias e contas: encontre-a com ${T.search_transactions} por datas ` +
43
+ `e descrições, crie a tag com ${T.create_tag}, marque as compras e monte o dashboard com ${T.save_dashboard}.`,
44
+ closing: `Pronto para os seus dados? Explique como instalar o ${PRODUCT_NAME} de verdade e que esta demo é de exemplo. Para ` +
45
+ `remover a demo do cliente de IA: \`${REMOVE_DEMO}\`.`,
46
+ step: (n) => `Passo ${n}`,
47
+ notDemo: `O tour é da demo do ${PRODUCT_NAME} e este servidor guarda dados reais, então não o execute aqui. Diga à pessoa para ` +
48
+ `iniciar a demo com \`${DEMO_COMMAND}\` e adicioná-la ao cliente de IA com \`${SETUP_DEMO}\`, e então rodar o ` +
49
+ `prompt tour no servidor \`${DEMO_SERVER_NAME}\`.`,
50
+ },
51
+ [Locale.enum.es]: {
52
+ intro: `Vas a guiar a la persona por un tour corto de ${PRODUCT_NAME} con datos de ejemplo. Haz los seis pasos en orden, de ` +
53
+ 'uno en uno: ejecuta las herramientas, cuenta en pocas frases lo que encontraste y espera a la persona antes del ' +
54
+ 'siguiente paso. Agrupa cada cifra por moneda y nunca sumes monedas distintas.',
55
+ balances: `¿Cuáles son mis saldos? Llama a ${T.get_account_balances} (cuentas y tarjetas, y el total convertido a la moneda base).`,
56
+ lastMonth: `¿A dónde se fue mi dinero el mes pasado? Llama a ${T.get_spending_summary} del mes pasado, por categoría.`,
57
+ budgets: `¿Me pasé del presupuesto? Llama a ${T.get_budget_status} del mes actual, contando lo que sigue pendiente.`,
58
+ importStep: (statement) => `Importa este extracto. Muestra las líneas de abajo, impórtalas en la cuenta corriente con ${T.import_account_statement} ` +
59
+ `y comenta el resultado: lo que se clasificó y la línea marcada como needs_review.\n${statement}`,
60
+ income: 'ingreso',
61
+ trip: (destination) => `Etiqueta todo lo de mi viaje a ${destination} como viaje y arma un dashboard de viaje. El viaje está en los ` +
62
+ `datos, sin etiqueta y repartido en varias categorías y cuentas: encuéntralo con ${T.search_transactions} por fechas ` +
63
+ `y descripciones, crea la etiqueta con ${T.create_tag}, etiqueta las compras y arma el dashboard con ${T.save_dashboard}.`,
64
+ closing: `¿Listo para tus datos? Explica cómo instalar ${PRODUCT_NAME} de verdad y que esta demo es de ejemplo. Para quitar la ` +
65
+ `demo del cliente de IA: \`${REMOVE_DEMO}\`.`,
66
+ step: (n) => `Paso ${n}`,
67
+ notDemo: `El tour es de la demo de ${PRODUCT_NAME} y este servidor guarda datos reales, así que no lo ejecutes aquí. Dile a la ` +
68
+ `persona que inicie la demo con \`${DEMO_COMMAND}\` y la agregue a su cliente de IA con \`${SETUP_DEMO}\`, y ` +
69
+ `luego ejecute el prompt tour en el servidor \`${DEMO_SERVER_NAME}\`.`,
70
+ },
71
+ };
72
+ const statementLine = (income) => (line) => `${line.date} · ${line.description} · ${line.amount}${line.income ? ` (${income})` : ''}`;
73
+ export const tourPromptText = (context) => {
74
+ const copy = TOUR_COPY[context.locale];
75
+ if (context.kind === InstanceKind.enum.standard)
76
+ return copy.notDemo;
77
+ const statement = context.statement.map(statementLine(copy.income)).join('\n');
78
+ const steps = [
79
+ copy.balances,
80
+ copy.lastMonth,
81
+ copy.budgets,
82
+ copy.importStep(statement),
83
+ copy.trip(context.destination),
84
+ copy.closing,
85
+ ];
86
+ return [copy.intro, ...steps.map((text, index) => `${copy.step(index + 1)}. ${text}`)].join('\n\n');
87
+ };
@@ -0,0 +1,79 @@
1
+ import { err, ok } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { localizeAccountType } from './localize.js';
4
+ import { accountErrors, AccountType, ACCOUNT_OWNED_TYPES, } from '../models/account.js';
5
+ import { UNCLASSIFIED, TransactionType, } from '../models/transaction.js';
6
+ import { defaultStatusFor, deriveIdempotencyKey, isTransfer } from './transaction.js';
7
+ export const filterByType = (type) => (a) => !type || a.type === type;
8
+ export const assertNonCreditType = (type) => type !== AccountType.enum.credit;
9
+ export const hasNoTransactions = (refs) => refs.transactions === 0;
10
+ export const hasNoRecurring = (refs) => refs.recurring === 0;
11
+ export const hasNoCards = (refs) => refs.cards === 0;
12
+ export const isUnreferenced = (refs) => hasNoTransactions(refs) && hasNoRecurring(refs) && hasNoCards(refs);
13
+ export const isRename = (currentName, newName) => newName !== undefined && newName.toLowerCase() !== currentName.toLowerCase();
14
+ export const changesPinnedField = (input) => R.isDefined(input.type) || R.isDefined(input.currency);
15
+ export const guardPinnedFields = (refs, input) => {
16
+ const isChangingType = R.isDefined(input.type);
17
+ const isChangingCurrency = R.isDefined(input.currency);
18
+ const violations = [
19
+ [isChangingType && !hasNoTransactions(refs), accountErrors.typeImmutable(refs.transactions)],
20
+ [isChangingCurrency && !hasNoTransactions(refs), accountErrors.currencyImmutableTransactions(refs.transactions)],
21
+ [isChangingCurrency && !hasNoRecurring(refs), accountErrors.currencyImmutableRecurring],
22
+ [isChangingCurrency && !hasNoCards(refs), accountErrors.currencyImmutableCards],
23
+ ];
24
+ const violated = R.find(violations, ([isViolated]) => isViolated);
25
+ return violated ? err(violated[1]) : ok(undefined);
26
+ };
27
+ export const mergeAccountPatch = (raw, input) => ({
28
+ ...raw,
29
+ name: input.newName ?? raw.name,
30
+ initialBalance: input.initialBalance ?? raw.initialBalance,
31
+ type: input.type ?? raw.type,
32
+ currency: input.currency ?? raw.currency,
33
+ });
34
+ export const areDifferentAccounts = (a, b) => a.id !== b.id;
35
+ export const assertCurrencyMatch = (a, b) => a.currency === b.currency;
36
+ export const isAccountOwnedType = (type) => ACCOUNT_OWNED_TYPES.has(type);
37
+ const wouldBeTransfer = (existing, input) => (input.type ?? existing.type) === TransactionType.enum.transfer;
38
+ const hasCategoryInput = (input) => !!(input.category || input.subCategory);
39
+ export const guardTransferMutability = (existing, input) => {
40
+ if (isTransfer(existing) && input.type)
41
+ return err(accountErrors.transferTypeImmutable);
42
+ if (wouldBeTransfer(existing, input) && hasCategoryInput(input))
43
+ return err(accountErrors.transferCategoryRejected);
44
+ return ok(undefined);
45
+ };
46
+ const _withTypeLabel = (account, locale) => ({
47
+ ...account,
48
+ typeLabel: localizeAccountType(account.type, locale),
49
+ });
50
+ export function withTypeLabel(...args) {
51
+ return R.purry(_withTypeLabel, args);
52
+ }
53
+ export const planTransfer = (facts) => {
54
+ const { input, from, to } = facts;
55
+ const date = input.date ?? facts.today;
56
+ const entity = {
57
+ id: facts.id,
58
+ description: input.description ?? `Transferência: ${from.name} → ${to.name}`,
59
+ amount: input.amount,
60
+ type: TransactionType.enum.transfer,
61
+ status: input.status ?? defaultStatusFor(date, facts.today),
62
+ date,
63
+ currency: from.currency,
64
+ source: facts.source,
65
+ classification: UNCLASSIFIED,
66
+ refs: { accountId: from.id, toAccountId: to.id },
67
+ };
68
+ const idempotencyKey = deriveIdempotencyKey({
69
+ fundingSourceId: from.id,
70
+ counterpartyId: to.id,
71
+ type: entity.type,
72
+ currency: entity.currency,
73
+ date,
74
+ // Not entity.description: its placeholder embeds account names, so a rename would miss a real duplicate.
75
+ description: input.description ?? '',
76
+ amount: entity.amount,
77
+ }, facts.decimals, input.discriminator);
78
+ return { entity, idempotencyKey };
79
+ };
@@ -0,0 +1,37 @@
1
+ import * as R from 'remeda';
2
+ import { localizeCategoryName } from './category.js';
3
+ import { roundMoney, roundToDecimals } from './money.js';
4
+ import { AggregateGroupBy, AggregateMetric, AggregateSort, UNCATEGORIZED_KEY, uncategorizedLabels, UNKNOWN_KEY, unknownLabels, } from '../models/aggregate.js';
5
+ const resolveKey = (row, groupBy) => {
6
+ if (R.isNonNullish(row.key))
7
+ return row.key;
8
+ return groupBy === AggregateGroupBy.enum.category ? UNCATEGORIZED_KEY : UNKNOWN_KEY;
9
+ };
10
+ const resolveLabel = (row, groupBy, locale) => {
11
+ if (!R.isNonNullish(row.key)) {
12
+ return groupBy === AggregateGroupBy.enum.category ? uncategorizedLabels[locale] : unknownLabels[locale];
13
+ }
14
+ if (groupBy === AggregateGroupBy.enum.category) {
15
+ return localizeCategoryName(row.label, row.labelNames, locale) ?? resolveKey(row, groupBy);
16
+ }
17
+ return row.label ?? resolveKey(row, groupBy);
18
+ };
19
+ const pct = (value, total) => (total === 0 ? 0 : roundMoney((value / total) * 100));
20
+ export const shapeAggregateResult = (rows, groupBy, sort, locale, decimalsFor, limit) => R.pipe(rows, R.groupBy((r) => r.currency), R.entries(), R.map(([currency, currencyRows]) => {
21
+ const code = currency;
22
+ const decimals = decimalsFor(code);
23
+ const total = roundToDecimals(R.sumBy(currencyRows, (r) => r.value), decimals);
24
+ const sorted = sort === AggregateSort.enum.asc
25
+ ? R.sortBy(currencyRows, (r) => r.value)
26
+ : R.sortBy(currencyRows, [(r) => r.value, 'desc']);
27
+ const limited = R.isNonNullish(limit) ? R.take(sorted, limit) : sorted;
28
+ const shapedRows = limited.map((r) => ({
29
+ key: resolveKey(r, groupBy),
30
+ label: resolveLabel(r, groupBy, locale),
31
+ value: roundToDecimals(r.value, decimals),
32
+ count: r.count,
33
+ pct: pct(r.value, total),
34
+ }));
35
+ return { currency: code, total, rows: shapedRows };
36
+ }), R.sortBy((b) => b.currency));
37
+ export const wantsDisplayConversion = (input) => R.isNonNullish(input.displayCurrency) && input.metric === AggregateMetric.enum.sum;
@@ -0,0 +1,35 @@
1
+ import { API_PATH_PREFIX, BEARER_HEADER, BEARER_METHOD_HEADER, BEARER_SCHEME, MCP_PATH, MCP_PRM_PATH, RESOURCE_NAME, } from '../../models/auth/bearer.js';
2
+ import { ALL_SCOPES } from '../../models/auth/scope.js';
3
+ import { isTokenShaped } from './token.js';
4
+ export const credentialOf = (authorization) => {
5
+ if (authorization === undefined)
6
+ return { kind: 'none' };
7
+ const token = BEARER_HEADER.exec(authorization)?.[1];
8
+ return token !== undefined && isTokenShaped(token) ? { kind: 'bearer', token } : { kind: 'malformed' };
9
+ };
10
+ export const acceptsBearer = (path) => [API_PATH_PREFIX, MCP_PATH].some((root) => path === root || path.startsWith(`${root}/`));
11
+ const quoted = (value) => `"${value.replace(/["\\]/g, '\\$&')}"`;
12
+ const param = (name, value) => `${name}=${quoted(value)}`;
13
+ const joinScopes = (scopes) => scopes.join(' ');
14
+ export const resourceMetadataUrl = (origin) => `${origin}${MCP_PRM_PATH}`;
15
+ export const bearerChallenge = (error, metadataUrl) => {
16
+ const metadata = metadataUrl === null ? [] : [param('resource_metadata', metadataUrl)];
17
+ switch (error.code) {
18
+ case 'unauthenticated':
19
+ return `${BEARER_SCHEME} ${[...metadata, param('scope', joinScopes(ALL_SCOPES))].join(', ')}`;
20
+ case 'invalid_token':
21
+ return `${BEARER_SCHEME} ${[param('error', error.code), ...metadata].join(', ')}`;
22
+ case 'insufficient_scope':
23
+ return `${BEARER_SCHEME} ${[param('error', error.code), param('scope', error.scope), ...metadata].join(', ')}`;
24
+ default: {
25
+ const _exhaustive = error;
26
+ throw new Error(`unmapped challenge: ${JSON.stringify(_exhaustive)}`);
27
+ }
28
+ }
29
+ };
30
+ export const protectedResourceMetadata = (origin) => ({
31
+ resource: `${origin}${MCP_PATH}`,
32
+ scopes_supported: [...ALL_SCOPES],
33
+ bearer_methods_supported: [BEARER_METHOD_HEADER],
34
+ resource_name: RESOURCE_NAME,
35
+ });
@@ -0,0 +1,126 @@
1
+ import * as R from 'remeda';
2
+ import { CLIENT_GRANT_TTL_MS, DEFAULT_SIGN_IN_DURATION, GrantChannel, GrantStatus, INVALID_REDEEM, MAX_SIGN_IN_DURATION_MS, RedeemKind, RedeemPlanKind, SIGN_IN_DURATION_MS, SignInDuration, } from '../../models/auth/grant.js';
3
+ import { WRITE_SCOPE } from '../../models/auth/scope.js';
4
+ import { SESSION_ONLY_LABEL, UNKNOWN_CLIENT_NAME } from '../../models/auth/sign-in.js';
5
+ import { AccessTokenKind, TOKEN_NAME_MAX_LENGTH, TokenAccess, } from '../../models/auth/token.js';
6
+ import { formatSetupCode, normalizeSetupCode } from './owner.js';
7
+ import { millis, toIso } from './time.js';
8
+ export const normalizeUserCode = normalizeSetupCode;
9
+ export const formatUserCode = formatSetupCode;
10
+ export const signInExpiry = (approvedAt, duration) => toIso(millis(approvedAt) + Math.min(SIGN_IN_DURATION_MS[duration], MAX_SIGN_IN_DURATION_MS));
11
+ export const persistsToKeychain = (duration) => duration !== SignInDuration.enum.session;
12
+ export const signInCapOf = (settings) => settings.maxSignInDuration;
13
+ export const withinCap = (duration, cap) => SIGN_IN_DURATION_MS[duration] <= SIGN_IN_DURATION_MS[cap];
14
+ export const clampToCap = (duration, cap) => withinCap(duration, cap) ? duration : cap;
15
+ export const durationAllowedFor = (channel, duration) => channel === GrantChannel.enum.stdio || duration !== SignInDuration.enum.session;
16
+ export const offeredDurations = (channel, cap) => R.filter(SignInDuration.options, (duration) => durationAllowedFor(channel, duration) && withinCap(duration, cap));
17
+ export const newGrant = (fields, now) => ({
18
+ id: fields.id,
19
+ deviceCodeHash: fields.deviceCodeHash,
20
+ userCode: fields.userCode,
21
+ clientName: fields.input.client.name,
22
+ clientVersion: fields.input.client.version,
23
+ profile: fields.input.profile,
24
+ channel: fields.input.channel,
25
+ hintAccess: fields.input.hint?.access ?? null,
26
+ hintDuration: fields.input.hint?.duration ?? null,
27
+ status: GrantStatus.enum.pending,
28
+ userId: null,
29
+ scopes: null,
30
+ duration: null,
31
+ createdAt: now.toISOString(),
32
+ approvedAt: null,
33
+ expiresAt: toIso(now.getTime() + CLIENT_GRANT_TTL_MS),
34
+ });
35
+ const isGrantExpired = (grant, now) => now.getTime() >= millis(grant.expiresAt);
36
+ export const isAnswerable = (grant, now) => grant !== null && grant.status === GrantStatus.enum.pending && !isGrantExpired(grant, now);
37
+ export const grantRequestOf = (grant) => ({
38
+ userCode: formatUserCode(grant.userCode),
39
+ clientName: grant.clientName,
40
+ clientVersion: grant.clientVersion,
41
+ profile: grant.profile,
42
+ channel: grant.channel,
43
+ createdAt: grant.createdAt,
44
+ expiresAt: grant.expiresAt,
45
+ });
46
+ export const approvedGrant = (grant, fields, now) => ({
47
+ ...grant,
48
+ status: GrantStatus.enum.approved,
49
+ userId: fields.userId,
50
+ scopes: [...fields.scopes],
51
+ duration: fields.duration,
52
+ approvedAt: now.toISOString(),
53
+ });
54
+ export const deniedGrant = (grant) => ({
55
+ ...grant,
56
+ status: GrantStatus.enum.denied,
57
+ });
58
+ export const redeemedGrant = (grant) => ({
59
+ ...grant,
60
+ status: GrantStatus.enum.redeemed,
61
+ });
62
+ export const expiredGrant = (grant) => ({
63
+ ...grant,
64
+ status: GrantStatus.enum.expired,
65
+ });
66
+ export const consentChoice = (grant, last, cap) => {
67
+ const lastAccess = last?.scopes
68
+ ? last.scopes.includes(WRITE_SCOPE)
69
+ ? TokenAccess.enum.write
70
+ : TokenAccess.enum.read
71
+ : undefined;
72
+ const duration = R.pipe([grant.hintDuration, last?.duration], R.filter((candidate) => candidate != null && durationAllowedFor(grant.channel, candidate)), R.first());
73
+ return {
74
+ access: grant.hintAccess ?? lastAccess ?? TokenAccess.enum.read,
75
+ duration: clampToCap(duration ?? DEFAULT_SIGN_IN_DURATION, cap),
76
+ };
77
+ };
78
+ const closedPlan = (grant, now) => {
79
+ if (grant.status === GrantStatus.enum.redeemed)
80
+ return INVALID_REDEEM;
81
+ if (grant.status === GrantStatus.enum.denied)
82
+ return { kind: RedeemPlanKind.enum.denied };
83
+ if (grant.status === GrantStatus.enum.expired)
84
+ return { kind: RedeemPlanKind.enum.expired, settle: null };
85
+ return isGrantExpired(grant, now) ? { kind: RedeemPlanKind.enum.expired, settle: expiredGrant(grant) } : null;
86
+ };
87
+ const openPlan = (grant) => {
88
+ if (grant.status === GrantStatus.enum.pending)
89
+ return { kind: RedeemPlanKind.enum.pending };
90
+ const { userId, scopes, duration, approvedAt } = grant;
91
+ return userId !== null && scopes !== null && duration !== null && approvedAt !== null
92
+ ? { kind: RedeemPlanKind.enum.mint, grant: { ...grant, userId, scopes, duration, approvedAt } }
93
+ : INVALID_REDEEM;
94
+ };
95
+ export const redeemPlan = (grant, now) => grant === null ? INVALID_REDEEM : (closedPlan(grant, now) ?? openPlan(grant));
96
+ export const signedIn = (token, entity, principal, duration) => ({
97
+ kind: RedeemKind.enum.signed_in,
98
+ token,
99
+ tokenId: entity.id,
100
+ scopes: entity.scopes,
101
+ principal,
102
+ duration,
103
+ expiresAt: entity.expiresAt,
104
+ });
105
+ export const newStdioSignIn = (fields, now) => ({
106
+ id: fields.id,
107
+ userId: fields.grant.userId,
108
+ kind: AccessTokenKind.enum.stdio,
109
+ clientName: fields.grant.clientName,
110
+ profile: fields.grant.profile,
111
+ name: `${fields.grant.clientName} (${fields.grant.profile})`.slice(0, TOKEN_NAME_MAX_LENGTH),
112
+ tokenHash: fields.tokenHash,
113
+ prefix: fields.prefix,
114
+ scopes: fields.grant.scopes,
115
+ createdAt: now.toISOString(),
116
+ lastUsedAt: null,
117
+ expiresAt: signInExpiry(fields.grant.approvedAt, fields.grant.duration),
118
+ revokedAt: null,
119
+ });
120
+ const consentMemoryKey = (grant) => JSON.stringify([grant.userId, grant.profile, grant.clientName]);
121
+ const newestApproval = (grants) => R.firstBy(grants, [(grant) => grant.approvedAt ?? '', 'desc'], [(grant) => grant.id, 'desc']);
122
+ export const supersededGrants = (redeemed) => R.pipe(redeemed, R.groupBy(consentMemoryKey), R.values(), R.filter(R.isDefined), R.flatMap((group) => {
123
+ const kept = newestApproval(group);
124
+ return group.filter((grant) => grant.id !== kept?.id);
125
+ }));
126
+ export const sessionOnlyLabel = (clientName) => clientName === UNKNOWN_CLIENT_NAME ? SESSION_ONLY_LABEL.unnamed : SESSION_ONLY_LABEL.named(clientName);
@@ -0,0 +1,10 @@
1
+ import { UserRole } from '../../models/auth/owner.js';
2
+ import { KEY_EXPORT_CONFIRMATION_ANSWER } from '../../models/auth/key-export.js';
3
+ import { hasCredentials } from './owner.js';
4
+ import { isActiveAdmin } from './users.js';
5
+ /** An administrator with a login exists. Until then there is no password to ask for. */
6
+ export const hasClaimedAdmin = (users) => users.some((user) => user.role === UserRole.enum.admin && hasCredentials(user));
7
+ export const findUserNamed = (users, username) => users.find((user) => user.username === username) ?? null;
8
+ /** Only an active administrator with a login may have the key written out. */
9
+ export const mayExportKey = (user) => isActiveAdmin(user);
10
+ export const isExportConfirmation = (answer) => answer.trim().toLowerCase() === KEY_EXPORT_CONFIRMATION_ANSWER;
@@ -0,0 +1,3 @@
1
+ import { DB_ID_LENGTH, SIGN_IN_ACCOUNT_PREFIX } from '../../models/auth/sign-in.js';
2
+ export const dbIdOf = (dbPathHash) => dbPathHash.slice(0, DB_ID_LENGTH);
3
+ export const keychainAccount = (profile, dbId) => [SIGN_IN_ACCOUNT_PREFIX, profile, dbId].join(':');